Fix pasteuri()
[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, *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 addaccelgroup(Client *c);
109 static void loaduri(Client *c, const Arg *a);
110 static const char *geturi(Client *c);
111 static void setatom(Client *c, int a, const char *v);
112 static const char *getatom(Client *c, int a);
113 static void updatetitle(Client *c);
114 static void gettogglestats(Client *c);
115 static void getpagestats(Client *c);
116 static WebKitCookieAcceptPolicy cookiepolicy_get(void);
117 static char cookiepolicy_set(const WebKitCookieAcceptPolicy p);
118 static const char *getstyle(const char *uri);
119 static void setstyle(Client *c, const char *stylefile);
120 static void runscript(Client *c);
121 static void evalscript(Client *c, const char *jsstr, ...);
122 static void updatewinid(Client *c);
123 static void handleplumb(Client *c, const char *uri);
124 static void newwindow(Client *c, const Arg *a, int noembed);
125 static void spawn(Client *c, const Arg *a);
126 static void destroyclient(Client *c);
127 static void cleanup(void);
128
129 /* GTK/WebKit */
130 static WebKitWebView *newview(Client *c, WebKitWebView *rv);
131 static GtkWidget *createview(WebKitWebView *v, WebKitNavigationAction *a,
132                              Client *c);
133 static gboolean buttonreleased(GtkWidget *w, GdkEvent *e, Client *c);
134 static gboolean keypress(GtkAccelGroup *group, GObject *obj, guint key,
135                          GdkModifierType mods, Client *c);
136 static GdkFilterReturn processx(GdkXEvent *xevent, GdkEvent *event,
137                                 gpointer d);
138 static gboolean winevent(GtkWidget *w, GdkEvent *e, Client *c);
139 static void showview(WebKitWebView *v, Client *c);
140 static GtkWidget *createwindow(Client *c);
141 static void loadchanged(WebKitWebView *v, WebKitLoadEvent e, Client *c);
142 static void progresschanged(WebKitWebView *v, GParamSpec *ps, Client *c);
143 static void titlechanged(WebKitWebView *view, GParamSpec *ps, Client *c);
144 static void mousetargetchanged(WebKitWebView *v, WebKitHitTestResult *h,
145                                guint modifiers, Client *c);
146 static gboolean permissionrequested(WebKitWebView *v,
147                                     WebKitPermissionRequest *r, Client *c);
148 static gboolean decidepolicy(WebKitWebView *v, WebKitPolicyDecision *d,
149                              WebKitPolicyDecisionType dt, Client *c);
150 static void decidenavigation(WebKitPolicyDecision *d, Client *c);
151 static void decidenewwindow(WebKitPolicyDecision *d, Client *c);
152 static void decideresource(WebKitPolicyDecision *d, Client *c);
153 static void downloadstarted(WebKitWebContext *wc, WebKitDownload *d,
154                             Client *c);
155 static void responsereceived(WebKitDownload *d, GParamSpec *ps, Client *c);
156 static void download(Client *c, WebKitURIResponse *r);
157 static void closeview(WebKitWebView *v, Client *c);
158 static void destroywin(GtkWidget* w, Client *c);
159
160 /* Hotkeys */
161 static void pasteuri(GtkClipboard *clipboard, const char *text, gpointer d);
162 static void reload(Client *c, const Arg *a);
163 static void print(Client *c, const Arg *a);
164 static void clipboard(Client *c, const Arg *a);
165 static void zoom(Client *c, const Arg *a);
166 static void scroll_v(Client *c, const Arg *a);
167 static void scroll_h(Client *c, const Arg *a);
168 static void navigate(Client *c, const Arg *a);
169 static void stop(Client *c, const Arg *a);
170 static void toggle(Client *c, const Arg *a);
171 static void togglefullscreen(Client *c, const Arg *a);
172 static void togglecookiepolicy(Client *c, const Arg *a);
173 static void togglestyle(Client *c, const Arg *a);
174 static void toggleinspector(Client *c, const Arg *a);
175 static void find(Client *c, const Arg *a);
176
177 /* Buttons */
178 static void clicknavigate(Client *c, const Arg *a, WebKitHitTestResult *h);
179 static void clicknewwindow(Client *c, const Arg *a, WebKitHitTestResult *h);
180 static void clickexternplayer(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 int showxid;
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(1);
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) {
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 (waitpid(-1, NULL, WNOHANG) > 0)
263                 ;
264 }
265
266 char *
267 buildfile(const char *path)
268 {
269         char *dname, *bname, *bpath, *fpath;
270         FILE *f;
271
272         dname = g_path_get_dirname(path);
273         bname = g_path_get_basename(path);
274
275         bpath = buildpath(dname);
276         g_free(dname);
277
278         fpath = g_build_filename(bpath, bname, NULL);
279         g_free(bpath);
280         g_free(bname);
281
282         if (!(f = fopen(fpath, "a")))
283                 die("Could not open file: %s\n", fpath);
284
285         g_chmod(fpath, 0600); /* always */
286         fclose(f);
287
288         return fpath;
289 }
290
291 char *
292 buildpath(const char *path)
293 {
294         struct passwd *pw;
295         char *apath, *name, *p, *fpath;
296
297         if (path[0] == '~') {
298                 if (path[1] == '/' || path[1] == '\0') {
299                         p = (char *)&path[1];
300                         pw = getpwuid(getuid());
301                 } else {
302                         if ((p = strchr(path, '/')))
303                                 name = g_strndup(&path[1], --p - path);
304                         else
305                                 name = g_strdup(&path[1]);
306
307                         if (!(pw = getpwnam(name))) {
308                                 die("Can't get user %s home directory: %s.\n",
309                                     name, path);
310                         }
311                         g_free(name);
312                 }
313                 apath = g_build_filename(pw->pw_dir, p, NULL);
314         } else {
315                 apath = g_strdup(path);
316         }
317
318         /* creating directory */
319         if (g_mkdir_with_parents(apath, 0700) < 0)
320                 die("Could not access directory: %s\n", apath);
321
322         fpath = realpath(apath, NULL);
323         g_free(apath);
324
325         return fpath;
326 }
327
328 Client *
329 newclient(Client *rc)
330 {
331         Client *c;
332
333         if (!(c = calloc(1, sizeof(Client))))
334                 die("Cannot malloc!\n");
335
336         c->title = NULL;
337         c->progress = 100;
338
339         c->next = clients;
340         clients = c;
341
342         c->view = newview(c, rc ? rc->view : NULL);
343         c->tlsflags = G_TLS_CERTIFICATE_VALIDATE_ALL + 1;
344
345         return c;
346 }
347
348 void
349 addaccelgroup(Client *c)
350 {
351         int i;
352         GtkAccelGroup *group = gtk_accel_group_new();
353         GClosure *closure;
354
355         for (i = 0; i < LENGTH(keys); i++) {
356                 closure = g_cclosure_new(G_CALLBACK(keypress), c, NULL);
357                 gtk_accel_group_connect(group, keys[i].keyval, keys[i].mod, 0,
358                                         closure);
359         }
360         gtk_window_add_accel_group(GTK_WINDOW(c->win), group);
361 }
362
363 void
364 loaduri(Client *c, const Arg *a)
365 {
366         struct stat st;
367         char *url, *path;
368         const char *uri = a->v;
369
370         if (g_strcmp0(uri, "") == 0)
371                 return;
372
373         if (g_strrstr(uri, "://") || g_str_has_prefix(uri, "about:")) {
374                 url = g_strdup(uri);
375         } else if (!stat(uri, &st) && (path = realpath(uri, NULL))) {
376                 url = g_strdup_printf("file://%s", path);
377                 free(path);
378         } else {
379                 url = g_strdup_printf("http://%s", uri);
380         }
381
382         setatom(c, AtomUri, url);
383
384         if (strcmp(url, geturi(c)) == 0) {
385                 reload(c, a);
386         } else {
387                 webkit_web_view_load_uri(c->view, url);
388                 c->title = geturi(c);
389                 updatetitle(c);
390         }
391
392         g_free(url);
393 }
394
395 const char *
396 geturi(Client *c)
397 {
398         const char *uri;
399
400         if (!(uri = webkit_web_view_get_uri(c->view)))
401                 uri = "about:blank";
402         return uri;
403 }
404
405 void
406 setatom(Client *c, int a, const char *v)
407 {
408         XSync(dpy, False);
409         XChangeProperty(dpy, c->xid,
410                         atoms[a], XA_STRING, 8, PropModeReplace,
411                         (unsigned char *)v, strlen(v) + 1);
412 }
413
414 const char *
415 getatom(Client *c, int a)
416 {
417         static char buf[BUFSIZ];
418         Atom adummy;
419         int idummy;
420         unsigned long ldummy;
421         unsigned char *p = NULL;
422
423         XGetWindowProperty(dpy, c->xid, 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 p)
502 {
503         switch (p) {
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 char *
517 getstyle(const char *uri)
518 {
519         int i;
520
521         if (stylefile)
522                 return stylefile;
523
524         for (i = 0; i < LENGTH(styles); ++i) {
525                 if (styles[i].regex &&
526                     !regexec(&(styles[i].re), uri, 0, 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 char *uri)
586 {
587         Arg a = (Arg)PLUMB(uri);
588         spawn(c, &a);
589 }
590
591 void
592 newwindow(Client *c, const Arg *a, int noembed)
593 {
594         int i = 0;
595         char tmp[64];
596         const char *cmd[26], *uri;
597         const Arg arg = { .v = cmd };
598
599         cmd[i++] = argv0;
600         cmd[i++] = "-a";
601         cmd[i++] = cookiepolicies;
602         cmd[i++] = enablescrollbars ? "-B" : "-b";
603         if (cookiefile && g_strcmp0(cookiefile, "")) {
604                 cmd[i++] = "-c";
605                 cmd[i++] = cookiefile;
606         }
607         cmd[i++] = enablecache ? "-D" : "-d";
608         if (embed && !noembed) {
609                 cmd[i++] = "-e";
610                 snprintf(tmp, LENGTH(tmp), "%lu", embed);
611                 cmd[i++] = tmp;
612         }
613         cmd[i++] = runinfullscreen ? "-F" : "-f";
614         cmd[i++] = allowgeolocation ? "-G" : "-g";
615         cmd[i++] = loadimages ? "-I" : "-i";
616         cmd[i++] = kioskmode ? "-K" : "-k";
617         cmd[i++] = enablestyle ? "-M" : "-m";
618         cmd[i++] = enableinspector ? "-N" : "-n";
619         cmd[i++] = enableplugins ? "-P" : "-p";
620         if (scriptfile && g_strcmp0(scriptfile, "")) {
621                 cmd[i++] = "-r";
622                 cmd[i++] = scriptfile;
623         }
624         cmd[i++] = enablescripts ? "-S" : "-s";
625         if (stylefile && g_strcmp0(stylefile, "")) {
626                 cmd[i++] = "-t";
627                 cmd[i++] = stylefile;
628         }
629         if (fulluseragent && g_strcmp0(fulluseragent, "")) {
630                 cmd[i++] = "-u";
631                 cmd[i++] = fulluseragent;
632         }
633         if (showxid)
634                 cmd[i++] = "-x";
635         /* do not keep zoom level */
636         cmd[i++] = "--";
637         if ((uri = a->v))
638                 cmd[i++] = uri;
639         cmd[i] = NULL;
640
641         spawn(c, &arg);
642 }
643
644 void
645 spawn(Client *c, const Arg *a)
646 {
647         if (fork() == 0) {
648                 if (dpy)
649                         close(ConnectionNumber(dpy));
650                 setsid();
651                 execvp(((char **)a->v)[0], (char **)a->v);
652                 fprintf(stderr, "surf: execvp %s", ((char **)a->v)[0]);
653                 perror(" failed");
654                 exit(0);
655         }
656 }
657
658 void
659 destroyclient(Client *c)
660 {
661         Client *p;
662
663         webkit_web_view_stop_loading(c->view);
664         /* Not needed, has already been called
665         gtk_widget_destroy(c->win);
666          */
667
668         for (p = clients; p && p->next != c; p = p->next)
669                 ;
670         if (p)
671                 p->next = c->next;
672         else
673                 clients = c->next;
674         free(c);
675 }
676
677 void
678 cleanup(void)
679 {
680         while (clients)
681                 destroyclient(clients);
682         g_free(cookiefile);
683         g_free(scriptfile);
684         g_free(stylefile);
685         g_free(cachedir);
686 }
687
688 WebKitWebView *
689 newview(Client *c, WebKitWebView *rv)
690 {
691         WebKitWebView *v;
692         WebKitSettings *settings;
693         WebKitUserContentManager *contentmanager;
694         WebKitWebContext *context;
695
696         /* Webview */
697         if (rv) {
698                 v = WEBKIT_WEB_VIEW(
699                     webkit_web_view_new_with_related_view(rv));
700         } else {
701                 settings = webkit_settings_new_with_settings(
702                            "auto-load-images", loadimages,
703                            "default-font-size", defaultfontsize,
704                            "enable-caret-browsing", enablecaretbrowsing,
705                            "enable-developer-extras", enableinspector,
706                            "enable-dns-prefetching", enablednsprefetching,
707                            "enable-frame-flattening", enableframeflattening,
708                            "enable-html5-database", enablecache,
709                            "enable-html5-local-storage", enablecache,
710                            "enable-javascript", enablescripts,
711                            "enable-plugins", enableplugins,
712                            NULL);
713 /* For mor interesting settings, have a look at
714  * http://webkitgtk.org/reference/webkit2gtk/stable/WebKitSettings.html */
715
716                 if (strcmp(fulluseragent, "")) {
717                         webkit_settings_set_user_agent(settings, fulluseragent);
718                 } else if (surfuseragent) {
719                         webkit_settings_set_user_agent_with_application_details(
720                             settings, "Surf", VERSION);
721                 }
722                 useragent = webkit_settings_get_user_agent(settings);
723
724                 contentmanager = webkit_user_content_manager_new();
725
726                 context = webkit_web_context_new_with_website_data_manager(
727                           webkit_website_data_manager_new(
728                           "base-cache-directory", cachedir,
729                           "base-data-directory", cachedir,
730                           NULL));
731
732                 /* rendering process model, can be a shared unique one
733                  * or one for each view */
734                 webkit_web_context_set_process_model(context,
735                     WEBKIT_PROCESS_MODEL_MULTIPLE_SECONDARY_PROCESSES);
736                 /* ssl */
737                 webkit_web_context_set_tls_errors_policy(context, strictssl ?
738                     WEBKIT_TLS_ERRORS_POLICY_FAIL :
739                     WEBKIT_TLS_ERRORS_POLICY_IGNORE);
740                 /* disk cache */
741                 webkit_web_context_set_cache_model(context, enablecache ?
742                     WEBKIT_CACHE_MODEL_WEB_BROWSER :
743                     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), "notify::title",
765                          G_CALLBACK(titlechanged), c);
766         g_signal_connect(G_OBJECT(v), "mouse-target-changed",
767                          G_CALLBACK(mousetargetchanged), c);
768         g_signal_connect(G_OBJECT(v), "permission-request",
769                          G_CALLBACK(permissionrequested), c);
770         g_signal_connect(G_OBJECT(v), "create",
771                          G_CALLBACK(createview), c);
772         g_signal_connect(G_OBJECT(v), "ready-to-show",
773                          G_CALLBACK(showview), c);
774         g_signal_connect(G_OBJECT(v), "decide-policy",
775                          G_CALLBACK(decidepolicy), c);
776         g_signal_connect(G_OBJECT(v), "load-changed",
777                          G_CALLBACK(loadchanged), c);
778         g_signal_connect(G_OBJECT(v), "notify::estimated-load-progress",
779                          G_CALLBACK(progresschanged), c);
780         g_signal_connect(G_OBJECT(v), "button-release-event",
781                          G_CALLBACK(buttonreleased), c);
782         g_signal_connect(G_OBJECT(v), "close",
783                         G_CALLBACK(closeview), c);
784
785         return v;
786 }
787
788 GtkWidget *
789 createview(WebKitWebView *v, WebKitNavigationAction *a, Client *c)
790 {
791         Client *n;
792
793         switch (webkit_navigation_action_get_navigation_type(a)) {
794         case WEBKIT_NAVIGATION_TYPE_OTHER: /* fallthrough */
795                 /*
796                  * popup windows of type “other” are almost always triggered
797                  * by user gesture, so inverse the logic here
798                  */
799 /* instead of this, compare destination uri to mouse-over uri for validating window */
800                 if (webkit_navigation_action_is_user_gesture(a))
801                         return NULL;
802         case WEBKIT_NAVIGATION_TYPE_LINK_CLICKED: /* fallthrough */
803         case WEBKIT_NAVIGATION_TYPE_FORM_SUBMITTED: /* fallthrough */
804         case WEBKIT_NAVIGATION_TYPE_BACK_FORWARD: /* fallthrough */
805         case WEBKIT_NAVIGATION_TYPE_RELOAD: /* fallthrough */
806         case WEBKIT_NAVIGATION_TYPE_FORM_RESUBMITTED:
807                 n = newclient(c);
808                 break;
809         default:
810                 return NULL;
811         }
812
813         return GTK_WIDGET(n->view);
814 }
815
816 gboolean
817 buttonreleased(GtkWidget *w, GdkEvent *e, Client *c)
818 {
819         WebKitHitTestResultContext element;
820         int i;
821
822         element = webkit_hit_test_result_get_context(c->mousepos);
823
824         for (i = 0; i < LENGTH(buttons); ++i) {
825                 if (element & buttons[i].target &&
826                     e->button.button == buttons[i].button &&
827                     CLEANMASK(e->button.state) == CLEANMASK(buttons[i].mask) &&
828                     buttons[i].func) {
829                         buttons[i].func(c, &buttons[i].arg, c->mousepos);
830                         return buttons[i].stopevent;
831                 }
832         }
833
834         return FALSE;
835 }
836
837 gboolean
838 keypress(GtkAccelGroup *group, GObject *obj, guint key, GdkModifierType mods,
839          Client *c)
840 {
841         guint i;
842         gboolean processed = FALSE;
843
844         mods = CLEANMASK(mods);
845         key = gdk_keyval_to_lower(key);
846         updatewinid(c);
847         for (i = 0; i < LENGTH(keys); i++) {
848                 if (key == keys[i].keyval
849                     && mods == keys[i].mod
850                     && keys[i].func) {
851                         keys[i].func(c, &(keys[i].arg));
852                         processed = TRUE;
853                 }
854         }
855
856         return processed;
857 }
858
859 GdkFilterReturn
860 processx(GdkXEvent *e, GdkEvent *event, gpointer d)
861 {
862         Client *c = (Client *)d;
863         XPropertyEvent *ev;
864         Arg a;
865
866         if (((XEvent *)e)->type == PropertyNotify) {
867                 ev = &((XEvent *)e)->xproperty;
868                 if (ev->state == PropertyNewValue) {
869                         if (ev->atom == atoms[AtomFind]) {
870                                 find(c, NULL);
871
872                                 return GDK_FILTER_REMOVE;
873                         } else if (ev->atom == atoms[AtomGo]) {
874                                 a.v = getatom(c, AtomGo);
875                                 loaduri(c, &a);
876
877                                 return GDK_FILTER_REMOVE;
878                         }
879                 }
880         }
881         return GDK_FILTER_CONTINUE;
882 }
883
884 gboolean
885 winevent(GtkWidget *w, GdkEvent *e, Client *c)
886 {
887         switch (e->type) {
888         case GDK_LEAVE_NOTIFY:
889                 c->targeturi = NULL;
890                 updatetitle(c);
891                 break;
892         case GDK_WINDOW_STATE: /* fallthrough */
893                 if (e->window_state.changed_mask ==
894                     GDK_WINDOW_STATE_FULLSCREEN) {
895                         c->fullscreen = e->window_state.new_window_state &
896                                         GDK_WINDOW_STATE_FULLSCREEN;
897                         break;
898                 }
899         default:
900                 return FALSE;
901         }
902
903         return TRUE;
904 }
905
906 void
907 showview(WebKitWebView *v, Client *c)
908 {
909         GdkRGBA bgcolor = { 0 };
910         GdkWindow *gwin;
911
912         c->finder = webkit_web_view_get_find_controller(c->view);
913         if (enableinspector)
914                 c->inspector = webkit_web_view_get_inspector(c->view);
915
916         c->win = createwindow(c);
917
918         gtk_container_add(GTK_CONTAINER(c->win), GTK_WIDGET(c->view));
919         gtk_widget_show_all(c->win);
920         gtk_widget_grab_focus(GTK_WIDGET(c->view));
921
922         gwin = gtk_widget_get_window(GTK_WIDGET(c->win));
923         c->xid = gdk_x11_window_get_xid(gwin);
924         updatewinid(c);
925         if (showxid) {
926                 gdk_display_sync(gtk_widget_get_display(c->win));
927                 puts(winid);
928         }
929
930         if (hidebackground)
931                 webkit_web_view_set_background_color(c->view, &bgcolor);
932
933         if (!kioskmode) {
934                 addaccelgroup(c);
935                 gdk_window_set_events(gwin, GDK_ALL_EVENTS_MASK);
936                 gdk_window_add_filter(gwin, processx, c);
937         }
938
939         if (runinfullscreen)
940                 togglefullscreen(c, NULL);
941
942         if (zoomlevel != 1.0)
943                 webkit_web_view_set_zoom_level(c->view, zoomlevel);
944
945         setatom(c, AtomFind, "");
946         setatom(c, AtomUri, "about:blank");
947 }
948
949 GtkWidget *
950 createwindow(Client *c)
951 {
952         char *wmstr;
953         GtkWidget *w;
954
955         if (embed) {
956                 w = gtk_plug_new(embed);
957         } else {
958                 w = gtk_window_new(GTK_WINDOW_TOPLEVEL);
959
960                 wmstr = g_path_get_basename(argv0);
961                 gtk_window_set_wmclass(GTK_WINDOW(w), wmstr, "Surf");
962                 g_free(wmstr);
963
964                 wmstr = g_strdup_printf("%s[%lu]", "Surf",
965                         webkit_web_view_get_page_id(c->view));
966                 gtk_window_set_role(GTK_WINDOW(w), wmstr);
967                 g_free(wmstr);
968
969                 gtk_window_set_default_size(GTK_WINDOW(w), 800, 600);
970         }
971
972         g_signal_connect(G_OBJECT(w), "destroy",
973                          G_CALLBACK(destroywin), c);
974         g_signal_connect(G_OBJECT(w), "leave-notify-event",
975                          G_CALLBACK(winevent), c);
976         g_signal_connect(G_OBJECT(w), "window-state-event",
977                          G_CALLBACK(winevent), c);
978
979         return w;
980 }
981
982 void
983 loadchanged(WebKitWebView *v, WebKitLoadEvent e, Client *c)
984 {
985         switch (e) {
986         case WEBKIT_LOAD_STARTED:
987                 c->tlsflags = G_TLS_CERTIFICATE_VALIDATE_ALL + 1;
988                 break;
989         case WEBKIT_LOAD_REDIRECTED:
990                 setatom(c, AtomUri, geturi(c));
991                 break;
992         case WEBKIT_LOAD_COMMITTED:
993                 if (!webkit_web_view_get_tls_info(c->view, NULL,
994                     &(c->tlsflags)))
995                         c->tlsflags = G_TLS_CERTIFICATE_VALIDATE_ALL + 1;
996
997                 setatom(c, AtomUri, geturi(c));
998
999                 if (enablestyle)
1000                         setstyle(c, getstyle(geturi(c)));
1001                 break;
1002         case WEBKIT_LOAD_FINISHED:
1003                 /* Disabled until we write some WebKitWebExtension for
1004                  * manipulating the DOM directly.
1005                 evalscript(c, "document.documentElement.style.overflow = '%s'",
1006                     enablescrollbars ? "auto" : "hidden");
1007                 */
1008                 runscript(c);
1009                 break;
1010         }
1011         updatetitle(c);
1012 }
1013
1014 void
1015 progresschanged(WebKitWebView *v, GParamSpec *ps, Client *c)
1016 {
1017         c->progress = webkit_web_view_get_estimated_load_progress(c->view) *
1018                       100;
1019         updatetitle(c);
1020 }
1021
1022 void
1023 titlechanged(WebKitWebView *view, GParamSpec *ps, Client *c)
1024 {
1025         c->title = webkit_web_view_get_title(c->view);
1026         updatetitle(c);
1027 }
1028
1029 void
1030 mousetargetchanged(WebKitWebView *v, WebKitHitTestResult *h, guint modifiers,
1031     Client *c)
1032 {
1033         WebKitHitTestResultContext hc = webkit_hit_test_result_get_context(h);
1034
1035         /* Keep the hit test to know where is the pointer on the next click */
1036         c->mousepos = h;
1037
1038         if (hc & OnLink)
1039                 c->targeturi = webkit_hit_test_result_get_link_uri(h);
1040         else if (hc & OnImg)
1041                 c->targeturi = webkit_hit_test_result_get_image_uri(h);
1042         else if (hc & OnMedia)
1043                 c->targeturi = webkit_hit_test_result_get_media_uri(h);
1044         else
1045                 c->targeturi = NULL;
1046         updatetitle(c);
1047 }
1048
1049 gboolean
1050 permissionrequested(WebKitWebView *v, WebKitPermissionRequest *r, Client *c)
1051 {
1052         if (WEBKIT_IS_GEOLOCATION_PERMISSION_REQUEST(r)) {
1053                 if (allowgeolocation)
1054                         webkit_permission_request_allow(r);
1055                 else
1056                         webkit_permission_request_deny(r);
1057                 return TRUE;
1058         }
1059
1060         return FALSE;
1061 }
1062
1063 gboolean
1064 decidepolicy(WebKitWebView *v, WebKitPolicyDecision *d,
1065     WebKitPolicyDecisionType dt, Client *c)
1066 {
1067         switch (dt) {
1068         case WEBKIT_POLICY_DECISION_TYPE_NAVIGATION_ACTION:
1069                 decidenavigation(d, c);
1070                 break;
1071         case WEBKIT_POLICY_DECISION_TYPE_NEW_WINDOW_ACTION:
1072                 decidenewwindow(d, c);
1073                 break;
1074         case WEBKIT_POLICY_DECISION_TYPE_RESPONSE:
1075                 decideresource(d, c);
1076                 break;
1077         default:
1078                 webkit_policy_decision_ignore(d);
1079                 break;
1080         }
1081         return TRUE;
1082 }
1083
1084 void
1085 decidenavigation(WebKitPolicyDecision *d, Client *c)
1086 {
1087         WebKitNavigationAction *a =
1088             webkit_navigation_policy_decision_get_navigation_action(
1089             WEBKIT_NAVIGATION_POLICY_DECISION(d));
1090
1091         switch (webkit_navigation_action_get_navigation_type(a)) {
1092         case WEBKIT_NAVIGATION_TYPE_LINK_CLICKED: /* fallthrough */
1093         case WEBKIT_NAVIGATION_TYPE_FORM_SUBMITTED: /* fallthrough */
1094         case WEBKIT_NAVIGATION_TYPE_BACK_FORWARD: /* fallthrough */
1095         case WEBKIT_NAVIGATION_TYPE_RELOAD: /* fallthrough */
1096         case WEBKIT_NAVIGATION_TYPE_FORM_RESUBMITTED: /* fallthrough */
1097         case WEBKIT_NAVIGATION_TYPE_OTHER: /* fallthrough */
1098         default:
1099                 /* Do not navigate to links with a "_blank" target (popup) */
1100                 if (webkit_navigation_policy_decision_get_frame_name(
1101                     WEBKIT_NAVIGATION_POLICY_DECISION(d))) {
1102                         webkit_policy_decision_ignore(d);
1103                 } else {
1104                         /* Filter out navigation to different domain ? */
1105                         /* get action→urirequest, copy and load in new window+view
1106                          * on Ctrl+Click ? */
1107                         webkit_policy_decision_use(d);
1108                 }
1109                 break;
1110         }
1111 }
1112
1113 void
1114 decidenewwindow(WebKitPolicyDecision *d, Client *c)
1115 {
1116         Arg arg;
1117         WebKitNavigationAction *a =
1118             webkit_navigation_policy_decision_get_navigation_action(
1119             WEBKIT_NAVIGATION_POLICY_DECISION(d));
1120
1121
1122         switch (webkit_navigation_action_get_navigation_type(a)) {
1123         case WEBKIT_NAVIGATION_TYPE_LINK_CLICKED: /* fallthrough */
1124         case WEBKIT_NAVIGATION_TYPE_FORM_SUBMITTED: /* fallthrough */
1125         case WEBKIT_NAVIGATION_TYPE_BACK_FORWARD: /* fallthrough */
1126         case WEBKIT_NAVIGATION_TYPE_RELOAD: /* fallthrough */
1127         case WEBKIT_NAVIGATION_TYPE_FORM_RESUBMITTED:
1128                 /* Filter domains here */
1129 /* If the value of “mouse-button” is not 0, then the navigation was triggered by a mouse event.
1130  * test for link clicked but no button ? */
1131                 arg.v = webkit_uri_request_get_uri(
1132                         webkit_navigation_action_get_request(a));
1133                 newwindow(c, &arg, 0);
1134                 break;
1135         case WEBKIT_NAVIGATION_TYPE_OTHER: /* fallthrough */
1136         default:
1137                 break;
1138         }
1139
1140         webkit_policy_decision_ignore(d);
1141 }
1142
1143 void
1144 decideresource(WebKitPolicyDecision *d, Client *c)
1145 {
1146         int i, isascii = 1;
1147         WebKitResponsePolicyDecision *r = WEBKIT_RESPONSE_POLICY_DECISION(d);
1148         WebKitURIResponse *res =
1149             webkit_response_policy_decision_get_response(r);
1150         const gchar *uri = webkit_uri_response_get_uri(res);
1151
1152         if (g_str_has_suffix(uri, "/favicon.ico"))
1153                 webkit_uri_request_set_uri(
1154                     webkit_response_policy_decision_get_request(r),
1155                     "about:blank");
1156
1157         if (!g_str_has_prefix(uri, "http://")
1158             && !g_str_has_prefix(uri, "https://")
1159             && !g_str_has_prefix(uri, "about:")
1160             && !g_str_has_prefix(uri, "file://")
1161             && !g_str_has_prefix(uri, "data:")
1162             && !g_str_has_prefix(uri, "blob:")
1163             && strlen(uri) > 0) {
1164                 for (i = 0; i < strlen(uri); i++) {
1165                         if (!g_ascii_isprint(uri[i])) {
1166                                 isascii = 0;
1167                                 break;
1168                         }
1169                 }
1170                 if (isascii) {
1171                         handleplumb(c, uri);
1172                         webkit_policy_decision_ignore(d);
1173                 }
1174         }
1175
1176         if (webkit_response_policy_decision_is_mime_type_supported(r)) {
1177                 webkit_policy_decision_use(d);
1178         } else {
1179                 webkit_policy_decision_ignore(d);
1180                 download(c, res);
1181         }
1182 }
1183
1184 void
1185 downloadstarted(WebKitWebContext *wc, WebKitDownload *d, Client *c)
1186 {
1187         g_signal_connect(G_OBJECT(d), "notify::response",
1188                          G_CALLBACK(responsereceived), c);
1189 }
1190
1191 void
1192 responsereceived(WebKitDownload *d, GParamSpec *ps, Client *c)
1193 {
1194         download(c, webkit_download_get_response(d));
1195         webkit_download_cancel(d);
1196 }
1197
1198 void
1199 download(Client *c, WebKitURIResponse *r)
1200 {
1201         Arg a = (Arg)DOWNLOAD(webkit_uri_response_get_uri(r), geturi(c));
1202         spawn(c, &a);
1203 }
1204
1205 void
1206 closeview(WebKitWebView *v, Client *c)
1207 {
1208         gtk_widget_destroy(c->win);
1209 }
1210
1211 void
1212 destroywin(GtkWidget* w, Client *c)
1213 {
1214         destroyclient(c);
1215         if (!clients)
1216                 gtk_main_quit();
1217 }
1218
1219 void
1220 pasteuri(GtkClipboard *clipboard, const char *text, gpointer d)
1221 {
1222         Arg a = {.v = text };
1223         if (text)
1224                 loaduri((Client *) d, &a);
1225 }
1226
1227 void
1228 reload(Client *c, const Arg *a)
1229 {
1230         if (a->b)
1231                 webkit_web_view_reload_bypass_cache(c->view);
1232         else
1233                 webkit_web_view_reload(c->view);
1234 }
1235
1236 void
1237 print(Client *c, const Arg *a)
1238 {
1239         webkit_print_operation_run_dialog(webkit_print_operation_new(c->view),
1240                                           GTK_WINDOW(c->win));
1241 }
1242
1243 void
1244 clipboard(Client *c, const Arg *a)
1245 {
1246         if (a->b) { /* load clipboard uri */
1247                 gtk_clipboard_request_text(gtk_clipboard_get(
1248                                            GDK_SELECTION_PRIMARY),
1249                                            pasteuri, c);
1250         } else { /* copy uri */
1251                 gtk_clipboard_set_text(gtk_clipboard_get(
1252                                        GDK_SELECTION_PRIMARY), c->targeturi
1253                                        ? c->targeturi : geturi(c), -1);
1254         }
1255 }
1256
1257 void
1258 zoom(Client *c, const Arg *a)
1259 {
1260         if (a->i > 0)
1261                 webkit_web_view_set_zoom_level(c->view, zoomlevel + 0.1);
1262         else if (a->i < 0)
1263                 webkit_web_view_set_zoom_level(c->view, zoomlevel - 0.1);
1264         else
1265                 webkit_web_view_set_zoom_level(c->view, 1.0);
1266
1267         zoomlevel = webkit_web_view_get_zoom_level(c->view);
1268 }
1269
1270 void
1271 scroll_v(Client *c, const Arg *a)
1272 {
1273         evalscript(c, "window.scrollBy(0, %d * (window.innerHeight / 100))",
1274                    a->i);
1275 }
1276
1277 void
1278 scroll_h(Client *c, const Arg *a)
1279 {
1280         evalscript(c, "window.scrollBy(%d * (window.innerWidth / 100), 0)",
1281                    a->i);
1282 }
1283
1284 void
1285 navigate(Client *c, const Arg *a)
1286 {
1287         if (a->i < 0)
1288                 webkit_web_view_go_back(c->view);
1289         else if (a->i > 0)
1290                 webkit_web_view_go_forward(c->view);
1291 }
1292
1293 void
1294 stop(Client *c, const Arg *a)
1295 {
1296         webkit_web_view_stop_loading(c->view);
1297 }
1298
1299 void
1300 toggle(Client *c, const Arg *a)
1301 {
1302         WebKitSettings *s = webkit_web_view_get_settings(c->view);
1303
1304         switch ((unsigned int)a->i) {
1305         case CaretBrowsing:
1306                 enablecaretbrowsing = !enablecaretbrowsing;
1307                 webkit_settings_set_enable_caret_browsing(s,
1308                     enablecaretbrowsing);
1309                 updatetitle(c);
1310                 return; /* do not reload */
1311                 break;
1312         case FrameFlattening:
1313                 enableframeflattening = !enableframeflattening;
1314                 webkit_settings_set_enable_frame_flattening(s,
1315                     enableframeflattening);
1316                 break;
1317         case Geolocation:
1318                 allowgeolocation = !allowgeolocation;
1319                 break;
1320         case JavaScript:
1321                 enablescripts = !enablescripts;
1322                 webkit_settings_set_enable_javascript(s, enablescripts);
1323                 break;
1324         case LoadImages:
1325                 loadimages = !loadimages;
1326                 webkit_settings_set_auto_load_images(s, loadimages);
1327                 break;
1328         case Plugins:
1329                 enableplugins = !enableplugins;
1330                 webkit_settings_set_enable_plugins(s, enableplugins);
1331                 break;
1332         case ScrollBars:
1333                 /* Disabled until we write some WebKitWebExtension for
1334                  * manipulating the DOM directly.
1335                 enablescrollbars = !enablescrollbars;
1336                 evalscript(c, "document.documentElement.style.overflow = '%s'",
1337                     enablescrollbars ? "auto" : "hidden");
1338                 */
1339                 return; /* do not reload */
1340                 break;
1341         default:
1342                 break;
1343         }
1344         reload(c, a);
1345 }
1346
1347 void
1348 togglefullscreen(Client *c, const Arg *a)
1349 {
1350         /* toggling value is handled in winevent() */
1351         if (c->fullscreen)
1352                 gtk_window_unfullscreen(GTK_WINDOW(c->win));
1353         else
1354                 gtk_window_fullscreen(GTK_WINDOW(c->win));
1355 }
1356
1357 void
1358 togglecookiepolicy(Client *c, const Arg *a)
1359 {
1360         ++cookiepolicy;
1361         cookiepolicy %= strlen(cookiepolicies);
1362
1363         webkit_cookie_manager_set_accept_policy(
1364             webkit_web_context_get_cookie_manager(
1365             webkit_web_view_get_context(c->view)),
1366             cookiepolicy_get());
1367
1368         updatetitle(c);
1369         /* Do not reload. */
1370 }
1371
1372 void
1373 togglestyle(Client *c, const Arg *a)
1374 {
1375         enablestyle = !enablestyle;
1376         setstyle(c, enablestyle ? getstyle(geturi(c)) : "");
1377
1378         updatetitle(c);
1379 }
1380
1381 void
1382 toggleinspector(Client *c, const Arg *a)
1383 {
1384         if (enableinspector) {
1385                 if (webkit_web_inspector_is_attached(c->inspector))
1386                         webkit_web_inspector_close(c->inspector);
1387                 else
1388                         webkit_web_inspector_show(c->inspector);
1389         }
1390 }
1391
1392 void
1393 find(Client *c, const Arg *a)
1394 {
1395         const char *s, *f;
1396
1397         if (a && a->i) {
1398                 if (a->i > 0)
1399                         webkit_find_controller_search_next(c->finder);
1400                 else
1401                         webkit_find_controller_search_previous(c->finder);
1402         } else {
1403                 s = getatom(c, AtomFind);
1404                 f = webkit_find_controller_get_search_text(c->finder);
1405
1406                 if (g_strcmp0(f, s) == 0) /* reset search */
1407                         webkit_find_controller_search(c->finder, "", findopts,
1408                                                       G_MAXUINT);
1409
1410                 webkit_find_controller_search(c->finder, s, findopts,
1411                                               G_MAXUINT);
1412
1413                 if (strcmp(s, "") == 0)
1414                         webkit_find_controller_search_finish(c->finder);
1415         }
1416 }
1417
1418 void
1419 clicknavigate(Client *c, const Arg *a, WebKitHitTestResult *h)
1420 {
1421         navigate(c, a);
1422 }
1423
1424 void
1425 clicknewwindow(Client *c, const Arg *a, WebKitHitTestResult *h)
1426 {
1427         Arg arg;
1428
1429         arg.v = webkit_hit_test_result_get_link_uri(h);
1430         newwindow(c, &arg, a->b);
1431 }
1432
1433 void
1434 clickexternplayer(Client *c, const Arg *a, WebKitHitTestResult *h)
1435 {
1436         Arg arg;
1437
1438         if (webkit_hit_test_result_get_context(h) & OnMedia) {
1439                 arg = (Arg)VIDEOPLAY(webkit_hit_test_result_get_media_uri(h));
1440                 spawn(c, &arg);
1441         }
1442 }
1443
1444 int
1445 main(int argc, char *argv[])
1446 {
1447         Arg arg;
1448         Client *c;
1449
1450         memset(&arg, 0, sizeof(arg));
1451
1452         /* command line args */
1453         ARGBEGIN {
1454         case 'a':
1455                 cookiepolicies = EARGF(usage());
1456                 break;
1457         case 'b':
1458                 enablescrollbars = 0;
1459                 break;
1460         case 'B':
1461                 enablescrollbars = 1;
1462                 break;
1463         case 'c':
1464                 cookiefile = EARGF(usage());
1465                 break;
1466         case 'd':
1467                 enablecache = 0;
1468                 break;
1469         case 'D':
1470                 enablecache = 1;
1471                 break;
1472         case 'e':
1473                 embed = strtol(EARGF(usage()), NULL, 0);
1474                 break;
1475         case 'f':
1476                 runinfullscreen = 0;
1477                 break;
1478         case 'F':
1479                 runinfullscreen = 1;
1480                 break;
1481         case 'g':
1482                 allowgeolocation = 0;
1483                 break;
1484         case 'G':
1485                 allowgeolocation = 1;
1486                 break;
1487         case 'i':
1488                 loadimages = 0;
1489                 break;
1490         case 'I':
1491                 loadimages = 1;
1492                 break;
1493         case 'k':
1494                 kioskmode = 0;
1495                 break;
1496         case 'K':
1497                 kioskmode = 1;
1498                 break;
1499         case 'm':
1500                 enablestyle = 0;
1501                 break;
1502         case 'M':
1503                 enablestyle = 1;
1504                 break;
1505         case 'n':
1506                 enableinspector = 0;
1507                 break;
1508         case 'N':
1509                 enableinspector = 1;
1510                 break;
1511         case 'p':
1512                 enableplugins = 0;
1513                 break;
1514         case 'P':
1515                 enableplugins = 1;
1516                 break;
1517         case 'r':
1518                 scriptfile = EARGF(usage());
1519                 break;
1520         case 's':
1521                 enablescripts = 0;
1522                 break;
1523         case 'S':
1524                 enablescripts = 1;
1525                 break;
1526         case 't':
1527                 stylefile = EARGF(usage());
1528                 break;
1529         case 'u':
1530                 useragent = EARGF(usage());
1531                 break;
1532         case 'v':
1533                 die("surf-"VERSION", ©2009-2015 surf engineers, "
1534                     "see LICENSE for details\n");
1535         case 'x':
1536                 showxid = 1;
1537                 break;
1538         case 'z':
1539                 zoomlevel = strtof(EARGF(usage()), NULL);
1540                 break;
1541         default:
1542                 usage();
1543         } ARGEND;
1544         if (argc > 0)
1545                 arg.v = argv[0];
1546
1547         setup();
1548         c = newclient(NULL);
1549         showview(NULL, c);
1550
1551         if (arg.v)
1552                 loaduri(clients, &arg);
1553         else
1554                 updatetitle(c);
1555
1556         gtk_main();
1557         cleanup();
1558
1559         return 0;
1560 }