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