surf

surf browser, a WebKit based browser
git clone git://git.suckless.org/surf
Log | Files | Refs | README | LICENSE

surf.c (53160B)


      1 /* See LICENSE file for copyright and license details.
      2  *
      3  * To understand surf, start reading main().
      4  */
      5 #include <sys/file.h>
      6 #include <sys/socket.h>
      7 #include <sys/types.h>
      8 #include <sys/wait.h>
      9 #include <glib.h>
     10 #include <inttypes.h>
     11 #include <libgen.h>
     12 #include <limits.h>
     13 #include <pwd.h>
     14 #include <regex.h>
     15 #include <signal.h>
     16 #include <stdio.h>
     17 #include <stdlib.h>
     18 #include <string.h>
     19 #include <unistd.h>
     20 
     21 #include <gdk/gdk.h>
     22 #include <gdk/gdkkeysyms.h>
     23 #include <gdk/gdkx.h>
     24 #include <glib/gstdio.h>
     25 #include <gtk/gtk.h>
     26 #include <gtk/gtkx.h>
     27 #include <gcr/gcr.h>
     28 #include <JavaScriptCore/JavaScript.h>
     29 #include <webkit2/webkit2.h>
     30 #include <X11/X.h>
     31 #include <X11/Xatom.h>
     32 #include <glib.h>
     33 
     34 #include "arg.h"
     35 #include "common.h"
     36 
     37 #define LENGTH(x)               (sizeof(x) / sizeof(x[0]))
     38 #define CLEANMASK(mask)         (mask & (MODKEY|GDK_SHIFT_MASK))
     39 
     40 enum { AtomFind, AtomGo, AtomUri, AtomLast };
     41 
     42 enum {
     43 	OnDoc   = WEBKIT_HIT_TEST_RESULT_CONTEXT_DOCUMENT,
     44 	OnLink  = WEBKIT_HIT_TEST_RESULT_CONTEXT_LINK,
     45 	OnImg   = WEBKIT_HIT_TEST_RESULT_CONTEXT_IMAGE,
     46 	OnMedia = WEBKIT_HIT_TEST_RESULT_CONTEXT_MEDIA,
     47 	OnEdit  = WEBKIT_HIT_TEST_RESULT_CONTEXT_EDITABLE,
     48 	OnBar   = WEBKIT_HIT_TEST_RESULT_CONTEXT_SCROLLBAR,
     49 	OnSel   = WEBKIT_HIT_TEST_RESULT_CONTEXT_SELECTION,
     50 	OnAny   = OnDoc | OnLink | OnImg | OnMedia | OnEdit | OnBar | OnSel,
     51 };
     52 
     53 typedef enum {
     54 	AccessMicrophone,
     55 	AccessWebcam,
     56 	CaretBrowsing,
     57 	Certificate,
     58 	CookiePolicies,
     59 	DiskCache,
     60 	DefaultCharset,
     61 	DNSPrefetch,
     62 	Ephemeral,
     63 	FileURLsCrossAccess,
     64 	FontSize,
     65 	FrameFlattening,
     66 	Geolocation,
     67 	HideBackground,
     68 	Inspector,
     69 	Java,
     70 	JavaScript,
     71 	KioskMode,
     72 	LoadImages,
     73 	MediaManualPlay,
     74 	PreferredLanguages,
     75 	RunInFullscreen,
     76 	ScrollBars,
     77 	ShowIndicators,
     78 	SiteQuirks,
     79 	SmoothScrolling,
     80 	SpellChecking,
     81 	SpellLanguages,
     82 	StrictTLS,
     83 	Style,
     84 	WebGL,
     85 	ZoomLevel,
     86 	ParameterLast
     87 } ParamName;
     88 
     89 typedef union {
     90 	int i;
     91 	float f;
     92 	const void *v;
     93 } Arg;
     94 
     95 typedef struct {
     96 	Arg val;
     97 	int prio;
     98 } Parameter;
     99 
    100 typedef struct Client {
    101 	GtkWidget *win;
    102 	WebKitWebView *view;
    103 	WebKitWebInspector *inspector;
    104 	WebKitFindController *finder;
    105 	WebKitHitTestResult *mousepos;
    106 	GTlsCertificate *cert, *failedcert;
    107 	GTlsCertificateFlags tlserr;
    108 	Window xid;
    109 	guint64 pageid;
    110 	int progress, fullscreen, https, insecure, errorpage;
    111 	const char *title, *overtitle, *targeturi;
    112 	const char *needle;
    113 	struct Client *next;
    114 } Client;
    115 
    116 typedef struct {
    117 	guint mod;
    118 	guint keyval;
    119 	void (*func)(Client *c, const Arg *a);
    120 	const Arg arg;
    121 } Key;
    122 
    123 typedef struct {
    124 	unsigned int target;
    125 	unsigned int mask;
    126 	guint button;
    127 	void (*func)(Client *c, const Arg *a, WebKitHitTestResult *h);
    128 	const Arg arg;
    129 	unsigned int stopevent;
    130 } Button;
    131 
    132 typedef struct {
    133 	const char *uri;
    134 	Parameter config[ParameterLast];
    135 	regex_t re;
    136 } UriParameters;
    137 
    138 typedef struct {
    139 	char *regex;
    140 	char *file;
    141 	regex_t re;
    142 } SiteSpecific;
    143 
    144 /* Surf */
    145 static void die(const char *errstr, ...);
    146 static void usage(void);
    147 static void setup(void);
    148 static void sigchld(int unused);
    149 static void sighup(int unused);
    150 static char *buildfile(const char *path);
    151 static char *buildpath(const char *path);
    152 static char *untildepath(const char *path);
    153 static const char *getuserhomedir(const char *user);
    154 static const char *getcurrentuserhomedir(void);
    155 static Client *newclient(Client *c);
    156 static void loaduri(Client *c, const Arg *a);
    157 static const char *geturi(Client *c);
    158 static void setatom(Client *c, int a, const char *v);
    159 static const char *getatom(Client *c, int a);
    160 static void updatetitle(Client *c);
    161 static void gettogglestats(Client *c);
    162 static void getpagestats(Client *c);
    163 static WebKitCookieAcceptPolicy cookiepolicy_get(void);
    164 static char cookiepolicy_set(const WebKitCookieAcceptPolicy p);
    165 static void seturiparameters(Client *c, const char *uri, ParamName *params);
    166 static void setparameter(Client *c, int refresh, ParamName p, const Arg *a);
    167 static const char *getcert(const char *uri);
    168 static void setcert(Client *c, const char *file);
    169 static const char *getstyle(const char *uri);
    170 static void setstyle(Client *c, const char *file);
    171 static void runscript(Client *c);
    172 static void evalscript(Client *c, const char *jsstr, ...);
    173 static void updatewinid(Client *c);
    174 static void handleplumb(Client *c, const char *uri);
    175 static void newwindow(Client *c, const Arg *a, int noembed);
    176 static void spawn(Client *c, const Arg *a);
    177 static void msgext(Client *c, char type, const Arg *a);
    178 static void destroyclient(Client *c);
    179 static void cleanup(void);
    180 
    181 /* GTK/WebKit */
    182 static WebKitWebView *newview(Client *c, WebKitWebView *rv);
    183 static void initwebextensions(WebKitWebContext *wc, Client *c);
    184 static GtkWidget *createview(WebKitWebView *v, WebKitNavigationAction *a,
    185                              Client *c);
    186 static gboolean buttonreleased(GtkWidget *w, GdkEvent *e, Client *c);
    187 static GdkFilterReturn processx(GdkXEvent *xevent, GdkEvent *event,
    188                                 gpointer d);
    189 static gboolean winevent(GtkWidget *w, GdkEvent *e, Client *c);
    190 static gboolean readsock(GIOChannel *s, GIOCondition ioc, gpointer unused);
    191 static void showview(WebKitWebView *v, Client *c);
    192 static GtkWidget *createwindow(Client *c);
    193 static gboolean loadfailedtls(WebKitWebView *v, gchar *uri,
    194                               GTlsCertificate *cert,
    195                               GTlsCertificateFlags err, Client *c);
    196 static void loadchanged(WebKitWebView *v, WebKitLoadEvent e, Client *c);
    197 static void progresschanged(WebKitWebView *v, GParamSpec *ps, Client *c);
    198 static void titlechanged(WebKitWebView *view, GParamSpec *ps, Client *c);
    199 static void mousetargetchanged(WebKitWebView *v, WebKitHitTestResult *h,
    200                                guint modifiers, Client *c);
    201 static gboolean permissionrequested(WebKitWebView *v,
    202                                     WebKitPermissionRequest *r, Client *c);
    203 static gboolean decidepolicy(WebKitWebView *v, WebKitPolicyDecision *d,
    204                              WebKitPolicyDecisionType dt, Client *c);
    205 static void decidenavigation(WebKitPolicyDecision *d, Client *c);
    206 static void decidenewwindow(WebKitPolicyDecision *d, Client *c);
    207 static void decideresource(WebKitPolicyDecision *d, Client *c);
    208 static void insecurecontent(WebKitWebView *v, WebKitInsecureContentEvent e,
    209                             Client *c);
    210 static void downloadstarted(WebKitWebContext *wc, WebKitDownload *d,
    211                             Client *c);
    212 static void responsereceived(WebKitDownload *d, GParamSpec *ps, Client *c);
    213 static void download(Client *c, WebKitURIResponse *r);
    214 static void webprocessterminated(WebKitWebView *v,
    215                                  WebKitWebProcessTerminationReason r,
    216                                  Client *c);
    217 static void closeview(WebKitWebView *v, Client *c);
    218 static void destroywin(GtkWidget* w, Client *c);
    219 
    220 /* Hotkeys */
    221 static void pasteuri(GtkClipboard *clipboard, const char *text, gpointer d);
    222 static void reload(Client *c, const Arg *a);
    223 static void print(Client *c, const Arg *a);
    224 static void showcert(Client *c, const Arg *a);
    225 static void clipboard(Client *c, const Arg *a);
    226 static void zoom(Client *c, const Arg *a);
    227 static void scrollv(Client *c, const Arg *a);
    228 static void scrollh(Client *c, const Arg *a);
    229 static void navigate(Client *c, const Arg *a);
    230 static void stop(Client *c, const Arg *a);
    231 static void toggle(Client *c, const Arg *a);
    232 static void togglefullscreen(Client *c, const Arg *a);
    233 static void togglecookiepolicy(Client *c, const Arg *a);
    234 static void toggleinspector(Client *c, const Arg *a);
    235 static void find(Client *c, const Arg *a);
    236 
    237 /* Buttons */
    238 static void clicknavigate(Client *c, const Arg *a, WebKitHitTestResult *h);
    239 static void clicknewwindow(Client *c, const Arg *a, WebKitHitTestResult *h);
    240 static void clickexternplayer(Client *c, const Arg *a, WebKitHitTestResult *h);
    241 
    242 static char winid[64];
    243 static char togglestats[11];
    244 static char pagestats[2];
    245 static Atom atoms[AtomLast];
    246 static Window embed;
    247 static int showxid;
    248 static int cookiepolicy;
    249 static Display *dpy;
    250 static Client *clients;
    251 static GdkDevice *gdkkb;
    252 static char *stylefile;
    253 static const char *useragent;
    254 static Parameter *curconfig;
    255 static int modparams[ParameterLast];
    256 static int spair[2];
    257 char *argv0;
    258 
    259 static ParamName loadtransient[] = {
    260 	Certificate,
    261 	CookiePolicies,
    262 	DiskCache,
    263 	DNSPrefetch,
    264 	FileURLsCrossAccess,
    265 	JavaScript,
    266 	LoadImages,
    267 	PreferredLanguages,
    268 	ShowIndicators,
    269 	StrictTLS,
    270 	ParameterLast
    271 };
    272 
    273 static ParamName loadcommitted[] = {
    274 //	AccessMicrophone,
    275 //	AccessWebcam,
    276 	CaretBrowsing,
    277 	DefaultCharset,
    278 	FontSize,
    279 	FrameFlattening,
    280 	Geolocation,
    281 	HideBackground,
    282 	Inspector,
    283 	Java,
    284 //	KioskMode,
    285 	MediaManualPlay,
    286 	RunInFullscreen,
    287 	ScrollBars,
    288 	SiteQuirks,
    289 	SmoothScrolling,
    290 	SpellChecking,
    291 	SpellLanguages,
    292 	Style,
    293 	ZoomLevel,
    294 	ParameterLast
    295 };
    296 
    297 static ParamName loadfinished[] = {
    298 	ParameterLast
    299 };
    300 
    301 /* configuration, allows nested code to access above variables */
    302 #include "config.h"
    303 
    304 void
    305 die(const char *errstr, ...)
    306 {
    307        va_list ap;
    308 
    309        va_start(ap, errstr);
    310        vfprintf(stderr, errstr, ap);
    311        va_end(ap);
    312        exit(1);
    313 }
    314 
    315 void
    316 usage(void)
    317 {
    318 	die("usage: surf [-bBdDfFgGiIkKmMnNpPsStTvwxX]\n"
    319 	    "[-a cookiepolicies ] [-c cookiefile] [-C stylefile] [-e xid]\n"
    320 	    "[-r scriptfile] [-u useragent] [-z zoomlevel] [uri]\n");
    321 }
    322 
    323 void
    324 setup(void)
    325 {
    326 	GIOChannel *gchanin;
    327 	GdkDisplay *gdpy;
    328 	int i, j;
    329 
    330 	/* clean up any zombies immediately */
    331 	sigchld(0);
    332 	if (signal(SIGHUP, sighup) == SIG_ERR)
    333 		die("Can't install SIGHUP handler");
    334 
    335 	if (!(dpy = XOpenDisplay(NULL)))
    336 		die("Can't open default display");
    337 
    338 	/* atoms */
    339 	atoms[AtomFind] = XInternAtom(dpy, "_SURF_FIND", False);
    340 	atoms[AtomGo] = XInternAtom(dpy, "_SURF_GO", False);
    341 	atoms[AtomUri] = XInternAtom(dpy, "_SURF_URI", False);
    342 
    343 	gtk_init(NULL, NULL);
    344 
    345 	gdpy = gdk_display_get_default();
    346 
    347 	curconfig = defconfig;
    348 
    349 	/* dirs and files */
    350 	cookiefile = buildfile(cookiefile);
    351 	scriptfile = buildfile(scriptfile);
    352 	certdir    = buildpath(certdir);
    353 	if (curconfig[Ephemeral].val.i)
    354 		cachedir = NULL;
    355 	else
    356 		cachedir   = buildpath(cachedir);
    357 
    358 	gdkkb = gdk_seat_get_keyboard(gdk_display_get_default_seat(gdpy));
    359 
    360 	if (socketpair(AF_UNIX, SOCK_DGRAM, 0, spair) < 0) {
    361 		fputs("Unable to create sockets\n", stderr);
    362 		spair[0] = spair[1] = -1;
    363 	} else {
    364 		gchanin = g_io_channel_unix_new(spair[0]);
    365 		g_io_channel_set_encoding(gchanin, NULL, NULL);
    366 		g_io_channel_set_flags(gchanin, g_io_channel_get_flags(gchanin)
    367 		                       | G_IO_FLAG_NONBLOCK, NULL);
    368 		g_io_channel_set_close_on_unref(gchanin, TRUE);
    369 		g_io_add_watch(gchanin, G_IO_IN, readsock, NULL);
    370 	}
    371 
    372 
    373 	for (i = 0; i < LENGTH(certs); ++i) {
    374 		if (!regcomp(&(certs[i].re), certs[i].regex, REG_EXTENDED)) {
    375 			certs[i].file = g_strconcat(certdir, "/", certs[i].file,
    376 			                            NULL);
    377 		} else {
    378 			fprintf(stderr, "Could not compile regex: %s\n",
    379 			        certs[i].regex);
    380 			certs[i].regex = NULL;
    381 		}
    382 	}
    383 
    384 	if (!stylefile) {
    385 		styledir = buildpath(styledir);
    386 		for (i = 0; i < LENGTH(styles); ++i) {
    387 			if (!regcomp(&(styles[i].re), styles[i].regex,
    388 			    REG_EXTENDED)) {
    389 				styles[i].file = g_strconcat(styledir, "/",
    390 				                    styles[i].file, NULL);
    391 			} else {
    392 				fprintf(stderr, "Could not compile regex: %s\n",
    393 				        styles[i].regex);
    394 				styles[i].regex = NULL;
    395 			}
    396 		}
    397 		g_free(styledir);
    398 	} else {
    399 		stylefile = buildfile(stylefile);
    400 	}
    401 
    402 	for (i = 0; i < LENGTH(uriparams); ++i) {
    403 		if (regcomp(&(uriparams[i].re), uriparams[i].uri,
    404 		    REG_EXTENDED)) {
    405 			fprintf(stderr, "Could not compile regex: %s\n",
    406 			        uriparams[i].uri);
    407 			uriparams[i].uri = NULL;
    408 			continue;
    409 		}
    410 
    411 		/* copy default parameters with higher priority */
    412 		for (j = 0; j < ParameterLast; ++j) {
    413 			if (defconfig[j].prio >= uriparams[i].config[j].prio)
    414 				uriparams[i].config[j] = defconfig[j];
    415 		}
    416 	}
    417 }
    418 
    419 void
    420 sigchld(int unused)
    421 {
    422 	if (signal(SIGCHLD, sigchld) == SIG_ERR)
    423 		die("Can't install SIGCHLD handler");
    424 	while (waitpid(-1, NULL, WNOHANG) > 0)
    425 		;
    426 }
    427 
    428 void
    429 sighup(int unused)
    430 {
    431 	Arg a = { .i = 0 };
    432 	Client *c;
    433 
    434 	for (c = clients; c; c = c->next)
    435 		reload(c, &a);
    436 }
    437 
    438 char *
    439 buildfile(const char *path)
    440 {
    441 	char *dname, *bname, *bpath, *fpath;
    442 	FILE *f;
    443 
    444 	dname = g_path_get_dirname(path);
    445 	bname = g_path_get_basename(path);
    446 
    447 	bpath = buildpath(dname);
    448 	g_free(dname);
    449 
    450 	fpath = g_build_filename(bpath, bname, NULL);
    451 	g_free(bpath);
    452 	g_free(bname);
    453 
    454 	if (!(f = fopen(fpath, "a")))
    455 		die("Could not open file: %s\n", fpath);
    456 
    457 	g_chmod(fpath, 0600); /* always */
    458 	fclose(f);
    459 
    460 	return fpath;
    461 }
    462 
    463 static const char*
    464 getuserhomedir(const char *user)
    465 {
    466 	struct passwd *pw = getpwnam(user);
    467 
    468 	if (!pw)
    469 		die("Can't get user %s login information.\n", user);
    470 
    471 	return pw->pw_dir;
    472 }
    473 
    474 static const char*
    475 getcurrentuserhomedir(void)
    476 {
    477 	const char *homedir;
    478 	const char *user;
    479 	struct passwd *pw;
    480 
    481 	homedir = getenv("HOME");
    482 	if (homedir)
    483 		return homedir;
    484 
    485 	user = getenv("USER");
    486 	if (user)
    487 		return getuserhomedir(user);
    488 
    489 	pw = getpwuid(getuid());
    490 	if (!pw)
    491 		die("Can't get current user home directory\n");
    492 
    493 	return pw->pw_dir;
    494 }
    495 
    496 char *
    497 buildpath(const char *path)
    498 {
    499 	char *apath, *fpath;
    500 
    501 	if (path[0] == '~')
    502 		apath = untildepath(path);
    503 	else
    504 		apath = g_strdup(path);
    505 
    506 	/* creating directory */
    507 	if (g_mkdir_with_parents(apath, 0700) < 0)
    508 		die("Could not access directory: %s\n", apath);
    509 
    510 	fpath = realpath(apath, NULL);
    511 	g_free(apath);
    512 
    513 	return fpath;
    514 }
    515 
    516 char *
    517 untildepath(const char *path)
    518 {
    519        char *apath, *name, *p;
    520        const char *homedir;
    521 
    522        if (path[1] == '/' || path[1] == '\0') {
    523                p = (char *)&path[1];
    524                homedir = getcurrentuserhomedir();
    525        } else {
    526                if ((p = strchr(path, '/')))
    527                        name = g_strndup(&path[1], p - (path + 1));
    528                else
    529                        name = g_strdup(&path[1]);
    530 
    531                homedir = getuserhomedir(name);
    532                g_free(name);
    533        }
    534        apath = g_build_filename(homedir, p, NULL);
    535        return apath;
    536 }
    537 
    538 Client *
    539 newclient(Client *rc)
    540 {
    541 	Client *c;
    542 
    543 	if (!(c = calloc(1, sizeof(Client))))
    544 		die("Cannot malloc!\n");
    545 
    546 	c->next = clients;
    547 	clients = c;
    548 
    549 	c->progress = 100;
    550 	c->view = newview(c, rc ? rc->view : NULL);
    551 
    552 	return c;
    553 }
    554 
    555 void
    556 loaduri(Client *c, const Arg *a)
    557 {
    558 	struct stat st;
    559 	char *url, *path, *apath;
    560 	const char *uri = a->v;
    561 
    562 	if (g_strcmp0(uri, "") == 0)
    563 		return;
    564 
    565 	if (g_str_has_prefix(uri, "http://")  ||
    566 	    g_str_has_prefix(uri, "https://") ||
    567 	    g_str_has_prefix(uri, "file://")  ||
    568 	    g_str_has_prefix(uri, "about:")) {
    569 		url = g_strdup(uri);
    570 	} else {
    571 		if (uri[0] == '~')
    572 			apath = untildepath(uri);
    573 		else
    574 			apath = (char *)uri;
    575 		if (!stat(apath, &st) && (path = realpath(apath, NULL))) {
    576 			url = g_strdup_printf("file://%s", path);
    577 			free(path);
    578 		} else {
    579 			url = g_strdup_printf("http://%s", uri);
    580 		}
    581 		if (apath != uri)
    582 			free(apath);
    583 	}
    584 
    585 	setatom(c, AtomUri, url);
    586 
    587 	if (strcmp(url, geturi(c)) == 0) {
    588 		reload(c, a);
    589 	} else {
    590 		webkit_web_view_load_uri(c->view, url);
    591 		updatetitle(c);
    592 	}
    593 
    594 	g_free(url);
    595 }
    596 
    597 const char *
    598 geturi(Client *c)
    599 {
    600 	const char *uri;
    601 
    602 	if (!(uri = webkit_web_view_get_uri(c->view)))
    603 		uri = "about:blank";
    604 	return uri;
    605 }
    606 
    607 void
    608 setatom(Client *c, int a, const char *v)
    609 {
    610 	XChangeProperty(dpy, c->xid,
    611 	                atoms[a], XA_STRING, 8, PropModeReplace,
    612 	                (unsigned char *)v, strlen(v) + 1);
    613 	XSync(dpy, False);
    614 }
    615 
    616 const char *
    617 getatom(Client *c, int a)
    618 {
    619 	static char buf[BUFSIZ];
    620 	Atom adummy;
    621 	int idummy;
    622 	unsigned long ldummy;
    623 	unsigned char *p = NULL;
    624 
    625 	XSync(dpy, False);
    626 	XGetWindowProperty(dpy, c->xid, atoms[a], 0L, BUFSIZ, False, XA_STRING,
    627 	                   &adummy, &idummy, &ldummy, &ldummy, &p);
    628 	if (p)
    629 		strncpy(buf, (char *)p, LENGTH(buf) - 1);
    630 	else
    631 		buf[0] = '\0';
    632 	XFree(p);
    633 
    634 	return buf;
    635 }
    636 
    637 void
    638 updatetitle(Client *c)
    639 {
    640 	char *title;
    641 	const char *name = c->overtitle ? c->overtitle :
    642 	                   c->title ? c->title : "";
    643 
    644 	if (curconfig[ShowIndicators].val.i) {
    645 		gettogglestats(c);
    646 		getpagestats(c);
    647 
    648 		if (c->progress != 100)
    649 			title = g_strdup_printf("[%i%%] %s:%s | %s",
    650 			        c->progress, togglestats, pagestats, name);
    651 		else
    652 			title = g_strdup_printf("%s:%s | %s",
    653 			        togglestats, pagestats, name);
    654 
    655 		gtk_window_set_title(GTK_WINDOW(c->win), title);
    656 		g_free(title);
    657 	} else {
    658 		gtk_window_set_title(GTK_WINDOW(c->win), name);
    659 	}
    660 }
    661 
    662 void
    663 gettogglestats(Client *c)
    664 {
    665 	togglestats[0] = cookiepolicy_set(cookiepolicy_get());
    666 	togglestats[1] = curconfig[CaretBrowsing].val.i ?   'C' : 'c';
    667 	togglestats[2] = curconfig[Geolocation].val.i ?     'G' : 'g';
    668 	togglestats[3] = curconfig[DiskCache].val.i ?       'D' : 'd';
    669 	togglestats[4] = curconfig[LoadImages].val.i ?      'I' : 'i';
    670 	togglestats[5] = curconfig[JavaScript].val.i ?      'S' : 's';
    671 	togglestats[6] = curconfig[Style].val.i ?           'M' : 'm';
    672 	togglestats[7] = curconfig[FrameFlattening].val.i ? 'F' : 'f';
    673 	togglestats[8] = curconfig[Certificate].val.i ?     'X' : 'x';
    674 	togglestats[9] = curconfig[StrictTLS].val.i ?       'T' : 't';
    675 }
    676 
    677 void
    678 getpagestats(Client *c)
    679 {
    680 	if (c->https)
    681 		pagestats[0] = (c->tlserr || c->insecure) ?  'U' : 'T';
    682 	else
    683 		pagestats[0] = '-';
    684 	pagestats[1] = '\0';
    685 }
    686 
    687 WebKitCookieAcceptPolicy
    688 cookiepolicy_get(void)
    689 {
    690 	switch (((char *)curconfig[CookiePolicies].val.v)[cookiepolicy]) {
    691 	case 'a':
    692 		return WEBKIT_COOKIE_POLICY_ACCEPT_NEVER;
    693 	case '@':
    694 		return WEBKIT_COOKIE_POLICY_ACCEPT_NO_THIRD_PARTY;
    695 	default: /* fallthrough */
    696 	case 'A':
    697 		return WEBKIT_COOKIE_POLICY_ACCEPT_ALWAYS;
    698 	}
    699 }
    700 
    701 char
    702 cookiepolicy_set(const WebKitCookieAcceptPolicy p)
    703 {
    704 	switch (p) {
    705 	case WEBKIT_COOKIE_POLICY_ACCEPT_NEVER:
    706 		return 'a';
    707 	case WEBKIT_COOKIE_POLICY_ACCEPT_NO_THIRD_PARTY:
    708 		return '@';
    709 	default: /* fallthrough */
    710 	case WEBKIT_COOKIE_POLICY_ACCEPT_ALWAYS:
    711 		return 'A';
    712 	}
    713 }
    714 
    715 void
    716 seturiparameters(Client *c, const char *uri, ParamName *params)
    717 {
    718 	Parameter *config, *uriconfig = NULL;
    719 	int i, p;
    720 
    721 	for (i = 0; i < LENGTH(uriparams); ++i) {
    722 		if (uriparams[i].uri &&
    723 		    !regexec(&(uriparams[i].re), uri, 0, NULL, 0)) {
    724 			uriconfig = uriparams[i].config;
    725 			break;
    726 		}
    727 	}
    728 
    729 	curconfig = uriconfig ? uriconfig : defconfig;
    730 
    731 	for (i = 0; (p = params[i]) != ParameterLast; ++i) {
    732 		switch(p) {
    733 		default: /* FALLTHROUGH */
    734 			if (!(defconfig[p].prio < curconfig[p].prio ||
    735 			    defconfig[p].prio < modparams[p]))
    736 				continue;
    737 		case Certificate:
    738 		case CookiePolicies:
    739 		case Style:
    740 			setparameter(c, 0, p, &curconfig[p].val);
    741 		}
    742 	}
    743 }
    744 
    745 void
    746 setparameter(Client *c, int refresh, ParamName p, const Arg *a)
    747 {
    748 	GdkRGBA bgcolor = { 0 };
    749 	WebKitSettings *s = webkit_web_view_get_settings(c->view);
    750 
    751 	modparams[p] = curconfig[p].prio;
    752 
    753 	switch (p) {
    754 	case AccessMicrophone:
    755 		return; /* do nothing */
    756 	case AccessWebcam:
    757 		return; /* do nothing */
    758 	case CaretBrowsing:
    759 		webkit_settings_set_enable_caret_browsing(s, a->i);
    760 		refresh = 0;
    761 		break;
    762 	case Certificate:
    763 		if (a->i)
    764 			setcert(c, geturi(c));
    765 		return; /* do not update */
    766 	case CookiePolicies:
    767 		webkit_cookie_manager_set_accept_policy(
    768 		    webkit_web_context_get_cookie_manager(
    769 		    webkit_web_view_get_context(c->view)),
    770 		    cookiepolicy_get());
    771 		refresh = 0;
    772 		break;
    773 	case DiskCache:
    774 		webkit_web_context_set_cache_model(
    775 		    webkit_web_view_get_context(c->view), a->i ?
    776 		    WEBKIT_CACHE_MODEL_WEB_BROWSER :
    777 		    WEBKIT_CACHE_MODEL_DOCUMENT_VIEWER);
    778 		return; /* do not update */
    779 	case DefaultCharset:
    780 		webkit_settings_set_default_charset(s, a->v);
    781 		return; /* do not update */
    782 	case DNSPrefetch:
    783 		webkit_settings_set_enable_dns_prefetching(s, a->i);
    784 		return; /* do not update */
    785 	case FileURLsCrossAccess:
    786 		webkit_settings_set_allow_file_access_from_file_urls(s, a->i);
    787 		webkit_settings_set_allow_universal_access_from_file_urls(s, a->i);
    788 		return; /* do not update */
    789 	case FontSize:
    790 		webkit_settings_set_default_font_size(s, a->i);
    791 		return; /* do not update */
    792 	case FrameFlattening:
    793 		webkit_settings_set_enable_frame_flattening(s, a->i);
    794 		break;
    795 	case Geolocation:
    796 		refresh = 0;
    797 		break;
    798 	case HideBackground:
    799 		if (a->i)
    800 			webkit_web_view_set_background_color(c->view, &bgcolor);
    801 		return; /* do not update */
    802 	case Inspector:
    803 		webkit_settings_set_enable_developer_extras(s, a->i);
    804 		return; /* do not update */
    805 	case Java:
    806 		webkit_settings_set_enable_java(s, a->i);
    807 		return; /* do not update */
    808 	case JavaScript:
    809 		webkit_settings_set_enable_javascript(s, a->i);
    810 		break;
    811 	case KioskMode:
    812 		return; /* do nothing */
    813 	case LoadImages:
    814 		webkit_settings_set_auto_load_images(s, a->i);
    815 		break;
    816 	case MediaManualPlay:
    817 		webkit_settings_set_media_playback_requires_user_gesture(s, a->i);
    818 		break;
    819 	case PreferredLanguages:
    820 		return; /* do nothing */
    821 	case RunInFullscreen:
    822 		return; /* do nothing */
    823 	case ScrollBars:
    824 		/* Disabled until we write some WebKitWebExtension for
    825 		 * manipulating the DOM directly.
    826 		enablescrollbars = !enablescrollbars;
    827 		evalscript(c, "document.documentElement.style.overflow = '%s'",
    828 		    enablescrollbars ? "auto" : "hidden");
    829 		*/
    830 		return; /* do not update */
    831 	case ShowIndicators:
    832 		break;
    833 	case SmoothScrolling:
    834 		webkit_settings_set_enable_smooth_scrolling(s, a->i);
    835 		return; /* do not update */
    836 	case SiteQuirks:
    837 		webkit_settings_set_enable_site_specific_quirks(s, a->i);
    838 		break;
    839 	case SpellChecking:
    840 		webkit_web_context_set_spell_checking_enabled(
    841 		    webkit_web_view_get_context(c->view), a->i);
    842 		return; /* do not update */
    843 	case SpellLanguages:
    844 		return; /* do nothing */
    845 	case StrictTLS:
    846 		webkit_web_context_set_tls_errors_policy(
    847 		    webkit_web_view_get_context(c->view), a->i ?
    848 		    WEBKIT_TLS_ERRORS_POLICY_FAIL :
    849 		    WEBKIT_TLS_ERRORS_POLICY_IGNORE);
    850 		break;
    851 	case Style:
    852 		webkit_user_content_manager_remove_all_style_sheets(
    853 		    webkit_web_view_get_user_content_manager(c->view));
    854 		if (a->i)
    855 			setstyle(c, getstyle(geturi(c)));
    856 		refresh = 0;
    857 		break;
    858 	case WebGL:
    859 		webkit_settings_set_enable_webgl(s, a->i);
    860 		break;
    861 	case ZoomLevel:
    862 		webkit_web_view_set_zoom_level(c->view, a->f);
    863 		return; /* do not update */
    864 	default:
    865 		return; /* do nothing */
    866 	}
    867 
    868 	updatetitle(c);
    869 	if (refresh)
    870 		reload(c, a);
    871 }
    872 
    873 const char *
    874 getcert(const char *uri)
    875 {
    876 	int i;
    877 
    878 	for (i = 0; i < LENGTH(certs); ++i) {
    879 		if (certs[i].regex &&
    880 		    !regexec(&(certs[i].re), uri, 0, NULL, 0))
    881 			return certs[i].file;
    882 	}
    883 
    884 	return NULL;
    885 }
    886 
    887 void
    888 setcert(Client *c, const char *uri)
    889 {
    890 	const char *file = getcert(uri);
    891 	char *host;
    892 	GTlsCertificate *cert;
    893 
    894 	if (!file)
    895 		return;
    896 
    897 	if (!(cert = g_tls_certificate_new_from_file(file, NULL))) {
    898 		fprintf(stderr, "Could not read certificate file: %s\n", file);
    899 		return;
    900 	}
    901 
    902 	if ((uri = strstr(uri, "https://"))) {
    903 		uri += sizeof("https://") - 1;
    904 		host = g_strndup(uri, strchr(uri, '/') - uri);
    905 		webkit_web_context_allow_tls_certificate_for_host(
    906 		    webkit_web_view_get_context(c->view), cert, host);
    907 		g_free(host);
    908 	}
    909 
    910 	g_object_unref(cert);
    911 
    912 }
    913 
    914 const char *
    915 getstyle(const char *uri)
    916 {
    917 	int i;
    918 
    919 	if (stylefile)
    920 		return stylefile;
    921 
    922 	for (i = 0; i < LENGTH(styles); ++i) {
    923 		if (styles[i].regex &&
    924 		    !regexec(&(styles[i].re), uri, 0, NULL, 0))
    925 			return styles[i].file;
    926 	}
    927 
    928 	return "";
    929 }
    930 
    931 void
    932 setstyle(Client *c, const char *file)
    933 {
    934 	gchar *style;
    935 
    936 	if (!g_file_get_contents(file, &style, NULL, NULL)) {
    937 		fprintf(stderr, "Could not read style file: %s\n", file);
    938 		return;
    939 	}
    940 
    941 	webkit_user_content_manager_add_style_sheet(
    942 	    webkit_web_view_get_user_content_manager(c->view),
    943 	    webkit_user_style_sheet_new(style,
    944 	    WEBKIT_USER_CONTENT_INJECT_ALL_FRAMES,
    945 	    WEBKIT_USER_STYLE_LEVEL_USER,
    946 	    NULL, NULL));
    947 
    948 	g_free(style);
    949 }
    950 
    951 void
    952 runscript(Client *c)
    953 {
    954 	gchar *script;
    955 	gsize l;
    956 
    957 	if (g_file_get_contents(scriptfile, &script, &l, NULL) && l)
    958 		evalscript(c, "%s", script);
    959 	g_free(script);
    960 }
    961 
    962 void
    963 evalscript(Client *c, const char *jsstr, ...)
    964 {
    965 	va_list ap;
    966 	gchar *script;
    967 
    968 	va_start(ap, jsstr);
    969 	script = g_strdup_vprintf(jsstr, ap);
    970 	va_end(ap);
    971 
    972 	webkit_web_view_run_javascript(c->view, script, NULL, NULL, NULL);
    973 	g_free(script);
    974 }
    975 
    976 void
    977 updatewinid(Client *c)
    978 {
    979 	snprintf(winid, LENGTH(winid), "%lu", c->xid);
    980 }
    981 
    982 void
    983 handleplumb(Client *c, const char *uri)
    984 {
    985 	Arg a = (Arg)PLUMB(uri);
    986 	spawn(c, &a);
    987 }
    988 
    989 void
    990 newwindow(Client *c, const Arg *a, int noembed)
    991 {
    992 	int i = 0;
    993 	char tmp[64];
    994 	const char *cmd[29], *uri;
    995 	const Arg arg = { .v = cmd };
    996 
    997 	cmd[i++] = argv0;
    998 	cmd[i++] = "-a";
    999 	cmd[i++] = curconfig[CookiePolicies].val.v;
   1000 	cmd[i++] = curconfig[ScrollBars].val.i ? "-B" : "-b";
   1001 	if (cookiefile && g_strcmp0(cookiefile, "")) {
   1002 		cmd[i++] = "-c";
   1003 		cmd[i++] = cookiefile;
   1004 	}
   1005 	if (stylefile && g_strcmp0(stylefile, "")) {
   1006 		cmd[i++] = "-C";
   1007 		cmd[i++] = stylefile;
   1008 	}
   1009 	cmd[i++] = curconfig[DiskCache].val.i ? "-D" : "-d";
   1010 	if (embed && !noembed) {
   1011 		cmd[i++] = "-e";
   1012 		snprintf(tmp, LENGTH(tmp), "%lu", embed);
   1013 		cmd[i++] = tmp;
   1014 	}
   1015 	cmd[i++] = curconfig[RunInFullscreen].val.i ? "-F" : "-f" ;
   1016 	cmd[i++] = curconfig[Geolocation].val.i ?     "-G" : "-g" ;
   1017 	cmd[i++] = curconfig[LoadImages].val.i ?      "-I" : "-i" ;
   1018 	cmd[i++] = curconfig[KioskMode].val.i ?       "-K" : "-k" ;
   1019 	cmd[i++] = curconfig[Style].val.i ?           "-M" : "-m" ;
   1020 	cmd[i++] = curconfig[Inspector].val.i ?       "-N" : "-n" ;
   1021 	if (scriptfile && g_strcmp0(scriptfile, "")) {
   1022 		cmd[i++] = "-r";
   1023 		cmd[i++] = scriptfile;
   1024 	}
   1025 	cmd[i++] = curconfig[JavaScript].val.i ? "-S" : "-s";
   1026 	cmd[i++] = curconfig[StrictTLS].val.i ? "-T" : "-t";
   1027 	if (fulluseragent && g_strcmp0(fulluseragent, "")) {
   1028 		cmd[i++] = "-u";
   1029 		cmd[i++] = fulluseragent;
   1030 	}
   1031 	if (showxid)
   1032 		cmd[i++] = "-w";
   1033 	cmd[i++] = curconfig[Certificate].val.i ? "-X" : "-x" ;
   1034 	/* do not keep zoom level */
   1035 	cmd[i++] = "--";
   1036 	if ((uri = a->v))
   1037 		cmd[i++] = uri;
   1038 	cmd[i] = NULL;
   1039 
   1040 	spawn(c, &arg);
   1041 }
   1042 
   1043 void
   1044 spawn(Client *c, const Arg *a)
   1045 {
   1046 	if (fork() == 0) {
   1047 		if (dpy)
   1048 			close(ConnectionNumber(dpy));
   1049 		close(spair[0]);
   1050 		close(spair[1]);
   1051 		setsid();
   1052 		execvp(((char **)a->v)[0], (char **)a->v);
   1053 		fprintf(stderr, "%s: execvp %s", argv0, ((char **)a->v)[0]);
   1054 		perror(" failed");
   1055 		exit(1);
   1056 	}
   1057 }
   1058 
   1059 void
   1060 destroyclient(Client *c)
   1061 {
   1062 	Client *p;
   1063 
   1064 	webkit_web_view_stop_loading(c->view);
   1065 	/* Not needed, has already been called
   1066 	gtk_widget_destroy(c->win);
   1067 	 */
   1068 
   1069 	for (p = clients; p && p->next != c; p = p->next)
   1070 		;
   1071 	if (p)
   1072 		p->next = c->next;
   1073 	else
   1074 		clients = c->next;
   1075 	free(c);
   1076 }
   1077 
   1078 void
   1079 cleanup(void)
   1080 {
   1081 	while (clients)
   1082 		destroyclient(clients);
   1083 
   1084 	close(spair[0]);
   1085 	close(spair[1]);
   1086 	g_free(cookiefile);
   1087 	g_free(scriptfile);
   1088 	g_free(stylefile);
   1089 	g_free(cachedir);
   1090 	XCloseDisplay(dpy);
   1091 }
   1092 
   1093 WebKitWebView *
   1094 newview(Client *c, WebKitWebView *rv)
   1095 {
   1096 	WebKitWebView *v;
   1097 	WebKitSettings *settings;
   1098 	WebKitWebContext *context;
   1099 	WebKitCookieManager *cookiemanager;
   1100 	WebKitUserContentManager *contentmanager;
   1101 
   1102 	/* Webview */
   1103 	if (rv) {
   1104 		v = WEBKIT_WEB_VIEW(webkit_web_view_new_with_related_view(rv));
   1105 	} else {
   1106 		settings = webkit_settings_new_with_settings(
   1107 		   "allow-file-access-from-file-urls", curconfig[FileURLsCrossAccess].val.i,
   1108 		   "allow-universal-access-from-file-urls", curconfig[FileURLsCrossAccess].val.i,
   1109 		   "auto-load-images", curconfig[LoadImages].val.i,
   1110 		   "default-charset", curconfig[DefaultCharset].val.v,
   1111 		   "default-font-size", curconfig[FontSize].val.i,
   1112 		   "enable-caret-browsing", curconfig[CaretBrowsing].val.i,
   1113 		   "enable-developer-extras", curconfig[Inspector].val.i,
   1114 		   "enable-dns-prefetching", curconfig[DNSPrefetch].val.i,
   1115 		   "enable-frame-flattening", curconfig[FrameFlattening].val.i,
   1116 		   "enable-html5-database", curconfig[DiskCache].val.i,
   1117 		   "enable-html5-local-storage", curconfig[DiskCache].val.i,
   1118 		   "enable-java", curconfig[Java].val.i,
   1119 		   "enable-javascript", curconfig[JavaScript].val.i,
   1120 		   "enable-site-specific-quirks", curconfig[SiteQuirks].val.i,
   1121 		   "enable-smooth-scrolling", curconfig[SmoothScrolling].val.i,
   1122 		   "enable-webgl", curconfig[WebGL].val.i,
   1123 		   "media-playback-requires-user-gesture", curconfig[MediaManualPlay].val.i,
   1124 		   NULL);
   1125 /* For more interesting settings, have a look at
   1126  * http://webkitgtk.org/reference/webkit2gtk/stable/WebKitSettings.html */
   1127 
   1128 		if (strcmp(fulluseragent, "")) {
   1129 			webkit_settings_set_user_agent(settings, fulluseragent);
   1130 		} else if (surfuseragent) {
   1131 			webkit_settings_set_user_agent_with_application_details(
   1132 			    settings, "Surf", VERSION);
   1133 		}
   1134 		useragent = webkit_settings_get_user_agent(settings);
   1135 
   1136 		contentmanager = webkit_user_content_manager_new();
   1137 
   1138 		if (curconfig[Ephemeral].val.i) {
   1139 			context = webkit_web_context_new_ephemeral();
   1140 		} else {
   1141 			context = webkit_web_context_new_with_website_data_manager(
   1142 			          webkit_website_data_manager_new(
   1143 			          "base-cache-directory", cachedir,
   1144 			          "base-data-directory", cachedir,
   1145 			          NULL));
   1146 		}
   1147 
   1148 
   1149 		cookiemanager = webkit_web_context_get_cookie_manager(context);
   1150 
   1151 		/* rendering process model, can be a shared unique one
   1152 		 * or one for each view */
   1153 		webkit_web_context_set_process_model(context,
   1154 		    WEBKIT_PROCESS_MODEL_MULTIPLE_SECONDARY_PROCESSES);
   1155 		/* TLS */
   1156 		webkit_web_context_set_tls_errors_policy(context,
   1157 		    curconfig[StrictTLS].val.i ? WEBKIT_TLS_ERRORS_POLICY_FAIL :
   1158 		    WEBKIT_TLS_ERRORS_POLICY_IGNORE);
   1159 		/* disk cache */
   1160 		webkit_web_context_set_cache_model(context,
   1161 		    curconfig[DiskCache].val.i ? WEBKIT_CACHE_MODEL_WEB_BROWSER :
   1162 		    WEBKIT_CACHE_MODEL_DOCUMENT_VIEWER);
   1163 
   1164 		/* Currently only works with text file to be compatible with curl */
   1165 		if (!curconfig[Ephemeral].val.i)
   1166 			webkit_cookie_manager_set_persistent_storage(cookiemanager,
   1167 			    cookiefile, WEBKIT_COOKIE_PERSISTENT_STORAGE_TEXT);
   1168 		/* cookie policy */
   1169 		webkit_cookie_manager_set_accept_policy(cookiemanager,
   1170 		    cookiepolicy_get());
   1171 		/* languages */
   1172 		webkit_web_context_set_preferred_languages(context,
   1173 		    curconfig[PreferredLanguages].val.v);
   1174 		webkit_web_context_set_spell_checking_languages(context,
   1175 		    curconfig[SpellLanguages].val.v);
   1176 		webkit_web_context_set_spell_checking_enabled(context,
   1177 		    curconfig[SpellChecking].val.i);
   1178 
   1179 		g_signal_connect(G_OBJECT(context), "download-started",
   1180 		                 G_CALLBACK(downloadstarted), c);
   1181 		g_signal_connect(G_OBJECT(context), "initialize-web-extensions",
   1182 		                 G_CALLBACK(initwebextensions), c);
   1183 
   1184 		v = g_object_new(WEBKIT_TYPE_WEB_VIEW,
   1185 		    "settings", settings,
   1186 		    "user-content-manager", contentmanager,
   1187 		    "web-context", context,
   1188 		    NULL);
   1189 	}
   1190 
   1191 	g_signal_connect(G_OBJECT(v), "notify::estimated-load-progress",
   1192 			 G_CALLBACK(progresschanged), c);
   1193 	g_signal_connect(G_OBJECT(v), "notify::title",
   1194 			 G_CALLBACK(titlechanged), c);
   1195 	g_signal_connect(G_OBJECT(v), "button-release-event",
   1196 			 G_CALLBACK(buttonreleased), c);
   1197 	g_signal_connect(G_OBJECT(v), "close",
   1198 			G_CALLBACK(closeview), c);
   1199 	g_signal_connect(G_OBJECT(v), "create",
   1200 			 G_CALLBACK(createview), c);
   1201 	g_signal_connect(G_OBJECT(v), "decide-policy",
   1202 			 G_CALLBACK(decidepolicy), c);
   1203 	g_signal_connect(G_OBJECT(v), "insecure-content-detected",
   1204 			 G_CALLBACK(insecurecontent), c);
   1205 	g_signal_connect(G_OBJECT(v), "load-failed-with-tls-errors",
   1206 			 G_CALLBACK(loadfailedtls), c);
   1207 	g_signal_connect(G_OBJECT(v), "load-changed",
   1208 			 G_CALLBACK(loadchanged), c);
   1209 	g_signal_connect(G_OBJECT(v), "mouse-target-changed",
   1210 			 G_CALLBACK(mousetargetchanged), c);
   1211 	g_signal_connect(G_OBJECT(v), "permission-request",
   1212 			 G_CALLBACK(permissionrequested), c);
   1213 	g_signal_connect(G_OBJECT(v), "ready-to-show",
   1214 			 G_CALLBACK(showview), c);
   1215 	g_signal_connect(G_OBJECT(v), "web-process-terminated",
   1216 			 G_CALLBACK(webprocessterminated), c);
   1217 
   1218 	return v;
   1219 }
   1220 
   1221 static gboolean
   1222 readsock(GIOChannel *s, GIOCondition ioc, gpointer unused)
   1223 {
   1224 	static char msg[MSGBUFSZ];
   1225 	GError *gerr = NULL;
   1226 	gsize msgsz;
   1227 
   1228 	if (g_io_channel_read_chars(s, msg, sizeof(msg), &msgsz, &gerr) !=
   1229 	    G_IO_STATUS_NORMAL) {
   1230 		if (gerr) {
   1231 			fprintf(stderr, "surf: error reading socket: %s\n",
   1232 			        gerr->message);
   1233 			g_error_free(gerr);
   1234 		}
   1235 		return TRUE;
   1236 	}
   1237 	if (msgsz < 2) {
   1238 		fprintf(stderr, "surf: message too short: %d\n", msgsz);
   1239 		return TRUE;
   1240 	}
   1241 
   1242 	return TRUE;
   1243 }
   1244 
   1245 void
   1246 initwebextensions(WebKitWebContext *wc, Client *c)
   1247 {
   1248 	GVariant *gv;
   1249 
   1250 	if (spair[1] < 0)
   1251 		return;
   1252 
   1253 	gv = g_variant_new("i", spair[1]);
   1254 
   1255 	webkit_web_context_set_web_extensions_initialization_user_data(wc, gv);
   1256 	webkit_web_context_set_web_extensions_directory(wc, WEBEXTDIR);
   1257 }
   1258 
   1259 GtkWidget *
   1260 createview(WebKitWebView *v, WebKitNavigationAction *a, Client *c)
   1261 {
   1262 	Client *n;
   1263 
   1264 	switch (webkit_navigation_action_get_navigation_type(a)) {
   1265 	case WEBKIT_NAVIGATION_TYPE_OTHER: /* fallthrough */
   1266 		/*
   1267 		 * popup windows of type “other” are almost always triggered
   1268 		 * by user gesture, so inverse the logic here
   1269 		 */
   1270 /* instead of this, compare destination uri to mouse-over uri for validating window */
   1271 		if (webkit_navigation_action_is_user_gesture(a))
   1272 			return NULL;
   1273 	case WEBKIT_NAVIGATION_TYPE_LINK_CLICKED: /* fallthrough */
   1274 	case WEBKIT_NAVIGATION_TYPE_FORM_SUBMITTED: /* fallthrough */
   1275 	case WEBKIT_NAVIGATION_TYPE_BACK_FORWARD: /* fallthrough */
   1276 	case WEBKIT_NAVIGATION_TYPE_RELOAD: /* fallthrough */
   1277 	case WEBKIT_NAVIGATION_TYPE_FORM_RESUBMITTED:
   1278 		n = newclient(c);
   1279 		break;
   1280 	default:
   1281 		return NULL;
   1282 	}
   1283 
   1284 	return GTK_WIDGET(n->view);
   1285 }
   1286 
   1287 gboolean
   1288 buttonreleased(GtkWidget *w, GdkEvent *e, Client *c)
   1289 {
   1290 	WebKitHitTestResultContext element;
   1291 	int i;
   1292 
   1293 	element = webkit_hit_test_result_get_context(c->mousepos);
   1294 
   1295 	for (i = 0; i < LENGTH(buttons); ++i) {
   1296 		if (element & buttons[i].target &&
   1297 		    e->button.button == buttons[i].button &&
   1298 		    CLEANMASK(e->button.state) == CLEANMASK(buttons[i].mask) &&
   1299 		    buttons[i].func) {
   1300 			buttons[i].func(c, &buttons[i].arg, c->mousepos);
   1301 			return buttons[i].stopevent;
   1302 		}
   1303 	}
   1304 
   1305 	return FALSE;
   1306 }
   1307 
   1308 GdkFilterReturn
   1309 processx(GdkXEvent *e, GdkEvent *event, gpointer d)
   1310 {
   1311 	Client *c = (Client *)d;
   1312 	XPropertyEvent *ev;
   1313 	Arg a;
   1314 
   1315 	if (((XEvent *)e)->type == PropertyNotify) {
   1316 		ev = &((XEvent *)e)->xproperty;
   1317 		if (ev->state == PropertyNewValue) {
   1318 			if (ev->atom == atoms[AtomFind]) {
   1319 				find(c, NULL);
   1320 
   1321 				return GDK_FILTER_REMOVE;
   1322 			} else if (ev->atom == atoms[AtomGo]) {
   1323 				a.v = getatom(c, AtomGo);
   1324 				loaduri(c, &a);
   1325 
   1326 				return GDK_FILTER_REMOVE;
   1327 			}
   1328 		}
   1329 	}
   1330 	return GDK_FILTER_CONTINUE;
   1331 }
   1332 
   1333 gboolean
   1334 winevent(GtkWidget *w, GdkEvent *e, Client *c)
   1335 {
   1336 	int i;
   1337 
   1338 	switch (e->type) {
   1339 	case GDK_ENTER_NOTIFY:
   1340 		c->overtitle = c->targeturi;
   1341 		updatetitle(c);
   1342 		break;
   1343 	case GDK_KEY_PRESS:
   1344 		if (!curconfig[KioskMode].val.i) {
   1345 			for (i = 0; i < LENGTH(keys); ++i) {
   1346 				if (gdk_keyval_to_lower(e->key.keyval) ==
   1347 				    keys[i].keyval &&
   1348 				    CLEANMASK(e->key.state) == keys[i].mod &&
   1349 				    keys[i].func) {
   1350 					updatewinid(c);
   1351 					keys[i].func(c, &(keys[i].arg));
   1352 					return TRUE;
   1353 				}
   1354 			}
   1355 		}
   1356 	case GDK_LEAVE_NOTIFY:
   1357 		c->overtitle = NULL;
   1358 		updatetitle(c);
   1359 		break;
   1360 	case GDK_WINDOW_STATE:
   1361 		if (e->window_state.changed_mask ==
   1362 		    GDK_WINDOW_STATE_FULLSCREEN)
   1363 			c->fullscreen = e->window_state.new_window_state &
   1364 			                GDK_WINDOW_STATE_FULLSCREEN;
   1365 		break;
   1366 	default:
   1367 		break;
   1368 	}
   1369 
   1370 	return FALSE;
   1371 }
   1372 
   1373 void
   1374 showview(WebKitWebView *v, Client *c)
   1375 {
   1376 	GdkRGBA bgcolor = { 0 };
   1377 	GdkWindow *gwin;
   1378 
   1379 	c->finder = webkit_web_view_get_find_controller(c->view);
   1380 	c->inspector = webkit_web_view_get_inspector(c->view);
   1381 
   1382 	c->pageid = webkit_web_view_get_page_id(c->view);
   1383 	c->win = createwindow(c);
   1384 
   1385 	gtk_container_add(GTK_CONTAINER(c->win), GTK_WIDGET(c->view));
   1386 	gtk_widget_show_all(c->win);
   1387 	gtk_widget_grab_focus(GTK_WIDGET(c->view));
   1388 
   1389 	gwin = gtk_widget_get_window(GTK_WIDGET(c->win));
   1390 	c->xid = gdk_x11_window_get_xid(gwin);
   1391 	updatewinid(c);
   1392 	if (showxid) {
   1393 		gdk_display_sync(gtk_widget_get_display(c->win));
   1394 		puts(winid);
   1395 		fflush(stdout);
   1396 	}
   1397 
   1398 	if (curconfig[HideBackground].val.i)
   1399 		webkit_web_view_set_background_color(c->view, &bgcolor);
   1400 
   1401 	if (!curconfig[KioskMode].val.i) {
   1402 		gdk_window_set_events(gwin, GDK_ALL_EVENTS_MASK);
   1403 		gdk_window_add_filter(gwin, processx, c);
   1404 	}
   1405 
   1406 	if (curconfig[RunInFullscreen].val.i)
   1407 		togglefullscreen(c, NULL);
   1408 
   1409 	if (curconfig[ZoomLevel].val.f != 1.0)
   1410 		webkit_web_view_set_zoom_level(c->view,
   1411 		                               curconfig[ZoomLevel].val.f);
   1412 
   1413 	setatom(c, AtomFind, "");
   1414 	setatom(c, AtomUri, "about:blank");
   1415 }
   1416 
   1417 GtkWidget *
   1418 createwindow(Client *c)
   1419 {
   1420 	char *wmstr;
   1421 	GtkWidget *w;
   1422 
   1423 	if (embed) {
   1424 		w = gtk_plug_new(embed);
   1425 	} else {
   1426 		w = gtk_window_new(GTK_WINDOW_TOPLEVEL);
   1427 
   1428 		wmstr = g_path_get_basename(argv0);
   1429 		gtk_window_set_wmclass(GTK_WINDOW(w), wmstr, "Surf");
   1430 		g_free(wmstr);
   1431 
   1432 		wmstr = g_strdup_printf("%s[%"PRIu64"]", "Surf", c->pageid);
   1433 		gtk_window_set_role(GTK_WINDOW(w), wmstr);
   1434 		g_free(wmstr);
   1435 
   1436 		gtk_window_set_default_size(GTK_WINDOW(w), winsize[0], winsize[1]);
   1437 	}
   1438 
   1439 	g_signal_connect(G_OBJECT(w), "destroy",
   1440 	                 G_CALLBACK(destroywin), c);
   1441 	g_signal_connect(G_OBJECT(w), "enter-notify-event",
   1442 	                 G_CALLBACK(winevent), c);
   1443 	g_signal_connect(G_OBJECT(w), "key-press-event",
   1444 	                 G_CALLBACK(winevent), c);
   1445 	g_signal_connect(G_OBJECT(w), "leave-notify-event",
   1446 	                 G_CALLBACK(winevent), c);
   1447 	g_signal_connect(G_OBJECT(w), "window-state-event",
   1448 	                 G_CALLBACK(winevent), c);
   1449 
   1450 	return w;
   1451 }
   1452 
   1453 gboolean
   1454 loadfailedtls(WebKitWebView *v, gchar *uri, GTlsCertificate *cert,
   1455               GTlsCertificateFlags err, Client *c)
   1456 {
   1457 	GString *errmsg = g_string_new(NULL);
   1458 	gchar *html, *pem;
   1459 
   1460 	c->failedcert = g_object_ref(cert);
   1461 	c->tlserr = err;
   1462 	c->errorpage = 1;
   1463 
   1464 	if (err & G_TLS_CERTIFICATE_UNKNOWN_CA)
   1465 		g_string_append(errmsg,
   1466 		    "The signing certificate authority is not known.<br>");
   1467 	if (err & G_TLS_CERTIFICATE_BAD_IDENTITY)
   1468 		g_string_append(errmsg,
   1469 		    "The certificate does not match the expected identity "
   1470 		    "of the site that it was retrieved from.<br>");
   1471 	if (err & G_TLS_CERTIFICATE_NOT_ACTIVATED)
   1472 		g_string_append(errmsg,
   1473 		    "The certificate's activation time "
   1474 		    "is still in the future.<br>");
   1475 	if (err & G_TLS_CERTIFICATE_EXPIRED)
   1476 		g_string_append(errmsg, "The certificate has expired.<br>");
   1477 	if (err & G_TLS_CERTIFICATE_REVOKED)
   1478 		g_string_append(errmsg,
   1479 		    "The certificate has been revoked according to "
   1480 		    "the GTlsConnection's certificate revocation list.<br>");
   1481 	if (err & G_TLS_CERTIFICATE_INSECURE)
   1482 		g_string_append(errmsg,
   1483 		    "The certificate's algorithm is considered insecure.<br>");
   1484 	if (err & G_TLS_CERTIFICATE_GENERIC_ERROR)
   1485 		g_string_append(errmsg,
   1486 		    "Some error occurred validating the certificate.<br>");
   1487 
   1488 	g_object_get(cert, "certificate-pem", &pem, NULL);
   1489 	html = g_strdup_printf("<p>Could not validate TLS for “%s”<br>%s</p>"
   1490 	                       "<p>You can inspect the following certificate "
   1491 	                       "with Ctrl-t (default keybinding).</p>"
   1492 	                       "<p><pre>%s</pre></p>", uri, errmsg->str, pem);
   1493 	g_free(pem);
   1494 	g_string_free(errmsg, TRUE);
   1495 
   1496 	webkit_web_view_load_alternate_html(c->view, html, uri, NULL);
   1497 	g_free(html);
   1498 
   1499 	return TRUE;
   1500 }
   1501 
   1502 void
   1503 loadchanged(WebKitWebView *v, WebKitLoadEvent e, Client *c)
   1504 {
   1505 	const char *uri = geturi(c);
   1506 
   1507 	switch (e) {
   1508 	case WEBKIT_LOAD_STARTED:
   1509 		setatom(c, AtomUri, uri);
   1510 		c->title = uri;
   1511 		c->https = c->insecure = 0;
   1512 		seturiparameters(c, uri, loadtransient);
   1513 		if (c->errorpage)
   1514 			c->errorpage = 0;
   1515 		else
   1516 			g_clear_object(&c->failedcert);
   1517 		break;
   1518 	case WEBKIT_LOAD_REDIRECTED:
   1519 		setatom(c, AtomUri, uri);
   1520 		c->title = uri;
   1521 		seturiparameters(c, uri, loadtransient);
   1522 		break;
   1523 	case WEBKIT_LOAD_COMMITTED:
   1524 		setatom(c, AtomUri, uri);
   1525 		c->title = uri;
   1526 		seturiparameters(c, uri, loadcommitted);
   1527 		c->https = webkit_web_view_get_tls_info(c->view, &c->cert,
   1528 		                                        &c->tlserr);
   1529 		break;
   1530 	case WEBKIT_LOAD_FINISHED:
   1531 		seturiparameters(c, uri, loadfinished);
   1532 		/* Disabled until we write some WebKitWebExtension for
   1533 		 * manipulating the DOM directly.
   1534 		evalscript(c, "document.documentElement.style.overflow = '%s'",
   1535 		    enablescrollbars ? "auto" : "hidden");
   1536 		*/
   1537 		runscript(c);
   1538 		break;
   1539 	}
   1540 	updatetitle(c);
   1541 }
   1542 
   1543 void
   1544 progresschanged(WebKitWebView *v, GParamSpec *ps, Client *c)
   1545 {
   1546 	c->progress = webkit_web_view_get_estimated_load_progress(c->view) *
   1547 	              100;
   1548 	updatetitle(c);
   1549 }
   1550 
   1551 void
   1552 titlechanged(WebKitWebView *view, GParamSpec *ps, Client *c)
   1553 {
   1554 	c->title = webkit_web_view_get_title(c->view);
   1555 	updatetitle(c);
   1556 }
   1557 
   1558 void
   1559 mousetargetchanged(WebKitWebView *v, WebKitHitTestResult *h, guint modifiers,
   1560     Client *c)
   1561 {
   1562 	WebKitHitTestResultContext hc = webkit_hit_test_result_get_context(h);
   1563 
   1564 	/* Keep the hit test to know where is the pointer on the next click */
   1565 	c->mousepos = h;
   1566 
   1567 	if (hc & OnLink)
   1568 		c->targeturi = webkit_hit_test_result_get_link_uri(h);
   1569 	else if (hc & OnImg)
   1570 		c->targeturi = webkit_hit_test_result_get_image_uri(h);
   1571 	else if (hc & OnMedia)
   1572 		c->targeturi = webkit_hit_test_result_get_media_uri(h);
   1573 	else
   1574 		c->targeturi = NULL;
   1575 
   1576 	c->overtitle = c->targeturi;
   1577 	updatetitle(c);
   1578 }
   1579 
   1580 gboolean
   1581 permissionrequested(WebKitWebView *v, WebKitPermissionRequest *r, Client *c)
   1582 {
   1583 	ParamName param = ParameterLast;
   1584 
   1585 	if (WEBKIT_IS_GEOLOCATION_PERMISSION_REQUEST(r)) {
   1586 		param = Geolocation;
   1587 	} else if (WEBKIT_IS_USER_MEDIA_PERMISSION_REQUEST(r)) {
   1588 		if (webkit_user_media_permission_is_for_audio_device(
   1589 		    WEBKIT_USER_MEDIA_PERMISSION_REQUEST(r)))
   1590 			param = AccessMicrophone;
   1591 		else if (webkit_user_media_permission_is_for_video_device(
   1592 		         WEBKIT_USER_MEDIA_PERMISSION_REQUEST(r)))
   1593 			param = AccessWebcam;
   1594 	} else {
   1595 		return FALSE;
   1596 	}
   1597 
   1598 	if (curconfig[param].val.i)
   1599 		webkit_permission_request_allow(r);
   1600 	else
   1601 		webkit_permission_request_deny(r);
   1602 
   1603 	return TRUE;
   1604 }
   1605 
   1606 gboolean
   1607 decidepolicy(WebKitWebView *v, WebKitPolicyDecision *d,
   1608     WebKitPolicyDecisionType dt, Client *c)
   1609 {
   1610 	switch (dt) {
   1611 	case WEBKIT_POLICY_DECISION_TYPE_NAVIGATION_ACTION:
   1612 		decidenavigation(d, c);
   1613 		break;
   1614 	case WEBKIT_POLICY_DECISION_TYPE_NEW_WINDOW_ACTION:
   1615 		decidenewwindow(d, c);
   1616 		break;
   1617 	case WEBKIT_POLICY_DECISION_TYPE_RESPONSE:
   1618 		decideresource(d, c);
   1619 		break;
   1620 	default:
   1621 		webkit_policy_decision_ignore(d);
   1622 		break;
   1623 	}
   1624 	return TRUE;
   1625 }
   1626 
   1627 void
   1628 decidenavigation(WebKitPolicyDecision *d, Client *c)
   1629 {
   1630 	WebKitNavigationAction *a =
   1631 	    webkit_navigation_policy_decision_get_navigation_action(
   1632 	    WEBKIT_NAVIGATION_POLICY_DECISION(d));
   1633 
   1634 	switch (webkit_navigation_action_get_navigation_type(a)) {
   1635 	case WEBKIT_NAVIGATION_TYPE_LINK_CLICKED: /* fallthrough */
   1636 	case WEBKIT_NAVIGATION_TYPE_FORM_SUBMITTED: /* fallthrough */
   1637 	case WEBKIT_NAVIGATION_TYPE_BACK_FORWARD: /* fallthrough */
   1638 	case WEBKIT_NAVIGATION_TYPE_RELOAD: /* fallthrough */
   1639 	case WEBKIT_NAVIGATION_TYPE_FORM_RESUBMITTED: /* fallthrough */
   1640 	case WEBKIT_NAVIGATION_TYPE_OTHER: /* fallthrough */
   1641 	default:
   1642 		/* Do not navigate to links with a "_blank" target (popup) */
   1643 		if (webkit_navigation_policy_decision_get_frame_name(
   1644 		    WEBKIT_NAVIGATION_POLICY_DECISION(d))) {
   1645 			webkit_policy_decision_ignore(d);
   1646 		} else {
   1647 			/* Filter out navigation to different domain ? */
   1648 			/* get action→urirequest, copy and load in new window+view
   1649 			 * on Ctrl+Click ? */
   1650 			webkit_policy_decision_use(d);
   1651 		}
   1652 		break;
   1653 	}
   1654 }
   1655 
   1656 void
   1657 decidenewwindow(WebKitPolicyDecision *d, Client *c)
   1658 {
   1659 	Arg arg;
   1660 	WebKitNavigationAction *a =
   1661 	    webkit_navigation_policy_decision_get_navigation_action(
   1662 	    WEBKIT_NAVIGATION_POLICY_DECISION(d));
   1663 
   1664 
   1665 	switch (webkit_navigation_action_get_navigation_type(a)) {
   1666 	case WEBKIT_NAVIGATION_TYPE_LINK_CLICKED: /* fallthrough */
   1667 	case WEBKIT_NAVIGATION_TYPE_FORM_SUBMITTED: /* fallthrough */
   1668 	case WEBKIT_NAVIGATION_TYPE_BACK_FORWARD: /* fallthrough */
   1669 	case WEBKIT_NAVIGATION_TYPE_RELOAD: /* fallthrough */
   1670 	case WEBKIT_NAVIGATION_TYPE_FORM_RESUBMITTED:
   1671 		/* Filter domains here */
   1672 /* If the value of “mouse-button” is not 0, then the navigation was triggered by a mouse event.
   1673  * test for link clicked but no button ? */
   1674 		arg.v = webkit_uri_request_get_uri(
   1675 		        webkit_navigation_action_get_request(a));
   1676 		newwindow(c, &arg, 0);
   1677 		break;
   1678 	case WEBKIT_NAVIGATION_TYPE_OTHER: /* fallthrough */
   1679 	default:
   1680 		break;
   1681 	}
   1682 
   1683 	webkit_policy_decision_ignore(d);
   1684 }
   1685 
   1686 void
   1687 decideresource(WebKitPolicyDecision *d, Client *c)
   1688 {
   1689 	int i, isascii = 1;
   1690 	WebKitResponsePolicyDecision *r = WEBKIT_RESPONSE_POLICY_DECISION(d);
   1691 	WebKitURIResponse *res =
   1692 	    webkit_response_policy_decision_get_response(r);
   1693 	const gchar *uri = webkit_uri_response_get_uri(res);
   1694 
   1695 	if (g_str_has_suffix(uri, "/favicon.ico")) {
   1696 		webkit_policy_decision_ignore(d);
   1697 		return;
   1698 	}
   1699 
   1700 	if (!g_str_has_prefix(uri, "http://")
   1701 	    && !g_str_has_prefix(uri, "https://")
   1702 	    && !g_str_has_prefix(uri, "about:")
   1703 	    && !g_str_has_prefix(uri, "file://")
   1704 	    && !g_str_has_prefix(uri, "data:")
   1705 	    && !g_str_has_prefix(uri, "blob:")
   1706 	    && strlen(uri) > 0) {
   1707 		for (i = 0; i < strlen(uri); i++) {
   1708 			if (!g_ascii_isprint(uri[i])) {
   1709 				isascii = 0;
   1710 				break;
   1711 			}
   1712 		}
   1713 		if (isascii) {
   1714 			handleplumb(c, uri);
   1715 			webkit_policy_decision_ignore(d);
   1716 			return;
   1717 		}
   1718 	}
   1719 
   1720 	if (webkit_response_policy_decision_is_mime_type_supported(r)) {
   1721 		webkit_policy_decision_use(d);
   1722 	} else {
   1723 		webkit_policy_decision_ignore(d);
   1724 		download(c, res);
   1725 	}
   1726 }
   1727 
   1728 void
   1729 insecurecontent(WebKitWebView *v, WebKitInsecureContentEvent e, Client *c)
   1730 {
   1731 	c->insecure = 1;
   1732 }
   1733 
   1734 void
   1735 downloadstarted(WebKitWebContext *wc, WebKitDownload *d, Client *c)
   1736 {
   1737 	g_signal_connect(G_OBJECT(d), "notify::response",
   1738 	                 G_CALLBACK(responsereceived), c);
   1739 }
   1740 
   1741 void
   1742 responsereceived(WebKitDownload *d, GParamSpec *ps, Client *c)
   1743 {
   1744 	download(c, webkit_download_get_response(d));
   1745 	webkit_download_cancel(d);
   1746 }
   1747 
   1748 void
   1749 download(Client *c, WebKitURIResponse *r)
   1750 {
   1751 	Arg a = (Arg)DOWNLOAD(webkit_uri_response_get_uri(r), geturi(c));
   1752 	spawn(c, &a);
   1753 }
   1754 
   1755 void
   1756 webprocessterminated(WebKitWebView *v, WebKitWebProcessTerminationReason r,
   1757                      Client *c)
   1758 {
   1759 	fprintf(stderr, "web process terminated: %s\n",
   1760 	        r == WEBKIT_WEB_PROCESS_CRASHED ? "crashed" : "no memory");
   1761 	closeview(v, c);
   1762 }
   1763 
   1764 void
   1765 closeview(WebKitWebView *v, Client *c)
   1766 {
   1767 	gtk_widget_destroy(c->win);
   1768 }
   1769 
   1770 void
   1771 destroywin(GtkWidget* w, Client *c)
   1772 {
   1773 	destroyclient(c);
   1774 	if (!clients)
   1775 		gtk_main_quit();
   1776 }
   1777 
   1778 void
   1779 pasteuri(GtkClipboard *clipboard, const char *text, gpointer d)
   1780 {
   1781 	Arg a = {.v = text };
   1782 	if (text)
   1783 		loaduri((Client *) d, &a);
   1784 }
   1785 
   1786 void
   1787 reload(Client *c, const Arg *a)
   1788 {
   1789 	if (a->i)
   1790 		webkit_web_view_reload_bypass_cache(c->view);
   1791 	else
   1792 		webkit_web_view_reload(c->view);
   1793 }
   1794 
   1795 void
   1796 print(Client *c, const Arg *a)
   1797 {
   1798 	webkit_print_operation_run_dialog(webkit_print_operation_new(c->view),
   1799 	                                  GTK_WINDOW(c->win));
   1800 }
   1801 
   1802 void
   1803 showcert(Client *c, const Arg *a)
   1804 {
   1805 	GTlsCertificate *cert = c->failedcert ? c->failedcert : c->cert;
   1806 	GcrCertificate *gcrt;
   1807 	GByteArray *crt;
   1808 	GtkWidget *win;
   1809 	GcrCertificateWidget *wcert;
   1810 
   1811 	if (!cert)
   1812 		return;
   1813 
   1814 	g_object_get(cert, "certificate", &crt, NULL);
   1815 	gcrt = gcr_simple_certificate_new(crt->data, crt->len);
   1816 	g_byte_array_unref(crt);
   1817 
   1818 	win = gtk_window_new(GTK_WINDOW_TOPLEVEL);
   1819 	wcert = gcr_certificate_widget_new(gcrt);
   1820 	g_object_unref(gcrt);
   1821 
   1822 	gtk_container_add(GTK_CONTAINER(win), GTK_WIDGET(wcert));
   1823 	gtk_widget_show_all(win);
   1824 }
   1825 
   1826 void
   1827 clipboard(Client *c, const Arg *a)
   1828 {
   1829 	if (a->i) { /* load clipboard uri */
   1830 		gtk_clipboard_request_text(gtk_clipboard_get(
   1831 		                           GDK_SELECTION_PRIMARY),
   1832 		                           pasteuri, c);
   1833 	} else { /* copy uri */
   1834 		gtk_clipboard_set_text(gtk_clipboard_get(
   1835 		                       GDK_SELECTION_PRIMARY), c->targeturi
   1836 		                       ? c->targeturi : geturi(c), -1);
   1837 	}
   1838 }
   1839 
   1840 void
   1841 zoom(Client *c, const Arg *a)
   1842 {
   1843 	if (a->i > 0)
   1844 		webkit_web_view_set_zoom_level(c->view,
   1845 		                               curconfig[ZoomLevel].val.f + 0.1);
   1846 	else if (a->i < 0)
   1847 		webkit_web_view_set_zoom_level(c->view,
   1848 		                               curconfig[ZoomLevel].val.f - 0.1);
   1849 	else
   1850 		webkit_web_view_set_zoom_level(c->view, 1.0);
   1851 
   1852 	curconfig[ZoomLevel].val.f = webkit_web_view_get_zoom_level(c->view);
   1853 }
   1854 
   1855 static void
   1856 msgext(Client *c, char type, const Arg *a)
   1857 {
   1858 	static char msg[MSGBUFSZ];
   1859 	int ret;
   1860 
   1861 	if (spair[0] < 0)
   1862 		return;
   1863 
   1864 	if ((ret = snprintf(msg, sizeof(msg), "%c%c%c", c->pageid, type, a->i))
   1865 	    >= sizeof(msg)) {
   1866 		fprintf(stderr, "surf: message too long: %d\n", ret);
   1867 		return;
   1868 	}
   1869 
   1870 	if (send(spair[0], msg, ret, 0) != ret)
   1871 		fprintf(stderr, "surf: error sending: %u%c%d (%d)\n",
   1872 		        c->pageid, type, a->i, ret);
   1873 }
   1874 
   1875 void
   1876 scrollv(Client *c, const Arg *a)
   1877 {
   1878 	msgext(c, 'v', a);
   1879 }
   1880 
   1881 void
   1882 scrollh(Client *c, const Arg *a)
   1883 {
   1884 	msgext(c, 'h', a);
   1885 }
   1886 
   1887 void
   1888 navigate(Client *c, const Arg *a)
   1889 {
   1890 	if (a->i < 0)
   1891 		webkit_web_view_go_back(c->view);
   1892 	else if (a->i > 0)
   1893 		webkit_web_view_go_forward(c->view);
   1894 }
   1895 
   1896 void
   1897 stop(Client *c, const Arg *a)
   1898 {
   1899 	webkit_web_view_stop_loading(c->view);
   1900 }
   1901 
   1902 void
   1903 toggle(Client *c, const Arg *a)
   1904 {
   1905 	curconfig[a->i].val.i ^= 1;
   1906 	setparameter(c, 1, (ParamName)a->i, &curconfig[a->i].val);
   1907 }
   1908 
   1909 void
   1910 togglefullscreen(Client *c, const Arg *a)
   1911 {
   1912 	/* toggling value is handled in winevent() */
   1913 	if (c->fullscreen)
   1914 		gtk_window_unfullscreen(GTK_WINDOW(c->win));
   1915 	else
   1916 		gtk_window_fullscreen(GTK_WINDOW(c->win));
   1917 }
   1918 
   1919 void
   1920 togglecookiepolicy(Client *c, const Arg *a)
   1921 {
   1922 	++cookiepolicy;
   1923 	cookiepolicy %= strlen(curconfig[CookiePolicies].val.v);
   1924 
   1925 	setparameter(c, 0, CookiePolicies, NULL);
   1926 }
   1927 
   1928 void
   1929 toggleinspector(Client *c, const Arg *a)
   1930 {
   1931 	if (webkit_web_inspector_is_attached(c->inspector))
   1932 		webkit_web_inspector_close(c->inspector);
   1933 	else if (curconfig[Inspector].val.i)
   1934 		webkit_web_inspector_show(c->inspector);
   1935 }
   1936 
   1937 void
   1938 find(Client *c, const Arg *a)
   1939 {
   1940 	const char *s, *f;
   1941 
   1942 	if (a && a->i) {
   1943 		if (a->i > 0)
   1944 			webkit_find_controller_search_next(c->finder);
   1945 		else
   1946 			webkit_find_controller_search_previous(c->finder);
   1947 	} else {
   1948 		s = getatom(c, AtomFind);
   1949 		f = webkit_find_controller_get_search_text(c->finder);
   1950 
   1951 		if (g_strcmp0(f, s) == 0) /* reset search */
   1952 			webkit_find_controller_search(c->finder, "", findopts,
   1953 			                              G_MAXUINT);
   1954 
   1955 		webkit_find_controller_search(c->finder, s, findopts,
   1956 		                              G_MAXUINT);
   1957 
   1958 		if (strcmp(s, "") == 0)
   1959 			webkit_find_controller_search_finish(c->finder);
   1960 	}
   1961 }
   1962 
   1963 void
   1964 clicknavigate(Client *c, const Arg *a, WebKitHitTestResult *h)
   1965 {
   1966 	navigate(c, a);
   1967 }
   1968 
   1969 void
   1970 clicknewwindow(Client *c, const Arg *a, WebKitHitTestResult *h)
   1971 {
   1972 	Arg arg;
   1973 
   1974 	arg.v = webkit_hit_test_result_get_link_uri(h);
   1975 	newwindow(c, &arg, a->i);
   1976 }
   1977 
   1978 void
   1979 clickexternplayer(Client *c, const Arg *a, WebKitHitTestResult *h)
   1980 {
   1981 	Arg arg;
   1982 
   1983 	arg = (Arg)VIDEOPLAY(webkit_hit_test_result_get_media_uri(h));
   1984 	spawn(c, &arg);
   1985 }
   1986 
   1987 int
   1988 main(int argc, char *argv[])
   1989 {
   1990 	Arg arg;
   1991 	Client *c;
   1992 
   1993 	memset(&arg, 0, sizeof(arg));
   1994 
   1995 	/* command line args */
   1996 	ARGBEGIN {
   1997 	case 'a':
   1998 		defconfig[CookiePolicies].val.v = EARGF(usage());
   1999 		defconfig[CookiePolicies].prio = 2;
   2000 		break;
   2001 	case 'b':
   2002 		defconfig[ScrollBars].val.i = 0;
   2003 		defconfig[ScrollBars].prio = 2;
   2004 		break;
   2005 	case 'B':
   2006 		defconfig[ScrollBars].val.i = 1;
   2007 		defconfig[ScrollBars].prio = 2;
   2008 		break;
   2009 	case 'c':
   2010 		cookiefile = EARGF(usage());
   2011 		break;
   2012 	case 'C':
   2013 		stylefile = EARGF(usage());
   2014 		break;
   2015 	case 'd':
   2016 		defconfig[DiskCache].val.i = 0;
   2017 		defconfig[DiskCache].prio = 2;
   2018 		break;
   2019 	case 'D':
   2020 		defconfig[DiskCache].val.i = 1;
   2021 		defconfig[DiskCache].prio = 2;
   2022 		break;
   2023 	case 'e':
   2024 		embed = strtol(EARGF(usage()), NULL, 0);
   2025 		break;
   2026 	case 'f':
   2027 		defconfig[RunInFullscreen].val.i = 0;
   2028 		defconfig[RunInFullscreen].prio = 2;
   2029 		break;
   2030 	case 'F':
   2031 		defconfig[RunInFullscreen].val.i = 1;
   2032 		defconfig[RunInFullscreen].prio = 2;
   2033 		break;
   2034 	case 'g':
   2035 		defconfig[Geolocation].val.i = 0;
   2036 		defconfig[Geolocation].prio = 2;
   2037 		break;
   2038 	case 'G':
   2039 		defconfig[Geolocation].val.i = 1;
   2040 		defconfig[Geolocation].prio = 2;
   2041 		break;
   2042 	case 'i':
   2043 		defconfig[LoadImages].val.i = 0;
   2044 		defconfig[LoadImages].prio = 2;
   2045 		break;
   2046 	case 'I':
   2047 		defconfig[LoadImages].val.i = 1;
   2048 		defconfig[LoadImages].prio = 2;
   2049 		break;
   2050 	case 'k':
   2051 		defconfig[KioskMode].val.i = 0;
   2052 		defconfig[KioskMode].prio = 2;
   2053 		break;
   2054 	case 'K':
   2055 		defconfig[KioskMode].val.i = 1;
   2056 		defconfig[KioskMode].prio = 2;
   2057 		break;
   2058 	case 'm':
   2059 		defconfig[Style].val.i = 0;
   2060 		defconfig[Style].prio = 2;
   2061 		break;
   2062 	case 'M':
   2063 		defconfig[Style].val.i = 1;
   2064 		defconfig[Style].prio = 2;
   2065 		break;
   2066 	case 'n':
   2067 		defconfig[Inspector].val.i = 0;
   2068 		defconfig[Inspector].prio = 2;
   2069 		break;
   2070 	case 'N':
   2071 		defconfig[Inspector].val.i = 1;
   2072 		defconfig[Inspector].prio = 2;
   2073 		break;
   2074 	case 'r':
   2075 		scriptfile = EARGF(usage());
   2076 		break;
   2077 	case 's':
   2078 		defconfig[JavaScript].val.i = 0;
   2079 		defconfig[JavaScript].prio = 2;
   2080 		break;
   2081 	case 'S':
   2082 		defconfig[JavaScript].val.i = 1;
   2083 		defconfig[JavaScript].prio = 2;
   2084 		break;
   2085 	case 't':
   2086 		defconfig[StrictTLS].val.i = 0;
   2087 		defconfig[StrictTLS].prio = 2;
   2088 		break;
   2089 	case 'T':
   2090 		defconfig[StrictTLS].val.i = 1;
   2091 		defconfig[StrictTLS].prio = 2;
   2092 		break;
   2093 	case 'u':
   2094 		fulluseragent = EARGF(usage());
   2095 		break;
   2096 	case 'v':
   2097 		die("surf-"VERSION", see LICENSE for © details\n");
   2098 	case 'w':
   2099 		showxid = 1;
   2100 		break;
   2101 	case 'x':
   2102 		defconfig[Certificate].val.i = 0;
   2103 		defconfig[Certificate].prio = 2;
   2104 		break;
   2105 	case 'X':
   2106 		defconfig[Certificate].val.i = 1;
   2107 		defconfig[Certificate].prio = 2;
   2108 		break;
   2109 	case 'z':
   2110 		defconfig[ZoomLevel].val.f = strtof(EARGF(usage()), NULL);
   2111 		defconfig[ZoomLevel].prio = 2;
   2112 		break;
   2113 	default:
   2114 		usage();
   2115 	} ARGEND;
   2116 	if (argc > 0)
   2117 		arg.v = argv[0];
   2118 	else
   2119 		arg.v = "about:blank";
   2120 
   2121 	setup();
   2122 	c = newclient(NULL);
   2123 	showview(NULL, c);
   2124 
   2125 	loaduri(c, &arg);
   2126 	updatetitle(c);
   2127 
   2128 	gtk_main();
   2129 	cleanup();
   2130 
   2131 	return 0;
   2132 }