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