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