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