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