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