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