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