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