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