Send message size inside messages through pipes
[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         static char msg[MSGBUFSZ], msgsz;
1213         GError *gerr = NULL;
1214
1215         if (g_io_channel_read_chars(s, msg, sizeof(msg), NULL, &gerr) !=
1216             G_IO_STATUS_NORMAL) {
1217                 fprintf(stderr, "surf: error reading pipe: %s\n",
1218                         gerr->message);
1219                 g_error_free(gerr);
1220                 return TRUE;
1221         }
1222         if ((msgsz = msg[0]) < 3) {
1223                 fprintf(stderr, "surf: message too short: %d\n", msgsz);
1224                 return TRUE;
1225         }
1226
1227         switch (msg[2]) {
1228         case 'i':
1229                 close(pipein[1]);
1230                 close(pipeout[0]);
1231                 break;
1232         }
1233
1234         return TRUE;
1235 }
1236
1237 void
1238 initwebextensions(WebKitWebContext *wc, Client *c)
1239 {
1240         GVariant *gv;
1241
1242         if (!pipeout[0] || !pipein[1])
1243                 return;
1244
1245         gv = g_variant_new("(ii)", pipeout[0], pipein[1]);
1246
1247         webkit_web_context_set_web_extensions_initialization_user_data(wc, gv);
1248         webkit_web_context_set_web_extensions_directory(wc, WEBEXTDIR);
1249 }
1250
1251 GtkWidget *
1252 createview(WebKitWebView *v, WebKitNavigationAction *a, Client *c)
1253 {
1254         Client *n;
1255
1256         switch (webkit_navigation_action_get_navigation_type(a)) {
1257         case WEBKIT_NAVIGATION_TYPE_OTHER: /* fallthrough */
1258                 /*
1259                  * popup windows of type “other” are almost always triggered
1260                  * by user gesture, so inverse the logic here
1261                  */
1262 /* instead of this, compare destination uri to mouse-over uri for validating window */
1263                 if (webkit_navigation_action_is_user_gesture(a))
1264                         return NULL;
1265         case WEBKIT_NAVIGATION_TYPE_LINK_CLICKED: /* fallthrough */
1266         case WEBKIT_NAVIGATION_TYPE_FORM_SUBMITTED: /* fallthrough */
1267         case WEBKIT_NAVIGATION_TYPE_BACK_FORWARD: /* fallthrough */
1268         case WEBKIT_NAVIGATION_TYPE_RELOAD: /* fallthrough */
1269         case WEBKIT_NAVIGATION_TYPE_FORM_RESUBMITTED:
1270                 n = newclient(c);
1271                 break;
1272         default:
1273                 return NULL;
1274         }
1275
1276         return GTK_WIDGET(n->view);
1277 }
1278
1279 gboolean
1280 buttonreleased(GtkWidget *w, GdkEvent *e, Client *c)
1281 {
1282         WebKitHitTestResultContext element;
1283         int i;
1284
1285         element = webkit_hit_test_result_get_context(c->mousepos);
1286
1287         for (i = 0; i < LENGTH(buttons); ++i) {
1288                 if (element & buttons[i].target &&
1289                     e->button.button == buttons[i].button &&
1290                     CLEANMASK(e->button.state) == CLEANMASK(buttons[i].mask) &&
1291                     buttons[i].func) {
1292                         buttons[i].func(c, &buttons[i].arg, c->mousepos);
1293                         return buttons[i].stopevent;
1294                 }
1295         }
1296
1297         return FALSE;
1298 }
1299
1300 GdkFilterReturn
1301 processx(GdkXEvent *e, GdkEvent *event, gpointer d)
1302 {
1303         Client *c = (Client *)d;
1304         XPropertyEvent *ev;
1305         Arg a;
1306
1307         if (((XEvent *)e)->type == PropertyNotify) {
1308                 ev = &((XEvent *)e)->xproperty;
1309                 if (ev->state == PropertyNewValue) {
1310                         if (ev->atom == atoms[AtomFind]) {
1311                                 find(c, NULL);
1312
1313                                 return GDK_FILTER_REMOVE;
1314                         } else if (ev->atom == atoms[AtomGo]) {
1315                                 a.v = getatom(c, AtomGo);
1316                                 loaduri(c, &a);
1317
1318                                 return GDK_FILTER_REMOVE;
1319                         }
1320                 }
1321         }
1322         return GDK_FILTER_CONTINUE;
1323 }
1324
1325 gboolean
1326 winevent(GtkWidget *w, GdkEvent *e, Client *c)
1327 {
1328         int i;
1329
1330         switch (e->type) {
1331         case GDK_ENTER_NOTIFY:
1332                 c->overtitle = c->targeturi;
1333                 updatetitle(c);
1334                 break;
1335         case GDK_KEY_PRESS:
1336                 if (!curconfig[KioskMode].val.i) {
1337                         for (i = 0; i < LENGTH(keys); ++i) {
1338                                 if (gdk_keyval_to_lower(e->key.keyval) ==
1339                                     keys[i].keyval &&
1340                                     CLEANMASK(e->key.state) == keys[i].mod &&
1341                                     keys[i].func) {
1342                                         updatewinid(c);
1343                                         keys[i].func(c, &(keys[i].arg));
1344                                         return TRUE;
1345                                 }
1346                         }
1347                 }
1348         case GDK_LEAVE_NOTIFY:
1349                 c->overtitle = NULL;
1350                 updatetitle(c);
1351                 break;
1352         case GDK_WINDOW_STATE:
1353                 if (e->window_state.changed_mask ==
1354                     GDK_WINDOW_STATE_FULLSCREEN)
1355                         c->fullscreen = e->window_state.new_window_state &
1356                                         GDK_WINDOW_STATE_FULLSCREEN;
1357                 break;
1358         default:
1359                 break;
1360         }
1361
1362         return FALSE;
1363 }
1364
1365 void
1366 showview(WebKitWebView *v, Client *c)
1367 {
1368         GdkRGBA bgcolor = { 0 };
1369         GdkWindow *gwin;
1370
1371         c->finder = webkit_web_view_get_find_controller(c->view);
1372         c->inspector = webkit_web_view_get_inspector(c->view);
1373
1374         c->pageid = webkit_web_view_get_page_id(c->view);
1375         c->win = createwindow(c);
1376
1377         gtk_container_add(GTK_CONTAINER(c->win), GTK_WIDGET(c->view));
1378         gtk_widget_show_all(c->win);
1379         gtk_widget_grab_focus(GTK_WIDGET(c->view));
1380
1381         gwin = gtk_widget_get_window(GTK_WIDGET(c->win));
1382         c->xid = gdk_x11_window_get_xid(gwin);
1383         updatewinid(c);
1384         if (showxid) {
1385                 gdk_display_sync(gtk_widget_get_display(c->win));
1386                 puts(winid);
1387                 fflush(stdout);
1388         }
1389
1390         if (curconfig[HideBackground].val.i)
1391                 webkit_web_view_set_background_color(c->view, &bgcolor);
1392
1393         if (!curconfig[KioskMode].val.i) {
1394                 gdk_window_set_events(gwin, GDK_ALL_EVENTS_MASK);
1395                 gdk_window_add_filter(gwin, processx, c);
1396         }
1397
1398         if (curconfig[RunInFullscreen].val.i)
1399                 togglefullscreen(c, NULL);
1400
1401         if (curconfig[ZoomLevel].val.f != 1.0)
1402                 webkit_web_view_set_zoom_level(c->view,
1403                                                curconfig[ZoomLevel].val.f);
1404
1405         setatom(c, AtomFind, "");
1406         setatom(c, AtomUri, "about:blank");
1407 }
1408
1409 GtkWidget *
1410 createwindow(Client *c)
1411 {
1412         char *wmstr;
1413         GtkWidget *w;
1414
1415         if (embed) {
1416                 w = gtk_plug_new(embed);
1417         } else {
1418                 w = gtk_window_new(GTK_WINDOW_TOPLEVEL);
1419
1420                 wmstr = g_path_get_basename(argv0);
1421                 gtk_window_set_wmclass(GTK_WINDOW(w), wmstr, "Surf");
1422                 g_free(wmstr);
1423
1424                 wmstr = g_strdup_printf("%s[%lu]", "Surf", c->pageid);
1425                 gtk_window_set_role(GTK_WINDOW(w), wmstr);
1426                 g_free(wmstr);
1427
1428                 gtk_window_set_default_size(GTK_WINDOW(w), winsize[0], winsize[1]);
1429         }
1430
1431         g_signal_connect(G_OBJECT(w), "destroy",
1432                          G_CALLBACK(destroywin), c);
1433         g_signal_connect(G_OBJECT(w), "enter-notify-event",
1434                          G_CALLBACK(winevent), c);
1435         g_signal_connect(G_OBJECT(w), "key-press-event",
1436                          G_CALLBACK(winevent), c);
1437         g_signal_connect(G_OBJECT(w), "leave-notify-event",
1438                          G_CALLBACK(winevent), c);
1439         g_signal_connect(G_OBJECT(w), "window-state-event",
1440                          G_CALLBACK(winevent), c);
1441
1442         return w;
1443 }
1444
1445 gboolean
1446 loadfailedtls(WebKitWebView *v, gchar *uri, GTlsCertificate *cert,
1447               GTlsCertificateFlags err, Client *c)
1448 {
1449         GString *errmsg = g_string_new(NULL);
1450         gchar *html, *pem;
1451
1452         c->failedcert = g_object_ref(cert);
1453         c->tlserr = err;
1454         c->errorpage = 1;
1455
1456         if (err & G_TLS_CERTIFICATE_UNKNOWN_CA)
1457                 g_string_append(errmsg,
1458                     "The signing certificate authority is not known.<br>");
1459         if (err & G_TLS_CERTIFICATE_BAD_IDENTITY)
1460                 g_string_append(errmsg,
1461                     "The certificate does not match the expected identity "
1462                     "of the site that it was retrieved from.<br>");
1463         if (err & G_TLS_CERTIFICATE_NOT_ACTIVATED)
1464                 g_string_append(errmsg,
1465                     "The certificate's activation time "
1466                     "is still in the future.<br>");
1467         if (err & G_TLS_CERTIFICATE_EXPIRED)
1468                 g_string_append(errmsg, "The certificate has expired.<br>");
1469         if (err & G_TLS_CERTIFICATE_REVOKED)
1470                 g_string_append(errmsg,
1471                     "The certificate has been revoked according to "
1472                     "the GTlsConnection's certificate revocation list.<br>");
1473         if (err & G_TLS_CERTIFICATE_INSECURE)
1474                 g_string_append(errmsg,
1475                     "The certificate's algorithm is considered insecure.<br>");
1476         if (err & G_TLS_CERTIFICATE_GENERIC_ERROR)
1477                 g_string_append(errmsg,
1478                     "Some error occurred validating the certificate.<br>");
1479
1480         g_object_get(cert, "certificate-pem", &pem, NULL);
1481         html = g_strdup_printf("<p>Could not validate TLS for “%s”<br>%s</p>"
1482                                "<p>You can inspect the following certificate "
1483                                "with Ctrl-t (default keybinding).</p>"
1484                                "<p><pre>%s</pre></p>", uri, errmsg->str, pem);
1485         g_free(pem);
1486         g_string_free(errmsg, TRUE);
1487
1488         webkit_web_view_load_alternate_html(c->view, html, uri, NULL);
1489         g_free(html);
1490
1491         return TRUE;
1492 }
1493
1494 void
1495 loadchanged(WebKitWebView *v, WebKitLoadEvent e, Client *c)
1496 {
1497         const char *uri = geturi(c);
1498
1499         switch (e) {
1500         case WEBKIT_LOAD_STARTED:
1501                 setatom(c, AtomUri, uri);
1502                 c->title = uri;
1503                 c->https = c->insecure = 0;
1504                 seturiparameters(c, uri, loadtransient);
1505                 if (c->errorpage)
1506                         c->errorpage = 0;
1507                 else
1508                         g_clear_object(&c->failedcert);
1509                 break;
1510         case WEBKIT_LOAD_REDIRECTED:
1511                 setatom(c, AtomUri, uri);
1512                 c->title = uri;
1513                 seturiparameters(c, uri, loadtransient);
1514                 break;
1515         case WEBKIT_LOAD_COMMITTED:
1516                 seturiparameters(c, uri, loadcommitted);
1517                 c->https = webkit_web_view_get_tls_info(c->view, &c->cert,
1518                                                         &c->tlserr);
1519                 break;
1520         case WEBKIT_LOAD_FINISHED:
1521                 seturiparameters(c, uri, loadfinished);
1522                 /* Disabled until we write some WebKitWebExtension for
1523                  * manipulating the DOM directly.
1524                 evalscript(c, "document.documentElement.style.overflow = '%s'",
1525                     enablescrollbars ? "auto" : "hidden");
1526                 */
1527                 runscript(c);
1528                 break;
1529         }
1530         updatetitle(c);
1531 }
1532
1533 void
1534 progresschanged(WebKitWebView *v, GParamSpec *ps, Client *c)
1535 {
1536         c->progress = webkit_web_view_get_estimated_load_progress(c->view) *
1537                       100;
1538         updatetitle(c);
1539 }
1540
1541 void
1542 titlechanged(WebKitWebView *view, GParamSpec *ps, Client *c)
1543 {
1544         c->title = webkit_web_view_get_title(c->view);
1545         updatetitle(c);
1546 }
1547
1548 void
1549 mousetargetchanged(WebKitWebView *v, WebKitHitTestResult *h, guint modifiers,
1550     Client *c)
1551 {
1552         WebKitHitTestResultContext hc = webkit_hit_test_result_get_context(h);
1553
1554         /* Keep the hit test to know where is the pointer on the next click */
1555         c->mousepos = h;
1556
1557         if (hc & OnLink)
1558                 c->targeturi = webkit_hit_test_result_get_link_uri(h);
1559         else if (hc & OnImg)
1560                 c->targeturi = webkit_hit_test_result_get_image_uri(h);
1561         else if (hc & OnMedia)
1562                 c->targeturi = webkit_hit_test_result_get_media_uri(h);
1563         else
1564                 c->targeturi = NULL;
1565
1566         c->overtitle = c->targeturi;
1567         updatetitle(c);
1568 }
1569
1570 gboolean
1571 permissionrequested(WebKitWebView *v, WebKitPermissionRequest *r, Client *c)
1572 {
1573         ParamName param = ParameterLast;
1574
1575         if (WEBKIT_IS_GEOLOCATION_PERMISSION_REQUEST(r)) {
1576                 param = Geolocation;
1577         } else if (WEBKIT_IS_USER_MEDIA_PERMISSION_REQUEST(r)) {
1578                 if (webkit_user_media_permission_is_for_audio_device(
1579                     WEBKIT_USER_MEDIA_PERMISSION_REQUEST(r)))
1580                         param = AccessMicrophone;
1581                 else if (webkit_user_media_permission_is_for_video_device(
1582                          WEBKIT_USER_MEDIA_PERMISSION_REQUEST(r)))
1583                         param = AccessWebcam;
1584         } else {
1585                 return FALSE;
1586         }
1587
1588         if (curconfig[param].val.i)
1589                 webkit_permission_request_allow(r);
1590         else
1591                 webkit_permission_request_deny(r);
1592
1593         return TRUE;
1594 }
1595
1596 gboolean
1597 decidepolicy(WebKitWebView *v, WebKitPolicyDecision *d,
1598     WebKitPolicyDecisionType dt, Client *c)
1599 {
1600         switch (dt) {
1601         case WEBKIT_POLICY_DECISION_TYPE_NAVIGATION_ACTION:
1602                 decidenavigation(d, c);
1603                 break;
1604         case WEBKIT_POLICY_DECISION_TYPE_NEW_WINDOW_ACTION:
1605                 decidenewwindow(d, c);
1606                 break;
1607         case WEBKIT_POLICY_DECISION_TYPE_RESPONSE:
1608                 decideresource(d, c);
1609                 break;
1610         default:
1611                 webkit_policy_decision_ignore(d);
1612                 break;
1613         }
1614         return TRUE;
1615 }
1616
1617 void
1618 decidenavigation(WebKitPolicyDecision *d, Client *c)
1619 {
1620         WebKitNavigationAction *a =
1621             webkit_navigation_policy_decision_get_navigation_action(
1622             WEBKIT_NAVIGATION_POLICY_DECISION(d));
1623
1624         switch (webkit_navigation_action_get_navigation_type(a)) {
1625         case WEBKIT_NAVIGATION_TYPE_LINK_CLICKED: /* fallthrough */
1626         case WEBKIT_NAVIGATION_TYPE_FORM_SUBMITTED: /* fallthrough */
1627         case WEBKIT_NAVIGATION_TYPE_BACK_FORWARD: /* fallthrough */
1628         case WEBKIT_NAVIGATION_TYPE_RELOAD: /* fallthrough */
1629         case WEBKIT_NAVIGATION_TYPE_FORM_RESUBMITTED: /* fallthrough */
1630         case WEBKIT_NAVIGATION_TYPE_OTHER: /* fallthrough */
1631         default:
1632                 /* Do not navigate to links with a "_blank" target (popup) */
1633                 if (webkit_navigation_policy_decision_get_frame_name(
1634                     WEBKIT_NAVIGATION_POLICY_DECISION(d))) {
1635                         webkit_policy_decision_ignore(d);
1636                 } else {
1637                         /* Filter out navigation to different domain ? */
1638                         /* get action→urirequest, copy and load in new window+view
1639                          * on Ctrl+Click ? */
1640                         webkit_policy_decision_use(d);
1641                 }
1642                 break;
1643         }
1644 }
1645
1646 void
1647 decidenewwindow(WebKitPolicyDecision *d, Client *c)
1648 {
1649         Arg arg;
1650         WebKitNavigationAction *a =
1651             webkit_navigation_policy_decision_get_navigation_action(
1652             WEBKIT_NAVIGATION_POLICY_DECISION(d));
1653
1654
1655         switch (webkit_navigation_action_get_navigation_type(a)) {
1656         case WEBKIT_NAVIGATION_TYPE_LINK_CLICKED: /* fallthrough */
1657         case WEBKIT_NAVIGATION_TYPE_FORM_SUBMITTED: /* fallthrough */
1658         case WEBKIT_NAVIGATION_TYPE_BACK_FORWARD: /* fallthrough */
1659         case WEBKIT_NAVIGATION_TYPE_RELOAD: /* fallthrough */
1660         case WEBKIT_NAVIGATION_TYPE_FORM_RESUBMITTED:
1661                 /* Filter domains here */
1662 /* If the value of “mouse-button” is not 0, then the navigation was triggered by a mouse event.
1663  * test for link clicked but no button ? */
1664                 arg.v = webkit_uri_request_get_uri(
1665                         webkit_navigation_action_get_request(a));
1666                 newwindow(c, &arg, 0);
1667                 break;
1668         case WEBKIT_NAVIGATION_TYPE_OTHER: /* fallthrough */
1669         default:
1670                 break;
1671         }
1672
1673         webkit_policy_decision_ignore(d);
1674 }
1675
1676 void
1677 decideresource(WebKitPolicyDecision *d, Client *c)
1678 {
1679         int i, isascii = 1;
1680         WebKitResponsePolicyDecision *r = WEBKIT_RESPONSE_POLICY_DECISION(d);
1681         WebKitURIResponse *res =
1682             webkit_response_policy_decision_get_response(r);
1683         const gchar *uri = webkit_uri_response_get_uri(res);
1684
1685         if (g_str_has_suffix(uri, "/favicon.ico")) {
1686                 webkit_policy_decision_ignore(d);
1687                 return;
1688         }
1689
1690         if (!g_str_has_prefix(uri, "http://")
1691             && !g_str_has_prefix(uri, "https://")
1692             && !g_str_has_prefix(uri, "about:")
1693             && !g_str_has_prefix(uri, "file://")
1694             && !g_str_has_prefix(uri, "data:")
1695             && !g_str_has_prefix(uri, "blob:")
1696             && strlen(uri) > 0) {
1697                 for (i = 0; i < strlen(uri); i++) {
1698                         if (!g_ascii_isprint(uri[i])) {
1699                                 isascii = 0;
1700                                 break;
1701                         }
1702                 }
1703                 if (isascii) {
1704                         handleplumb(c, uri);
1705                         webkit_policy_decision_ignore(d);
1706                         return;
1707                 }
1708         }
1709
1710         if (webkit_response_policy_decision_is_mime_type_supported(r)) {
1711                 webkit_policy_decision_use(d);
1712         } else {
1713                 webkit_policy_decision_ignore(d);
1714                 download(c, res);
1715         }
1716 }
1717
1718 void
1719 insecurecontent(WebKitWebView *v, WebKitInsecureContentEvent e, Client *c)
1720 {
1721         c->insecure = 1;
1722 }
1723
1724 void
1725 downloadstarted(WebKitWebContext *wc, WebKitDownload *d, Client *c)
1726 {
1727         g_signal_connect(G_OBJECT(d), "notify::response",
1728                          G_CALLBACK(responsereceived), c);
1729 }
1730
1731 void
1732 responsereceived(WebKitDownload *d, GParamSpec *ps, Client *c)
1733 {
1734         download(c, webkit_download_get_response(d));
1735         webkit_download_cancel(d);
1736 }
1737
1738 void
1739 download(Client *c, WebKitURIResponse *r)
1740 {
1741         Arg a = (Arg)DOWNLOAD(webkit_uri_response_get_uri(r), geturi(c));
1742         spawn(c, &a);
1743 }
1744
1745 void
1746 webprocessterminated(WebKitWebView *v, WebKitWebProcessTerminationReason r,
1747                      Client *c)
1748 {
1749         fprintf(stderr, "web process terminated: %s\n",
1750                 r == WEBKIT_WEB_PROCESS_CRASHED ? "crashed" : "no memory");
1751         closeview(v, c);
1752 }
1753
1754 void
1755 closeview(WebKitWebView *v, Client *c)
1756 {
1757         gtk_widget_destroy(c->win);
1758 }
1759
1760 void
1761 destroywin(GtkWidget* w, Client *c)
1762 {
1763         destroyclient(c);
1764         if (!clients)
1765                 gtk_main_quit();
1766 }
1767
1768 void
1769 pasteuri(GtkClipboard *clipboard, const char *text, gpointer d)
1770 {
1771         Arg a = {.v = text };
1772         if (text)
1773                 loaduri((Client *) d, &a);
1774 }
1775
1776 void
1777 reload(Client *c, const Arg *a)
1778 {
1779         if (a->i)
1780                 webkit_web_view_reload_bypass_cache(c->view);
1781         else
1782                 webkit_web_view_reload(c->view);
1783 }
1784
1785 void
1786 print(Client *c, const Arg *a)
1787 {
1788         webkit_print_operation_run_dialog(webkit_print_operation_new(c->view),
1789                                           GTK_WINDOW(c->win));
1790 }
1791
1792 void
1793 showcert(Client *c, const Arg *a)
1794 {
1795         GTlsCertificate *cert = c->failedcert ? c->failedcert : c->cert;
1796         GcrCertificate *gcrt;
1797         GByteArray *crt;
1798         GtkWidget *win;
1799         GcrCertificateWidget *wcert;
1800
1801         if (!cert)
1802                 return;
1803
1804         g_object_get(cert, "certificate", &crt, NULL);
1805         gcrt = gcr_simple_certificate_new(crt->data, crt->len);
1806         g_byte_array_unref(crt);
1807
1808         win = gtk_window_new(GTK_WINDOW_TOPLEVEL);
1809         wcert = gcr_certificate_widget_new(gcrt);
1810         g_object_unref(gcrt);
1811
1812         gtk_container_add(GTK_CONTAINER(win), GTK_WIDGET(wcert));
1813         gtk_widget_show_all(win);
1814 }
1815
1816 void
1817 clipboard(Client *c, const Arg *a)
1818 {
1819         if (a->i) { /* load clipboard uri */
1820                 gtk_clipboard_request_text(gtk_clipboard_get(
1821                                            GDK_SELECTION_PRIMARY),
1822                                            pasteuri, c);
1823         } else { /* copy uri */
1824                 gtk_clipboard_set_text(gtk_clipboard_get(
1825                                        GDK_SELECTION_PRIMARY), c->targeturi
1826                                        ? c->targeturi : geturi(c), -1);
1827         }
1828 }
1829
1830 void
1831 zoom(Client *c, const Arg *a)
1832 {
1833         if (a->i > 0)
1834                 webkit_web_view_set_zoom_level(c->view,
1835                                                curconfig[ZoomLevel].val.f + 0.1);
1836         else if (a->i < 0)
1837                 webkit_web_view_set_zoom_level(c->view,
1838                                                curconfig[ZoomLevel].val.f - 0.1);
1839         else
1840                 webkit_web_view_set_zoom_level(c->view, 1.0);
1841
1842         curconfig[ZoomLevel].val.f = webkit_web_view_get_zoom_level(c->view);
1843 }
1844
1845 static void
1846 msgext(Client *c, char type, const Arg *a)
1847 {
1848         static char msg[MSGBUFSZ];
1849         int ret;
1850
1851         if ((ret = snprintf(msg, sizeof(msg), "%c%c%c%c",
1852                             4, c->pageid, type, a->i))
1853             >= sizeof(msg)) {
1854                 fprintf(stderr, "surf: message too long: %d\n", ret);
1855                 return;
1856         }
1857
1858         if (pipeout[1] && write(pipeout[1], msg, sizeof(msg)) < 0)
1859                 fprintf(stderr, "surf: error sending: %.*s\n", ret-2, msg+2);
1860 }
1861
1862 void
1863 scrollv(Client *c, const Arg *a)
1864 {
1865         msgext(c, 'v', a);
1866 }
1867
1868 void
1869 scrollh(Client *c, const Arg *a)
1870 {
1871         msgext(c, 'h', a);
1872 }
1873
1874 void
1875 navigate(Client *c, const Arg *a)
1876 {
1877         if (a->i < 0)
1878                 webkit_web_view_go_back(c->view);
1879         else if (a->i > 0)
1880                 webkit_web_view_go_forward(c->view);
1881 }
1882
1883 void
1884 stop(Client *c, const Arg *a)
1885 {
1886         webkit_web_view_stop_loading(c->view);
1887 }
1888
1889 void
1890 toggle(Client *c, const Arg *a)
1891 {
1892         curconfig[a->i].val.i ^= 1;
1893         setparameter(c, 1, (ParamName)a->i, &curconfig[a->i].val);
1894 }
1895
1896 void
1897 togglefullscreen(Client *c, const Arg *a)
1898 {
1899         /* toggling value is handled in winevent() */
1900         if (c->fullscreen)
1901                 gtk_window_unfullscreen(GTK_WINDOW(c->win));
1902         else
1903                 gtk_window_fullscreen(GTK_WINDOW(c->win));
1904 }
1905
1906 void
1907 togglecookiepolicy(Client *c, const Arg *a)
1908 {
1909         ++cookiepolicy;
1910         cookiepolicy %= strlen(curconfig[CookiePolicies].val.v);
1911
1912         setparameter(c, 0, CookiePolicies, NULL);
1913 }
1914
1915 void
1916 toggleinspector(Client *c, const Arg *a)
1917 {
1918         if (webkit_web_inspector_is_attached(c->inspector))
1919                 webkit_web_inspector_close(c->inspector);
1920         else if (curconfig[Inspector].val.i)
1921                 webkit_web_inspector_show(c->inspector);
1922 }
1923
1924 void
1925 find(Client *c, const Arg *a)
1926 {
1927         const char *s, *f;
1928
1929         if (a && a->i) {
1930                 if (a->i > 0)
1931                         webkit_find_controller_search_next(c->finder);
1932                 else
1933                         webkit_find_controller_search_previous(c->finder);
1934         } else {
1935                 s = getatom(c, AtomFind);
1936                 f = webkit_find_controller_get_search_text(c->finder);
1937
1938                 if (g_strcmp0(f, s) == 0) /* reset search */
1939                         webkit_find_controller_search(c->finder, "", findopts,
1940                                                       G_MAXUINT);
1941
1942                 webkit_find_controller_search(c->finder, s, findopts,
1943                                               G_MAXUINT);
1944
1945                 if (strcmp(s, "") == 0)
1946                         webkit_find_controller_search_finish(c->finder);
1947         }
1948 }
1949
1950 void
1951 clicknavigate(Client *c, const Arg *a, WebKitHitTestResult *h)
1952 {
1953         navigate(c, a);
1954 }
1955
1956 void
1957 clicknewwindow(Client *c, const Arg *a, WebKitHitTestResult *h)
1958 {
1959         Arg arg;
1960
1961         arg.v = webkit_hit_test_result_get_link_uri(h);
1962         newwindow(c, &arg, a->i);
1963 }
1964
1965 void
1966 clickexternplayer(Client *c, const Arg *a, WebKitHitTestResult *h)
1967 {
1968         Arg arg;
1969
1970         arg = (Arg)VIDEOPLAY(webkit_hit_test_result_get_media_uri(h));
1971         spawn(c, &arg);
1972 }
1973
1974 int
1975 main(int argc, char *argv[])
1976 {
1977         Arg arg;
1978         Client *c;
1979
1980         memset(&arg, 0, sizeof(arg));
1981
1982         /* command line args */
1983         ARGBEGIN {
1984         case 'a':
1985                 defconfig[CookiePolicies].val.v = EARGF(usage());
1986                 defconfig[CookiePolicies].prio = 2;
1987                 break;
1988         case 'b':
1989                 defconfig[ScrollBars].val.i = 0;
1990                 defconfig[ScrollBars].prio = 2;
1991                 break;
1992         case 'B':
1993                 defconfig[ScrollBars].val.i = 1;
1994                 defconfig[ScrollBars].prio = 2;
1995                 break;
1996         case 'c':
1997                 cookiefile = EARGF(usage());
1998                 break;
1999         case 'C':
2000                 stylefile = EARGF(usage());
2001                 break;
2002         case 'd':
2003                 defconfig[DiskCache].val.i = 0;
2004                 defconfig[DiskCache].prio = 2;
2005                 break;
2006         case 'D':
2007                 defconfig[DiskCache].val.i = 1;
2008                 defconfig[DiskCache].prio = 2;
2009                 break;
2010         case 'e':
2011                 embed = strtol(EARGF(usage()), NULL, 0);
2012                 break;
2013         case 'f':
2014                 defconfig[RunInFullscreen].val.i = 0;
2015                 defconfig[RunInFullscreen].prio = 2;
2016                 break;
2017         case 'F':
2018                 defconfig[RunInFullscreen].val.i = 1;
2019                 defconfig[RunInFullscreen].prio = 2;
2020                 break;
2021         case 'g':
2022                 defconfig[Geolocation].val.i = 0;
2023                 defconfig[Geolocation].prio = 2;
2024                 break;
2025         case 'G':
2026                 defconfig[Geolocation].val.i = 1;
2027                 defconfig[Geolocation].prio = 2;
2028                 break;
2029         case 'i':
2030                 defconfig[LoadImages].val.i = 0;
2031                 defconfig[LoadImages].prio = 2;
2032                 break;
2033         case 'I':
2034                 defconfig[LoadImages].val.i = 1;
2035                 defconfig[LoadImages].prio = 2;
2036                 break;
2037         case 'k':
2038                 defconfig[KioskMode].val.i = 0;
2039                 defconfig[KioskMode].prio = 2;
2040                 break;
2041         case 'K':
2042                 defconfig[KioskMode].val.i = 1;
2043                 defconfig[KioskMode].prio = 2;
2044                 break;
2045         case 'm':
2046                 defconfig[Style].val.i = 0;
2047                 defconfig[Style].prio = 2;
2048                 break;
2049         case 'M':
2050                 defconfig[Style].val.i = 1;
2051                 defconfig[Style].prio = 2;
2052                 break;
2053         case 'n':
2054                 defconfig[Inspector].val.i = 0;
2055                 defconfig[Inspector].prio = 2;
2056                 break;
2057         case 'N':
2058                 defconfig[Inspector].val.i = 1;
2059                 defconfig[Inspector].prio = 2;
2060                 break;
2061         case 'p':
2062                 defconfig[Plugins].val.i = 0;
2063                 defconfig[Plugins].prio = 2;
2064                 break;
2065         case 'P':
2066                 defconfig[Plugins].val.i = 1;
2067                 defconfig[Plugins].prio = 2;
2068                 break;
2069         case 'r':
2070                 scriptfile = EARGF(usage());
2071                 break;
2072         case 's':
2073                 defconfig[JavaScript].val.i = 0;
2074                 defconfig[JavaScript].prio = 2;
2075                 break;
2076         case 'S':
2077                 defconfig[JavaScript].val.i = 1;
2078                 defconfig[JavaScript].prio = 2;
2079                 break;
2080         case 't':
2081                 defconfig[StrictTLS].val.i = 0;
2082                 defconfig[StrictTLS].prio = 2;
2083                 break;
2084         case 'T':
2085                 defconfig[StrictTLS].val.i = 1;
2086                 defconfig[StrictTLS].prio = 2;
2087                 break;
2088         case 'u':
2089                 fulluseragent = EARGF(usage());
2090                 break;
2091         case 'v':
2092                 die("surf-"VERSION", see LICENSE for © details\n");
2093         case 'w':
2094                 showxid = 1;
2095                 break;
2096         case 'x':
2097                 defconfig[Certificate].val.i = 0;
2098                 defconfig[Certificate].prio = 2;
2099                 break;
2100         case 'X':
2101                 defconfig[Certificate].val.i = 1;
2102                 defconfig[Certificate].prio = 2;
2103                 break;
2104         case 'z':
2105                 defconfig[ZoomLevel].val.f = strtof(EARGF(usage()), NULL);
2106                 defconfig[ZoomLevel].prio = 2;
2107                 break;
2108         default:
2109                 usage();
2110         } ARGEND;
2111         if (argc > 0)
2112                 arg.v = argv[0];
2113         else
2114                 arg.v = "about:blank";
2115
2116         setup();
2117         c = newclient(NULL);
2118         showview(NULL, c);
2119
2120         loaduri(c, &arg);
2121         updatetitle(c);
2122
2123         gtk_main();
2124         cleanup();
2125
2126         return 0;
2127 }