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