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