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