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