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