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