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