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