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