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