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