surf

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

surf.c (53261B)


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