Change site styles structure for a more generic one
[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 *file;
140         regex_t re;
141 } SiteSpecific;
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 [-bBdDfFgGiIkKmMnNpPsStTvx] [-a cookiepolicies ] "
250             "[-c cookiefile] [-C stylefile] [-e xid] [-r scriptfile] "
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].file = g_strconcat(styledir, "/",
308                                                      styles[i].file, 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].file;
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[28], *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         if (stylefile && g_strcmp0(stylefile, "")) {
832                 cmd[i++] = "-C";
833                 cmd[i++] = stylefile;
834         }
835         cmd[i++] = curconfig[DiskCache].val.b ? "-D" : "-d";
836         if (embed && !noembed) {
837                 cmd[i++] = "-e";
838                 snprintf(tmp, LENGTH(tmp), "%lu", embed);
839                 cmd[i++] = tmp;
840         }
841         cmd[i++] = curconfig[RunInFullscreen].val.b ? "-F" : "-f" ;
842         cmd[i++] = curconfig[Geolocation].val.b ?     "-G" : "-g" ;
843         cmd[i++] = curconfig[LoadImages].val.b ?      "-I" : "-i" ;
844         cmd[i++] = curconfig[KioskMode].val.b ?       "-K" : "-k" ;
845         cmd[i++] = curconfig[Style].val.b ?           "-M" : "-m" ;
846         cmd[i++] = curconfig[Inspector].val.b ?       "-N" : "-n" ;
847         cmd[i++] = curconfig[Plugins].val.b ?         "-P" : "-p" ;
848         if (scriptfile && g_strcmp0(scriptfile, "")) {
849                 cmd[i++] = "-r";
850                 cmd[i++] = scriptfile;
851         }
852         cmd[i++] = curconfig[JavaScript].val.b ? "-S" : "-s";
853         cmd[i++] = curconfig[StrictTLS].val.b ? "-T" : "-t";
854         if (fulluseragent && g_strcmp0(fulluseragent, "")) {
855                 cmd[i++] = "-u";
856                 cmd[i++] = fulluseragent;
857         }
858         if (showxid)
859                 cmd[i++] = "-x";
860         /* do not keep zoom level */
861         cmd[i++] = "--";
862         if ((uri = a->v))
863                 cmd[i++] = uri;
864         cmd[i] = NULL;
865
866         spawn(c, &arg);
867 }
868
869 void
870 spawn(Client *c, const Arg *a)
871 {
872         if (fork() == 0) {
873                 if (dpy)
874                         close(ConnectionNumber(dpy));
875                 setsid();
876                 execvp(((char **)a->v)[0], (char **)a->v);
877                 fprintf(stderr, "%s: execvp %s", argv0, ((char **)a->v)[0]);
878                 perror(" failed");
879                 exit(1);
880         }
881 }
882
883 void
884 destroyclient(Client *c)
885 {
886         Client *p;
887
888         webkit_web_view_stop_loading(c->view);
889         /* Not needed, has already been called
890         gtk_widget_destroy(c->win);
891          */
892
893         for (p = clients; p && p->next != c; p = p->next)
894                 ;
895         if (p)
896                 p->next = c->next;
897         else
898                 clients = c->next;
899         free(c);
900 }
901
902 void
903 cleanup(void)
904 {
905         while (clients)
906                 destroyclient(clients);
907         g_free(cookiefile);
908         g_free(scriptfile);
909         g_free(stylefile);
910         g_free(cachedir);
911         XCloseDisplay(dpy);
912 }
913
914 WebKitWebView *
915 newview(Client *c, WebKitWebView *rv)
916 {
917         WebKitWebView *v;
918         WebKitSettings *settings;
919         WebKitUserContentManager *contentmanager;
920         WebKitWebContext *context;
921
922         /* Webview */
923         if (rv) {
924                 v = WEBKIT_WEB_VIEW(
925                     webkit_web_view_new_with_related_view(rv));
926         } else {
927                 settings = webkit_settings_new_with_settings(
928                    "auto-load-images", curconfig[LoadImages].val.b,
929                    "default-font-size", curconfig[FontSize].val.i,
930                    "enable-caret-browsing", curconfig[CaretBrowsing].val.b,
931                    "enable-developer-extras", curconfig[Inspector].val.b,
932                    "enable-dns-prefetching", curconfig[DNSPrefetch].val.b,
933                    "enable-frame-flattening", curconfig[FrameFlattening].val.b,
934                    "enable-html5-database", curconfig[DiskCache].val.b,
935                    "enable-html5-local-storage", curconfig[DiskCache].val.b,
936                    "enable-javascript", curconfig[JavaScript].val.b,
937                    "enable-plugins", curconfig[Plugins].val.b,
938                    "enable-accelerated-2d-canvas", curconfig[AcceleratedCanvas].val.b,
939                    "enable-site-specific-quirks", curconfig[SiteQuirks].val.b,
940                    "media-playback-requires-user-gesture", curconfig[MediaManualPlay].val.b,
941                    NULL);
942 /* For mor interesting settings, have a look at
943  * http://webkitgtk.org/reference/webkit2gtk/stable/WebKitSettings.html */
944
945                 if (strcmp(fulluseragent, "")) {
946                         webkit_settings_set_user_agent(settings, fulluseragent);
947                 } else if (surfuseragent) {
948                         webkit_settings_set_user_agent_with_application_details(
949                             settings, "Surf", VERSION);
950                 }
951                 useragent = webkit_settings_get_user_agent(settings);
952
953                 contentmanager = webkit_user_content_manager_new();
954
955                 context = webkit_web_context_new_with_website_data_manager(
956                           webkit_website_data_manager_new(
957                           "base-cache-directory", cachedir,
958                           "base-data-directory", cachedir,
959                           NULL));
960
961                 /* rendering process model, can be a shared unique one
962                  * or one for each view */
963                 webkit_web_context_set_process_model(context,
964                     WEBKIT_PROCESS_MODEL_MULTIPLE_SECONDARY_PROCESSES);
965                 /* TLS */
966                 webkit_web_context_set_tls_errors_policy(context,
967                     curconfig[StrictTLS].val.b ? WEBKIT_TLS_ERRORS_POLICY_FAIL :
968                     WEBKIT_TLS_ERRORS_POLICY_IGNORE);
969                 /* disk cache */
970                 webkit_web_context_set_cache_model(context,
971                     curconfig[DiskCache].val.b ? WEBKIT_CACHE_MODEL_WEB_BROWSER :
972                     WEBKIT_CACHE_MODEL_DOCUMENT_VIEWER);
973
974                 /* Currently only works with text file to be compatible with curl */
975                 webkit_cookie_manager_set_persistent_storage(
976                     webkit_web_context_get_cookie_manager(context), cookiefile,
977                     WEBKIT_COOKIE_PERSISTENT_STORAGE_TEXT);
978                 /* cookie policy */
979                 webkit_cookie_manager_set_accept_policy(
980                     webkit_web_context_get_cookie_manager(context),
981                     cookiepolicy_get());
982                 /* languages */
983                 webkit_web_context_set_preferred_languages(context,
984                     curconfig[PreferredLanguages].val.v);
985                 webkit_web_context_set_spell_checking_languages(context,
986                     curconfig[SpellLanguages].val.v);
987                 webkit_web_context_set_spell_checking_enabled(context,
988                     curconfig[SpellChecking].val.b);
989
990                 g_signal_connect(G_OBJECT(context), "download-started",
991                                  G_CALLBACK(downloadstarted), c);
992                 g_signal_connect(G_OBJECT(context), "initialize-web-extensions",
993                                  G_CALLBACK(initwebextensions), c);
994
995                 v = g_object_new(WEBKIT_TYPE_WEB_VIEW,
996                     "settings", settings,
997                     "user-content-manager", contentmanager,
998                     "web-context", context,
999                     NULL);
1000         }
1001
1002         g_signal_connect(G_OBJECT(v), "notify::estimated-load-progress",
1003                          G_CALLBACK(progresschanged), c);
1004         g_signal_connect(G_OBJECT(v), "notify::title",
1005                          G_CALLBACK(titlechanged), c);
1006         g_signal_connect(G_OBJECT(v), "button-release-event",
1007                          G_CALLBACK(buttonreleased), c);
1008         g_signal_connect(G_OBJECT(v), "close",
1009                         G_CALLBACK(closeview), c);
1010         g_signal_connect(G_OBJECT(v), "create",
1011                          G_CALLBACK(createview), c);
1012         g_signal_connect(G_OBJECT(v), "decide-policy",
1013                          G_CALLBACK(decidepolicy), c);
1014         g_signal_connect(G_OBJECT(v), "insecure-content-detected",
1015                          G_CALLBACK(insecurecontent), c);
1016         g_signal_connect(G_OBJECT(v), "load-changed",
1017                          G_CALLBACK(loadchanged), c);
1018         g_signal_connect(G_OBJECT(v), "mouse-target-changed",
1019                          G_CALLBACK(mousetargetchanged), c);
1020         g_signal_connect(G_OBJECT(v), "permission-request",
1021                          G_CALLBACK(permissionrequested), c);
1022         g_signal_connect(G_OBJECT(v), "ready-to-show",
1023                          G_CALLBACK(showview), c);
1024
1025         return v;
1026 }
1027
1028 void
1029 initwebextensions(WebKitWebContext *wc, Client *c)
1030 {
1031         webkit_web_context_set_web_extensions_directory(wc, WEBEXTDIR);
1032 }
1033
1034 GtkWidget *
1035 createview(WebKitWebView *v, WebKitNavigationAction *a, Client *c)
1036 {
1037         Client *n;
1038
1039         switch (webkit_navigation_action_get_navigation_type(a)) {
1040         case WEBKIT_NAVIGATION_TYPE_OTHER: /* fallthrough */
1041                 /*
1042                  * popup windows of type “other” are almost always triggered
1043                  * by user gesture, so inverse the logic here
1044                  */
1045 /* instead of this, compare destination uri to mouse-over uri for validating window */
1046                 if (webkit_navigation_action_is_user_gesture(a))
1047                         return NULL;
1048         case WEBKIT_NAVIGATION_TYPE_LINK_CLICKED: /* fallthrough */
1049         case WEBKIT_NAVIGATION_TYPE_FORM_SUBMITTED: /* fallthrough */
1050         case WEBKIT_NAVIGATION_TYPE_BACK_FORWARD: /* fallthrough */
1051         case WEBKIT_NAVIGATION_TYPE_RELOAD: /* fallthrough */
1052         case WEBKIT_NAVIGATION_TYPE_FORM_RESUBMITTED:
1053                 n = newclient(c);
1054                 break;
1055         default:
1056                 return NULL;
1057         }
1058
1059         return GTK_WIDGET(n->view);
1060 }
1061
1062 gboolean
1063 buttonreleased(GtkWidget *w, GdkEvent *e, Client *c)
1064 {
1065         WebKitHitTestResultContext element;
1066         int i;
1067
1068         element = webkit_hit_test_result_get_context(c->mousepos);
1069
1070         for (i = 0; i < LENGTH(buttons); ++i) {
1071                 if (element & buttons[i].target &&
1072                     e->button.button == buttons[i].button &&
1073                     CLEANMASK(e->button.state) == CLEANMASK(buttons[i].mask) &&
1074                     buttons[i].func) {
1075                         buttons[i].func(c, &buttons[i].arg, c->mousepos);
1076                         return buttons[i].stopevent;
1077                 }
1078         }
1079
1080         return FALSE;
1081 }
1082
1083 GdkFilterReturn
1084 processx(GdkXEvent *e, GdkEvent *event, gpointer d)
1085 {
1086         Client *c = (Client *)d;
1087         XPropertyEvent *ev;
1088         Arg a;
1089
1090         if (((XEvent *)e)->type == PropertyNotify) {
1091                 ev = &((XEvent *)e)->xproperty;
1092                 if (ev->state == PropertyNewValue) {
1093                         if (ev->atom == atoms[AtomFind]) {
1094                                 find(c, NULL);
1095
1096                                 return GDK_FILTER_REMOVE;
1097                         } else if (ev->atom == atoms[AtomGo]) {
1098                                 a.v = getatom(c, AtomGo);
1099                                 loaduri(c, &a);
1100
1101                                 return GDK_FILTER_REMOVE;
1102                         }
1103                 }
1104         }
1105         return GDK_FILTER_CONTINUE;
1106 }
1107
1108 gboolean
1109 winevent(GtkWidget *w, GdkEvent *e, Client *c)
1110 {
1111         int i;
1112
1113         switch (e->type) {
1114         case GDK_ENTER_NOTIFY:
1115                 c->overtitle = c->targeturi;
1116                 updatetitle(c);
1117                 break;
1118         case GDK_KEY_PRESS:
1119                 if (!curconfig[KioskMode].val.b) {
1120                         for (i = 0; i < LENGTH(keys); ++i) {
1121                                 if (gdk_keyval_to_lower(e->key.keyval) ==
1122                                     keys[i].keyval &&
1123                                     CLEANMASK(e->key.state) == keys[i].mod &&
1124                                     keys[i].func) {
1125                                         updatewinid(c);
1126                                         keys[i].func(c, &(keys[i].arg));
1127                                         return TRUE;
1128                                 }
1129                         }
1130                 }
1131         case GDK_LEAVE_NOTIFY:
1132                 c->overtitle = NULL;
1133                 updatetitle(c);
1134                 break;
1135         case GDK_WINDOW_STATE:
1136                 if (e->window_state.changed_mask ==
1137                     GDK_WINDOW_STATE_FULLSCREEN)
1138                         c->fullscreen = e->window_state.new_window_state &
1139                                         GDK_WINDOW_STATE_FULLSCREEN;
1140                 break;
1141         default:
1142                 break;
1143         }
1144
1145         return FALSE;
1146 }
1147
1148 void
1149 showview(WebKitWebView *v, Client *c)
1150 {
1151         GdkRGBA bgcolor = { 0 };
1152         GdkWindow *gwin;
1153
1154         c->finder = webkit_web_view_get_find_controller(c->view);
1155         c->inspector = webkit_web_view_get_inspector(c->view);
1156
1157         c->win = createwindow(c);
1158
1159         gtk_container_add(GTK_CONTAINER(c->win), GTK_WIDGET(c->view));
1160         gtk_widget_show_all(c->win);
1161         gtk_widget_grab_focus(GTK_WIDGET(c->view));
1162
1163         gwin = gtk_widget_get_window(GTK_WIDGET(c->win));
1164         c->xid = gdk_x11_window_get_xid(gwin);
1165         updatewinid(c);
1166         if (showxid) {
1167                 gdk_display_sync(gtk_widget_get_display(c->win));
1168                 puts(winid);
1169         }
1170
1171         if (curconfig[HideBackground].val.b)
1172                 webkit_web_view_set_background_color(c->view, &bgcolor);
1173
1174         if (!curconfig[KioskMode].val.b) {
1175                 gdk_window_set_events(gwin, GDK_ALL_EVENTS_MASK);
1176                 gdk_window_add_filter(gwin, processx, c);
1177         }
1178
1179         if (curconfig[RunInFullscreen].val.b)
1180                 togglefullscreen(c, NULL);
1181
1182         if (curconfig[ZoomLevel].val.f != 1.0)
1183                 webkit_web_view_set_zoom_level(c->view,
1184                                                curconfig[ZoomLevel].val.f);
1185
1186         setatom(c, AtomFind, "");
1187         setatom(c, AtomUri, "about:blank");
1188 }
1189
1190 GtkWidget *
1191 createwindow(Client *c)
1192 {
1193         char *wmstr;
1194         GtkWidget *w;
1195
1196         if (embed) {
1197                 w = gtk_plug_new(embed);
1198         } else {
1199                 w = gtk_window_new(GTK_WINDOW_TOPLEVEL);
1200
1201                 wmstr = g_path_get_basename(argv0);
1202                 gtk_window_set_wmclass(GTK_WINDOW(w), wmstr, "Surf");
1203                 g_free(wmstr);
1204
1205                 wmstr = g_strdup_printf("%s[%lu]", "Surf",
1206                         webkit_web_view_get_page_id(c->view));
1207                 gtk_window_set_role(GTK_WINDOW(w), wmstr);
1208                 g_free(wmstr);
1209
1210                 gtk_window_set_default_size(GTK_WINDOW(w), winsize[0], winsize[1]);
1211         }
1212
1213         g_signal_connect(G_OBJECT(w), "destroy",
1214                          G_CALLBACK(destroywin), c);
1215         g_signal_connect(G_OBJECT(w), "enter-notify-event",
1216                          G_CALLBACK(winevent), c);
1217         g_signal_connect(G_OBJECT(w), "key-press-event",
1218                          G_CALLBACK(winevent), c);
1219         g_signal_connect(G_OBJECT(w), "leave-notify-event",
1220                          G_CALLBACK(winevent), c);
1221         g_signal_connect(G_OBJECT(w), "window-state-event",
1222                          G_CALLBACK(winevent), c);
1223
1224         return w;
1225 }
1226
1227 void
1228 loadchanged(WebKitWebView *v, WebKitLoadEvent e, Client *c)
1229 {
1230         const char *title = geturi(c);
1231
1232         switch (e) {
1233         case WEBKIT_LOAD_STARTED:
1234                 curconfig = defconfig;
1235                 setatom(c, AtomUri, title);
1236                 c->title = title;
1237                 c->https = c->insecure = 0;
1238                 seturiparameters(c, geturi(c));
1239                 break;
1240         case WEBKIT_LOAD_REDIRECTED:
1241                 setatom(c, AtomUri, title);
1242                 c->title = title;
1243                 seturiparameters(c, geturi(c));
1244                 break;
1245         case WEBKIT_LOAD_COMMITTED:
1246                 c->https = webkit_web_view_get_tls_info(c->view, NULL,
1247                                                         &c->tlserr);
1248                 break;
1249         case WEBKIT_LOAD_FINISHED:
1250                 /* Disabled until we write some WebKitWebExtension for
1251                  * manipulating the DOM directly.
1252                 evalscript(c, "document.documentElement.style.overflow = '%s'",
1253                     enablescrollbars ? "auto" : "hidden");
1254                 */
1255                 runscript(c);
1256                 break;
1257         }
1258         updatetitle(c);
1259 }
1260
1261 void
1262 progresschanged(WebKitWebView *v, GParamSpec *ps, Client *c)
1263 {
1264         c->progress = webkit_web_view_get_estimated_load_progress(c->view) *
1265                       100;
1266         updatetitle(c);
1267 }
1268
1269 void
1270 titlechanged(WebKitWebView *view, GParamSpec *ps, Client *c)
1271 {
1272         c->title = webkit_web_view_get_title(c->view);
1273         updatetitle(c);
1274 }
1275
1276 void
1277 mousetargetchanged(WebKitWebView *v, WebKitHitTestResult *h, guint modifiers,
1278     Client *c)
1279 {
1280         WebKitHitTestResultContext hc = webkit_hit_test_result_get_context(h);
1281
1282         /* Keep the hit test to know where is the pointer on the next click */
1283         c->mousepos = h;
1284
1285         if (hc & OnLink)
1286                 c->targeturi = webkit_hit_test_result_get_link_uri(h);
1287         else if (hc & OnImg)
1288                 c->targeturi = webkit_hit_test_result_get_image_uri(h);
1289         else if (hc & OnMedia)
1290                 c->targeturi = webkit_hit_test_result_get_media_uri(h);
1291         else
1292                 c->targeturi = NULL;
1293
1294         c->overtitle = c->targeturi;
1295         updatetitle(c);
1296 }
1297
1298 gboolean
1299 permissionrequested(WebKitWebView *v, WebKitPermissionRequest *r, Client *c)
1300 {
1301         if (WEBKIT_IS_GEOLOCATION_PERMISSION_REQUEST(r)) {
1302                 if (curconfig[Geolocation].val.b)
1303                         webkit_permission_request_allow(r);
1304                 else
1305                         webkit_permission_request_deny(r);
1306                 return TRUE;
1307         }
1308
1309         return FALSE;
1310 }
1311
1312 gboolean
1313 decidepolicy(WebKitWebView *v, WebKitPolicyDecision *d,
1314     WebKitPolicyDecisionType dt, Client *c)
1315 {
1316         switch (dt) {
1317         case WEBKIT_POLICY_DECISION_TYPE_NAVIGATION_ACTION:
1318                 decidenavigation(d, c);
1319                 break;
1320         case WEBKIT_POLICY_DECISION_TYPE_NEW_WINDOW_ACTION:
1321                 decidenewwindow(d, c);
1322                 break;
1323         case WEBKIT_POLICY_DECISION_TYPE_RESPONSE:
1324                 decideresource(d, c);
1325                 break;
1326         default:
1327                 webkit_policy_decision_ignore(d);
1328                 break;
1329         }
1330         return TRUE;
1331 }
1332
1333 void
1334 decidenavigation(WebKitPolicyDecision *d, Client *c)
1335 {
1336         WebKitNavigationAction *a =
1337             webkit_navigation_policy_decision_get_navigation_action(
1338             WEBKIT_NAVIGATION_POLICY_DECISION(d));
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: /* fallthrough */
1346         case WEBKIT_NAVIGATION_TYPE_OTHER: /* fallthrough */
1347         default:
1348                 /* Do not navigate to links with a "_blank" target (popup) */
1349                 if (webkit_navigation_policy_decision_get_frame_name(
1350                     WEBKIT_NAVIGATION_POLICY_DECISION(d))) {
1351                         webkit_policy_decision_ignore(d);
1352                 } else {
1353                         /* Filter out navigation to different domain ? */
1354                         /* get action→urirequest, copy and load in new window+view
1355                          * on Ctrl+Click ? */
1356                         webkit_policy_decision_use(d);
1357                 }
1358                 break;
1359         }
1360 }
1361
1362 void
1363 decidenewwindow(WebKitPolicyDecision *d, Client *c)
1364 {
1365         Arg arg;
1366         WebKitNavigationAction *a =
1367             webkit_navigation_policy_decision_get_navigation_action(
1368             WEBKIT_NAVIGATION_POLICY_DECISION(d));
1369
1370
1371         switch (webkit_navigation_action_get_navigation_type(a)) {
1372         case WEBKIT_NAVIGATION_TYPE_LINK_CLICKED: /* fallthrough */
1373         case WEBKIT_NAVIGATION_TYPE_FORM_SUBMITTED: /* fallthrough */
1374         case WEBKIT_NAVIGATION_TYPE_BACK_FORWARD: /* fallthrough */
1375         case WEBKIT_NAVIGATION_TYPE_RELOAD: /* fallthrough */
1376         case WEBKIT_NAVIGATION_TYPE_FORM_RESUBMITTED:
1377                 /* Filter domains here */
1378 /* If the value of “mouse-button” is not 0, then the navigation was triggered by a mouse event.
1379  * test for link clicked but no button ? */
1380                 arg.v = webkit_uri_request_get_uri(
1381                         webkit_navigation_action_get_request(a));
1382                 newwindow(c, &arg, 0);
1383                 break;
1384         case WEBKIT_NAVIGATION_TYPE_OTHER: /* fallthrough */
1385         default:
1386                 break;
1387         }
1388
1389         webkit_policy_decision_ignore(d);
1390 }
1391
1392 void
1393 decideresource(WebKitPolicyDecision *d, Client *c)
1394 {
1395         int i, isascii = 1;
1396         WebKitResponsePolicyDecision *r = WEBKIT_RESPONSE_POLICY_DECISION(d);
1397         WebKitURIResponse *res =
1398             webkit_response_policy_decision_get_response(r);
1399         const gchar *uri = webkit_uri_response_get_uri(res);
1400
1401         if (g_str_has_suffix(uri, "/favicon.ico")) {
1402                 webkit_policy_decision_ignore(d);
1403                 return;
1404         }
1405
1406         if (!g_str_has_prefix(uri, "http://")
1407             && !g_str_has_prefix(uri, "https://")
1408             && !g_str_has_prefix(uri, "about:")
1409             && !g_str_has_prefix(uri, "file://")
1410             && !g_str_has_prefix(uri, "data:")
1411             && !g_str_has_prefix(uri, "blob:")
1412             && strlen(uri) > 0) {
1413                 for (i = 0; i < strlen(uri); i++) {
1414                         if (!g_ascii_isprint(uri[i])) {
1415                                 isascii = 0;
1416                                 break;
1417                         }
1418                 }
1419                 if (isascii) {
1420                         handleplumb(c, uri);
1421                         webkit_policy_decision_ignore(d);
1422                         return;
1423                 }
1424         }
1425
1426         if (webkit_response_policy_decision_is_mime_type_supported(r)) {
1427                 webkit_policy_decision_use(d);
1428         } else {
1429                 webkit_policy_decision_ignore(d);
1430                 download(c, res);
1431         }
1432 }
1433
1434 void
1435 insecurecontent(WebKitWebView *v, WebKitInsecureContentEvent e, Client *c)
1436 {
1437         c->insecure = 1;
1438 }
1439
1440 void
1441 downloadstarted(WebKitWebContext *wc, WebKitDownload *d, Client *c)
1442 {
1443         g_signal_connect(G_OBJECT(d), "notify::response",
1444                          G_CALLBACK(responsereceived), c);
1445 }
1446
1447 void
1448 responsereceived(WebKitDownload *d, GParamSpec *ps, Client *c)
1449 {
1450         download(c, webkit_download_get_response(d));
1451         webkit_download_cancel(d);
1452 }
1453
1454 void
1455 download(Client *c, WebKitURIResponse *r)
1456 {
1457         Arg a = (Arg)DOWNLOAD(webkit_uri_response_get_uri(r), geturi(c));
1458         spawn(c, &a);
1459 }
1460
1461 void
1462 closeview(WebKitWebView *v, Client *c)
1463 {
1464         gtk_widget_destroy(c->win);
1465 }
1466
1467 void
1468 destroywin(GtkWidget* w, Client *c)
1469 {
1470         destroyclient(c);
1471         if (!clients)
1472                 gtk_main_quit();
1473 }
1474
1475 void
1476 pasteuri(GtkClipboard *clipboard, const char *text, gpointer d)
1477 {
1478         Arg a = {.v = text };
1479         if (text)
1480                 loaduri((Client *) d, &a);
1481 }
1482
1483 void
1484 reload(Client *c, const Arg *a)
1485 {
1486         if (a->b)
1487                 webkit_web_view_reload_bypass_cache(c->view);
1488         else
1489                 webkit_web_view_reload(c->view);
1490 }
1491
1492 void
1493 print(Client *c, const Arg *a)
1494 {
1495         webkit_print_operation_run_dialog(webkit_print_operation_new(c->view),
1496                                           GTK_WINDOW(c->win));
1497 }
1498
1499 void
1500 clipboard(Client *c, const Arg *a)
1501 {
1502         if (a->b) { /* load clipboard uri */
1503                 gtk_clipboard_request_text(gtk_clipboard_get(
1504                                            GDK_SELECTION_PRIMARY),
1505                                            pasteuri, c);
1506         } else { /* copy uri */
1507                 gtk_clipboard_set_text(gtk_clipboard_get(
1508                                        GDK_SELECTION_PRIMARY), c->targeturi
1509                                        ? c->targeturi : geturi(c), -1);
1510         }
1511 }
1512
1513 void
1514 zoom(Client *c, const Arg *a)
1515 {
1516         if (a->i > 0)
1517                 webkit_web_view_set_zoom_level(c->view,
1518                                                curconfig[ZoomLevel].val.f + 0.1);
1519         else if (a->i < 0)
1520                 webkit_web_view_set_zoom_level(c->view,
1521                                                curconfig[ZoomLevel].val.f - 0.1);
1522         else
1523                 webkit_web_view_set_zoom_level(c->view, 1.0);
1524
1525         curconfig[ZoomLevel].val.f = webkit_web_view_get_zoom_level(c->view);
1526 }
1527
1528 void
1529 scroll(Client *c, const Arg *a)
1530 {
1531         GdkEvent *ev = gdk_event_new(GDK_KEY_PRESS);
1532
1533         gdk_event_set_device(ev, gdkkb);
1534         ev->key.window = gtk_widget_get_window(GTK_WIDGET(c->win));
1535         ev->key.state = GDK_CONTROL_MASK;
1536         ev->key.time = GDK_CURRENT_TIME;
1537
1538         switch (a->i) {
1539         case 'd':
1540                 ev->key.keyval = GDK_KEY_Down;
1541                 break;
1542         case 'D':
1543                 ev->key.keyval = GDK_KEY_Page_Down;
1544                 break;
1545         case 'l':
1546                 ev->key.keyval = GDK_KEY_Left;
1547                 break;
1548         case 'r':
1549                 ev->key.keyval = GDK_KEY_Right;
1550                 break;
1551         case 'U':
1552                 ev->key.keyval = GDK_KEY_Page_Up;
1553                 break;
1554         case 'u':
1555                 ev->key.keyval = GDK_KEY_Up;
1556                 break;
1557         }
1558
1559         gdk_event_put(ev);
1560 }
1561
1562 void
1563 navigate(Client *c, const Arg *a)
1564 {
1565         if (a->i < 0)
1566                 webkit_web_view_go_back(c->view);
1567         else if (a->i > 0)
1568                 webkit_web_view_go_forward(c->view);
1569 }
1570
1571 void
1572 stop(Client *c, const Arg *a)
1573 {
1574         webkit_web_view_stop_loading(c->view);
1575 }
1576
1577 void
1578 toggle(Client *c, const Arg *a)
1579 {
1580         curconfig[a->i].val.b ^= 1;
1581         setparameter(c, 1, (ParamName)a->i, &curconfig[a->i].val);
1582 }
1583
1584 void
1585 togglefullscreen(Client *c, const Arg *a)
1586 {
1587         /* toggling value is handled in winevent() */
1588         if (c->fullscreen)
1589                 gtk_window_unfullscreen(GTK_WINDOW(c->win));
1590         else
1591                 gtk_window_fullscreen(GTK_WINDOW(c->win));
1592 }
1593
1594 void
1595 togglecookiepolicy(Client *c, const Arg *a)
1596 {
1597         ++cookiepolicy;
1598         cookiepolicy %= strlen(curconfig[CookiePolicies].val.v);
1599
1600         setparameter(c, 0, CookiePolicies, NULL);
1601 }
1602
1603 void
1604 toggleinspector(Client *c, const Arg *a)
1605 {
1606         if (webkit_web_inspector_is_attached(c->inspector))
1607                 webkit_web_inspector_close(c->inspector);
1608         else if (curconfig[Inspector].val.b)
1609                 webkit_web_inspector_show(c->inspector);
1610 }
1611
1612 void
1613 find(Client *c, const Arg *a)
1614 {
1615         const char *s, *f;
1616
1617         if (a && a->i) {
1618                 if (a->i > 0)
1619                         webkit_find_controller_search_next(c->finder);
1620                 else
1621                         webkit_find_controller_search_previous(c->finder);
1622         } else {
1623                 s = getatom(c, AtomFind);
1624                 f = webkit_find_controller_get_search_text(c->finder);
1625
1626                 if (g_strcmp0(f, s) == 0) /* reset search */
1627                         webkit_find_controller_search(c->finder, "", findopts,
1628                                                       G_MAXUINT);
1629
1630                 webkit_find_controller_search(c->finder, s, findopts,
1631                                               G_MAXUINT);
1632
1633                 if (strcmp(s, "") == 0)
1634                         webkit_find_controller_search_finish(c->finder);
1635         }
1636 }
1637
1638 void
1639 clicknavigate(Client *c, const Arg *a, WebKitHitTestResult *h)
1640 {
1641         navigate(c, a);
1642 }
1643
1644 void
1645 clicknewwindow(Client *c, const Arg *a, WebKitHitTestResult *h)
1646 {
1647         Arg arg;
1648
1649         arg.v = webkit_hit_test_result_get_link_uri(h);
1650         newwindow(c, &arg, a->b);
1651 }
1652
1653 void
1654 clickexternplayer(Client *c, const Arg *a, WebKitHitTestResult *h)
1655 {
1656         Arg arg;
1657
1658         arg = (Arg)VIDEOPLAY(webkit_hit_test_result_get_media_uri(h));
1659         spawn(c, &arg);
1660 }
1661
1662 int
1663 main(int argc, char *argv[])
1664 {
1665         Arg arg;
1666         Client *c;
1667
1668         memset(&arg, 0, sizeof(arg));
1669
1670         /* command line args */
1671         ARGBEGIN {
1672         case 'a':
1673                 defconfig CSETV(CookiePolicies, EARGF(usage()));
1674                 break;
1675         case 'b':
1676                 defconfig CSETB(ScrollBars, 0);
1677                 break;
1678         case 'B':
1679                 defconfig CSETB(ScrollBars, 1);
1680                 break;
1681         case 'c':
1682                 cookiefile = EARGF(usage());
1683                 break;
1684         case 'C':
1685                 stylefile = EARGF(usage());
1686                 break;
1687         case 'd':
1688                 defconfig CSETB(DiskCache, 0);
1689                 break;
1690         case 'D':
1691                 defconfig CSETB(DiskCache, 1);
1692                 break;
1693         case 'e':
1694                 embed = strtol(EARGF(usage()), NULL, 0);
1695                 break;
1696         case 'f':
1697                 defconfig CSETB(RunInFullscreen, 0);
1698                 break;
1699         case 'F':
1700                 defconfig CSETB(RunInFullscreen, 1);
1701                 break;
1702         case 'g':
1703                 defconfig CSETB(Geolocation, 0);
1704                 break;
1705         case 'G':
1706                 defconfig CSETB(Geolocation, 1);
1707                 break;
1708         case 'i':
1709                 defconfig CSETB(LoadImages, 0);
1710                 break;
1711         case 'I':
1712                 defconfig CSETB(LoadImages, 1);
1713                 break;
1714         case 'k':
1715                 defconfig CSETB(KioskMode, 0);
1716                 break;
1717         case 'K':
1718                 defconfig CSETB(KioskMode, 1);
1719                 break;
1720         case 'm':
1721                 defconfig CSETB(Style, 0);
1722                 break;
1723         case 'M':
1724                 defconfig CSETB(Style, 1);
1725                 break;
1726         case 'n':
1727                 defconfig CSETB(Inspector, 0);
1728                 break;
1729         case 'N':
1730                 defconfig CSETB(Inspector, 1);
1731                 break;
1732         case 'p':
1733                 defconfig CSETB(Plugins, 0);
1734                 break;
1735         case 'P':
1736                 defconfig CSETB(Plugins, 1);
1737                 break;
1738         case 'r':
1739                 scriptfile = EARGF(usage());
1740                 break;
1741         case 's':
1742                 defconfig CSETB(JavaScript, 0);
1743                 break;
1744         case 'S':
1745                 defconfig CSETB(JavaScript, 1);
1746                 break;
1747         case 't':
1748                 defconfig CSETB(StrictTLS, 0);
1749                 break;
1750         case 'T':
1751                 defconfig CSETB(StrictTLS, 1);
1752                 break;
1753         case 'u':
1754                 fulluseragent = EARGF(usage());
1755                 break;
1756         case 'v':
1757                 die("surf-"VERSION", ©2009-2017 surf engineers, "
1758                     "see LICENSE for details\n");
1759         case 'x':
1760                 showxid = 1;
1761                 break;
1762         case 'z':
1763                 defconfig CSETF(ZoomLevel, strtof(EARGF(usage()), NULL));
1764                 break;
1765         default:
1766                 usage();
1767         } ARGEND;
1768         if (argc > 0)
1769                 arg.v = argv[0];
1770         else
1771                 arg.v = "about:blank";
1772
1773         setup();
1774         c = newclient(NULL);
1775         showview(NULL, c);
1776
1777         loaduri(c, &arg);
1778         updatetitle(c);
1779
1780         gtk_main();
1781         cleanup();
1782
1783         return 0;
1784 }