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