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