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