Style update for indentation
[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         gboolean b;
60         gint i;
61         const void *v;
62 } Arg;
63
64 typedef struct Client {
65         GtkWidget *win;
66         WebKitWebView *view;
67         WebKitWebInspector *inspector;
68         WebKitFindController *finder;
69         WebKitHitTestResult *mousepos;
70         GTlsCertificateFlags tlsflags;
71         Window xid;
72         gint progress;
73         gboolean fullscreen;
74         const char *title, *targeturi;
75         const char *needle;
76         struct Client *next;
77 } Client;
78
79 typedef struct {
80         guint mod;
81         guint keyval;
82         void (*func)(Client *c, const Arg *a);
83         const Arg arg;
84 } Key;
85
86 typedef struct {
87         unsigned int target;
88         unsigned int mask;
89         guint button;
90         void (*func)(Client *c, const Arg *a, WebKitHitTestResult *h);
91         const Arg arg;
92         unsigned int stopevent;
93 } Button;
94
95 typedef struct {
96         char *regex;
97         char *style;
98         regex_t re;
99 } SiteStyle;
100
101 /* Surf */
102 static void usage(void);
103 static void die(const char *errstr, ...);
104 static void setup(void);
105 static void sigchld(int unused);
106 static char *buildfile(const char *path);
107 static char *buildpath(const char *path);
108 static Client *newclient(Client *c);
109 static void addaccelgroup(Client *c);
110 static void loaduri(Client *c, const Arg *a);
111 static char *geturi(Client *c);
112 static void setatom(Client *c, int a, const char *v);
113 static const char *getatom(Client *c, int a);
114 static void updatetitle(Client *c);
115 static void gettogglestats(Client *c);
116 static void getpagestats(Client *c);
117 static WebKitCookieAcceptPolicy cookiepolicy_get(void);
118 static char cookiepolicy_set(const WebKitCookieAcceptPolicy p);
119 static const gchar *getstyle(const char *uri);
120 static void setstyle(Client *c, const char *stylefile);
121 static void runscript(Client *c);
122 static void evalscript(Client *c, const char *jsstr, ...);
123 static void updatewinid(Client *c);
124 static void handleplumb(Client *c, const gchar *uri);
125 static void newwindow(Client *c, const Arg *a, gboolean noembed);
126 static void spawn(Client *c, const Arg *a);
127 static void destroyclient(Client *c);
128 static void cleanup(void);
129
130 /* GTK/WebKit */
131 static WebKitWebView *newview(Client *c, WebKitWebView *rv);
132 static GtkWidget *createview(WebKitWebView *v, WebKitNavigationAction *a,
133                              Client *c);
134 static gboolean buttonreleased(GtkWidget *w, GdkEventKey *e, Client *c);
135 static gboolean keypress(GtkAccelGroup *group, GObject *obj, guint key,
136                          GdkModifierType mods, Client *c);
137 static GdkFilterReturn processx(GdkXEvent *xevent, GdkEvent *event,
138                                 gpointer d);
139 static gboolean winevent(GtkWidget *w, GdkEvent *e, Client *c);
140 static void showview(WebKitWebView *v, Client *c);
141 static GtkWidget *createwindow(Client *c);
142 static void loadchanged(WebKitWebView *v, WebKitLoadEvent e, Client *c);
143 static void progresschanged(WebKitWebView *v, GParamSpec *ps, Client *c);
144 static void titlechanged(WebKitWebView *view, GParamSpec *ps, Client *c);
145 static void mousetargetchanged(WebKitWebView *v, WebKitHitTestResult *h,
146                                guint modifiers, Client *c);
147 static gboolean permissionrequested(WebKitWebView *v,
148                                     WebKitPermissionRequest *r, Client *c);
149 static gboolean decidepolicy(WebKitWebView *v, WebKitPolicyDecision *d,
150                              WebKitPolicyDecisionType dt, Client *c);
151 static void decidenavigation(WebKitPolicyDecision *d, Client *c);
152 static void decidenewwindow(WebKitPolicyDecision *d, Client *c);
153 static void decideresource(WebKitPolicyDecision *d, Client *c);
154 static void downloadstarted(WebKitWebContext *wc, WebKitDownload *d,
155                             Client *c);
156 static void responsereceived(WebKitDownload *d, GParamSpec *ps, Client *c);
157 static void download(Client *c, WebKitURIResponse *r);
158 static void closeview(WebKitWebView *v, Client *c);
159 static void destroywin(GtkWidget* w, Client *c);
160
161 /* Hotkeys */
162 static void pasteuri(GtkClipboard *clipboard, const char *text, gpointer d);
163 static void reload(Client *c, const Arg *a);
164 static void print(Client *c, const Arg *a);
165 static void clipboard(Client *c, const Arg *a);
166 static void zoom(Client *c, const Arg *a);
167 static void scroll_v(Client *c, const Arg *a);
168 static void scroll_h(Client *c, const Arg *a);
169 static void navigate(Client *c, const Arg *a);
170 static void stop(Client *c, const Arg *a);
171 static void toggle(Client *c, const Arg *a);
172 static void togglefullscreen(Client *c, const Arg *a);
173 static void togglecookiepolicy(Client *c, const Arg *a);
174 static void togglestyle(Client *c, const Arg *a);
175 static void toggleinspector(Client *c, const Arg *a);
176 static void find(Client *c, const Arg *a);
177
178 /* Buttons */
179 static void clicknavigate(Client *c, const Arg *a, WebKitHitTestResult *h);
180 static void clicknewwindow(Client *c, const Arg *a, WebKitHitTestResult *h);
181 static void clickexternplayer(Client *c, const Arg *a, WebKitHitTestResult *h);
182
183 static char winid[64];
184 static char togglestats[10];
185 static char pagestats[2];
186 static Atom atoms[AtomLast];
187 static Window embed;
188 static gboolean showxid = FALSE;
189 static int cookiepolicy;
190 static Display *dpy;
191 static Client *clients;
192 static char *stylefile;
193 static const char *useragent;
194 char *argv0;
195
196 /* configuration, allows nested code to access above variables */
197 #include "config.h"
198
199 void
200 usage(void)
201 {
202         die("usage: %s [-bBdDfFgGiIkKmMnNpPsSvx] [-a cookiepolicies ] "
203             "[-c cookiefile] [-e xid] [-r scriptfile] [-t stylefile] "
204             "[-u useragent] [-z zoomlevel] [uri]\n", basename(argv0));
205 }
206
207 void
208 die(const char *errstr, ...)
209 {
210         va_list ap;
211
212         va_start(ap, errstr);
213         vfprintf(stderr, errstr, ap);
214         va_end(ap);
215         exit(EXIT_FAILURE);
216 }
217
218 void
219 setup(void)
220 {
221         int i;
222
223         /* clean up any zombies immediately */
224         sigchld(0);
225         gtk_init(NULL, NULL);
226
227         dpy = GDK_DISPLAY_XDISPLAY(gdk_display_get_default());
228
229         /* atoms */
230         atoms[AtomFind] = XInternAtom(dpy, "_SURF_FIND", False);
231         atoms[AtomGo] = XInternAtom(dpy, "_SURF_GO", False);
232         atoms[AtomUri] = XInternAtom(dpy, "_SURF_URI", False);
233
234         /* dirs and files */
235         cookiefile = buildfile(cookiefile);
236         scriptfile = buildfile(scriptfile);
237         cachedir   = buildpath(cachedir);
238
239         if (!stylefile) {
240                 styledir = buildpath(styledir);
241                 for (i = 0; i < LENGTH(styles); ++i) {
242                         if (regcomp(&(styles[i].re), styles[i].regex,
243                             REG_EXTENDED)) {
244                                 fprintf(stderr,
245                                         "Could not compile regex: %s\n",
246                                         styles[i].regex);
247                                 styles[i].regex = NULL;
248                         }
249                         styles[i].style = g_strconcat(styledir, "/",
250                                                       styles[i].style, NULL);
251                 }
252                 g_free(styledir);
253         } else {
254                 stylefile = buildfile(stylefile);
255         }
256 }
257
258 void
259 sigchld(int unused)
260 {
261         if (signal(SIGCHLD, sigchld) == SIG_ERR)
262                 die("Can't install SIGCHLD handler");
263         while (0 < waitpid(-1, NULL, WNOHANG));
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 char *
396 geturi(Client *c)
397 {
398         char *uri;
399
400         if (!(uri = (char *)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 gchar *
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 gchar *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, GdkEventKey *e, Client *c)
818 {
819         WebKitHitTestResultContext element;
820         GdkEventButton *eb = (GdkEventButton*)e;
821         int i;
822
823         element = webkit_hit_test_result_get_context(c->mousepos);
824
825         for (i = 0; i < LENGTH(buttons); ++i) {
826                 if (element & buttons[i].target &&
827                     eb->button == buttons[i].button &&
828                     CLEANMASK(eb->state) == CLEANMASK(buttons[i].mask) &&
829                     buttons[i].func) {
830                         buttons[i].func(c, &buttons[i].arg, c->mousepos);
831                         return buttons[i].stopevent;
832                 }
833         }
834
835         return FALSE;
836 }
837
838 gboolean
839 keypress(GtkAccelGroup *group, GObject *obj, guint key, GdkModifierType mods,
840          Client *c)
841 {
842         guint i;
843         gboolean processed = FALSE;
844
845         mods = CLEANMASK(mods);
846         key = gdk_keyval_to_lower(key);
847         updatewinid(c);
848         for (i = 0; i < LENGTH(keys); i++) {
849                 if (key == keys[i].keyval
850                     && mods == keys[i].mod
851                     && keys[i].func) {
852                         keys[i].func(c, &(keys[i].arg));
853                         processed = TRUE;
854                 }
855         }
856
857         return processed;
858 }
859
860 GdkFilterReturn
861 processx(GdkXEvent *e, GdkEvent *event, gpointer d)
862 {
863         Client *c = (Client *)d;
864         XPropertyEvent *ev;
865         Arg a;
866
867         if (((XEvent *)e)->type == PropertyNotify) {
868                 ev = &((XEvent *)e)->xproperty;
869                 if (ev->state == PropertyNewValue) {
870                         if (ev->atom == atoms[AtomFind]) {
871                                 find(c, NULL);
872
873                                 return GDK_FILTER_REMOVE;
874                         } else if (ev->atom == atoms[AtomGo]) {
875                                 a.v = getatom(c, AtomGo);
876                                 loaduri(c, &a);
877
878                                 return GDK_FILTER_REMOVE;
879                         }
880                 }
881         }
882         return GDK_FILTER_CONTINUE;
883 }
884
885 gboolean
886 winevent(GtkWidget *w, GdkEvent *e, Client *c)
887 {
888         switch (e->type) {
889         case GDK_LEAVE_NOTIFY:
890                 c->targeturi = NULL;
891                 updatetitle(c);
892                 break;
893         case GDK_WINDOW_STATE: /* fallthrough */
894                 if (e->window_state.changed_mask ==
895                     GDK_WINDOW_STATE_FULLSCREEN) {
896                         c->fullscreen = e->window_state.new_window_state &
897                                         GDK_WINDOW_STATE_FULLSCREEN;
898                         break;
899                 }
900         default:
901                 return FALSE;
902         }
903
904         return TRUE;
905 }
906
907 void
908 showview(WebKitWebView *v, Client *c)
909 {
910         GdkGeometry hints = { 1, 1 };
911         GdkRGBA bgcolor = { 0 };
912         GdkWindow *gwin;
913
914         c->finder = webkit_web_view_get_find_controller(c->view);
915         if (enableinspector)
916                 c->inspector = webkit_web_view_get_inspector(c->view);
917
918         c->win = createwindow(c);
919
920         gtk_container_add(GTK_CONTAINER(c->win), GTK_WIDGET(c->view));
921         gtk_window_set_geometry_hints(GTK_WINDOW(c->win), NULL, &hints,
922                                       GDK_HINT_MIN_SIZE);
923         gtk_widget_show_all(c->win);
924         gtk_widget_grab_focus(GTK_WIDGET(c->view));
925
926         gwin = gtk_widget_get_window(GTK_WIDGET(c->win));
927         c->xid = gdk_x11_window_get_xid(gwin);
928         updatewinid(c);
929         if (showxid) {
930                 gdk_display_sync(gtk_widget_get_display(c->win));
931                 puts(winid);
932         }
933
934         if (hidebackground)
935                 webkit_web_view_set_background_color(c->view, &bgcolor);
936
937         if (!kioskmode) {
938                 addaccelgroup(c);
939                 gdk_window_set_events(gwin, GDK_ALL_EVENTS_MASK);
940                 gdk_window_add_filter(gwin, processx, c);
941         }
942
943         if (runinfullscreen)
944                 togglefullscreen(c, NULL);
945
946         if (zoomlevel != 1.0)
947                 webkit_web_view_set_zoom_level(c->view, zoomlevel);
948
949         setatom(c, AtomFind, "");
950         setatom(c, AtomUri, "about:blank");
951 }
952
953 GtkWidget *
954 createwindow(Client *c)
955 {
956         GtkWidget *w;
957
958         if (embed) {
959                 w = gtk_plug_new(embed);
960         } else {
961                 w = gtk_window_new(GTK_WINDOW_TOPLEVEL);
962
963                 /* TA:  20091214:  Despite what the GNOME docs say, the ICCCM
964                  * is always correct, so we should still call this function.
965                  * But when doing so, we *must* differentiate between a
966                  * WM_CLASS and a resource on the window.  By convention, the
967                  * window class (WM_CLASS) is capped, while the resource is in
968                  * lowercase.   Both these values come as a pair.
969                  */
970                 gtk_window_set_wmclass(GTK_WINDOW(w), "surf", "Surf");
971
972                 /* TA:  20091214:  And set the role here as well -- so that
973                  * sessions can pick this up.
974                  */
975                 gtk_window_set_role(GTK_WINDOW(w), "Surf");
976
977                 gtk_window_set_default_size(GTK_WINDOW(w), 800, 600);
978         }
979
980         g_signal_connect(G_OBJECT(w), "destroy",
981                          G_CALLBACK(destroywin), c);
982         g_signal_connect(G_OBJECT(w), "leave-notify-event",
983                          G_CALLBACK(winevent), c);
984         g_signal_connect(G_OBJECT(w), "window-state-event",
985                          G_CALLBACK(winevent), c);
986
987         return w;
988 }
989
990 void
991 loadchanged(WebKitWebView *v, WebKitLoadEvent e, Client *c)
992 {
993         switch (e) {
994         case WEBKIT_LOAD_STARTED:
995                 c->tlsflags = G_TLS_CERTIFICATE_VALIDATE_ALL + 1;
996                 break;
997         case WEBKIT_LOAD_REDIRECTED:
998                 setatom(c, AtomUri, geturi(c));
999                 break;
1000         case WEBKIT_LOAD_COMMITTED:
1001                 if (!webkit_web_view_get_tls_info(c->view, NULL,
1002                     &(c->tlsflags)))
1003                         c->tlsflags = G_TLS_CERTIFICATE_VALIDATE_ALL + 1;
1004
1005                 setatom(c, AtomUri, geturi(c));
1006
1007                 if (enablestyle)
1008                         setstyle(c, getstyle(geturi(c)));
1009                 break;
1010         case WEBKIT_LOAD_FINISHED:
1011                 /* Disabled until we write some WebKitWebExtension for
1012                  * manipulating the DOM directly.
1013                 evalscript(c, "document.documentElement.style.overflow = '%s'",
1014                     enablescrollbars ? "auto" : "hidden");
1015                 */
1016                 runscript(c);
1017                 break;
1018         }
1019         updatetitle(c);
1020 }
1021
1022 void
1023 progresschanged(WebKitWebView *v, GParamSpec *ps, Client *c)
1024 {
1025         c->progress = webkit_web_view_get_estimated_load_progress(c->view) *
1026                       100;
1027         updatetitle(c);
1028 }
1029
1030 void
1031 titlechanged(WebKitWebView *view, GParamSpec *ps, Client *c)
1032 {
1033         c->title = webkit_web_view_get_title(c->view);
1034         updatetitle(c);
1035 }
1036
1037 void
1038 mousetargetchanged(WebKitWebView *v, WebKitHitTestResult *h, guint modifiers,
1039     Client *c)
1040 {
1041         WebKitHitTestResultContext hc = webkit_hit_test_result_get_context(h);
1042
1043         /* Keep the hit test to know where is the pointer on the next click */
1044         c->mousepos = h;
1045
1046         if (hc & OnLink)
1047                 c->targeturi = webkit_hit_test_result_get_link_uri(h);
1048         else if (hc & OnImg)
1049                 c->targeturi = webkit_hit_test_result_get_image_uri(h);
1050         else if (hc & OnMedia)
1051                 c->targeturi = webkit_hit_test_result_get_media_uri(h);
1052         else
1053                 c->targeturi = NULL;
1054         updatetitle(c);
1055 }
1056
1057 gboolean
1058 permissionrequested(WebKitWebView *v, WebKitPermissionRequest *r, Client *c)
1059 {
1060         if (WEBKIT_IS_GEOLOCATION_PERMISSION_REQUEST(r)) {
1061                 if (allowgeolocation)
1062                         webkit_permission_request_allow(r);
1063                 else
1064                         webkit_permission_request_deny(r);
1065                 return TRUE;
1066         }
1067
1068         return FALSE;
1069 }
1070
1071 gboolean
1072 decidepolicy(WebKitWebView *v, WebKitPolicyDecision *d,
1073     WebKitPolicyDecisionType dt, Client *c)
1074 {
1075         switch (dt) {
1076         case WEBKIT_POLICY_DECISION_TYPE_NAVIGATION_ACTION:
1077                 decidenavigation(d, c);
1078                 break;
1079         case WEBKIT_POLICY_DECISION_TYPE_NEW_WINDOW_ACTION:
1080                 decidenewwindow(d, c);
1081                 break;
1082         case WEBKIT_POLICY_DECISION_TYPE_RESPONSE:
1083                 decideresource(d, c);
1084                 break;
1085         default:
1086                 webkit_policy_decision_ignore(d);
1087                 break;
1088         }
1089         return TRUE;
1090 }
1091
1092 void
1093 decidenavigation(WebKitPolicyDecision *d, Client *c)
1094 {
1095         WebKitNavigationAction *a =
1096             webkit_navigation_policy_decision_get_navigation_action(
1097             WEBKIT_NAVIGATION_POLICY_DECISION(d));
1098
1099         switch (webkit_navigation_action_get_navigation_type(a)) {
1100         case WEBKIT_NAVIGATION_TYPE_LINK_CLICKED: /* fallthrough */
1101         case WEBKIT_NAVIGATION_TYPE_FORM_SUBMITTED: /* fallthrough */
1102         case WEBKIT_NAVIGATION_TYPE_BACK_FORWARD: /* fallthrough */
1103         case WEBKIT_NAVIGATION_TYPE_RELOAD: /* fallthrough */
1104         case WEBKIT_NAVIGATION_TYPE_FORM_RESUBMITTED: /* fallthrough */
1105         case WEBKIT_NAVIGATION_TYPE_OTHER: /* fallthrough */
1106         default:
1107                 /* Do not navigate to links with a "_blank" target (popup) */
1108                 if (webkit_navigation_policy_decision_get_frame_name(
1109                     WEBKIT_NAVIGATION_POLICY_DECISION(d))) {
1110                         webkit_policy_decision_ignore(d);
1111                 } else {
1112                         /* Filter out navigation to different domain ? */
1113                         /* get action→urirequest, copy and load in new window+view
1114                          * on Ctrl+Click ? */
1115                         webkit_policy_decision_use(d);
1116                 }
1117                 break;
1118         }
1119 }
1120
1121 void
1122 decidenewwindow(WebKitPolicyDecision *d, Client *c)
1123 {
1124         Arg arg;
1125         WebKitNavigationAction *a =
1126             webkit_navigation_policy_decision_get_navigation_action(
1127             WEBKIT_NAVIGATION_POLICY_DECISION(d));
1128
1129
1130         switch (webkit_navigation_action_get_navigation_type(a)) {
1131         case WEBKIT_NAVIGATION_TYPE_LINK_CLICKED: /* fallthrough */
1132         case WEBKIT_NAVIGATION_TYPE_FORM_SUBMITTED: /* fallthrough */
1133         case WEBKIT_NAVIGATION_TYPE_BACK_FORWARD: /* fallthrough */
1134         case WEBKIT_NAVIGATION_TYPE_RELOAD: /* fallthrough */
1135         case WEBKIT_NAVIGATION_TYPE_FORM_RESUBMITTED:
1136                 /* Filter domains here */
1137 /* If the value of “mouse-button” is not 0, then the navigation was triggered by a mouse event.
1138  * test for link clicked but no button ? */
1139                 arg.v = webkit_uri_request_get_uri(
1140                         webkit_navigation_action_get_request(a));
1141                 newwindow(c, &arg, 0);
1142                 break;
1143         case WEBKIT_NAVIGATION_TYPE_OTHER: /* fallthrough */
1144         default:
1145                 break;
1146         }
1147
1148         webkit_policy_decision_ignore(d);
1149 }
1150
1151 void
1152 decideresource(WebKitPolicyDecision *d, Client *c)
1153 {
1154         int i, isascii = 1;
1155         WebKitResponsePolicyDecision *r = WEBKIT_RESPONSE_POLICY_DECISION(d);
1156         WebKitURIResponse *res =
1157             webkit_response_policy_decision_get_response(r);
1158         const gchar *uri = webkit_uri_response_get_uri(res);
1159
1160         if (g_str_has_suffix(uri, "/favicon.ico"))
1161                 webkit_uri_request_set_uri(
1162                     webkit_response_policy_decision_get_request(r),
1163                     "about:blank");
1164
1165         if (!g_str_has_prefix(uri, "http://")
1166             && !g_str_has_prefix(uri, "https://")
1167             && !g_str_has_prefix(uri, "about:")
1168             && !g_str_has_prefix(uri, "file://")
1169             && !g_str_has_prefix(uri, "data:")
1170             && !g_str_has_prefix(uri, "blob:")
1171             && strlen(uri) > 0) {
1172                 for (i = 0; i < strlen(uri); i++) {
1173                         if (!g_ascii_isprint(uri[i])) {
1174                                 isascii = 0;
1175                                 break;
1176                         }
1177                 }
1178                 if (isascii) {
1179                         handleplumb(c, uri);
1180                         webkit_policy_decision_ignore(d);
1181                 }
1182         }
1183
1184         if (webkit_response_policy_decision_is_mime_type_supported(r)) {
1185                 webkit_policy_decision_use(d);
1186         } else {
1187                 webkit_policy_decision_ignore(d);
1188                 download(c, res);
1189         }
1190 }
1191
1192 void
1193 downloadstarted(WebKitWebContext *wc, WebKitDownload *d, Client *c)
1194 {
1195         g_signal_connect(G_OBJECT(d), "notify::response",
1196                          G_CALLBACK(responsereceived), c);
1197 }
1198
1199 void
1200 responsereceived(WebKitDownload *d, GParamSpec *ps, Client *c)
1201 {
1202         download(c, webkit_download_get_response(d));
1203         webkit_download_cancel(d);
1204 }
1205
1206 void
1207 download(Client *c, WebKitURIResponse *r)
1208 {
1209         Arg a = (Arg)DOWNLOAD(webkit_uri_response_get_uri(r), geturi(c));
1210         spawn(c, &a);
1211 }
1212
1213 void
1214 closeview(WebKitWebView *v, Client *c)
1215 {
1216         gtk_widget_destroy(c->win);
1217 }
1218
1219 void
1220 destroywin(GtkWidget* w, Client *c)
1221 {
1222         destroyclient(c);
1223         if (!clients)
1224                 gtk_main_quit();
1225 }
1226
1227 void
1228 pasteuri(GtkClipboard *clipboard, const char *text, gpointer d)
1229 {
1230         Arg a = {.v = text };
1231         if (!text)
1232                 loaduri((Client *) d, &a);
1233 }
1234
1235 void
1236 reload(Client *c, const Arg *a)
1237 {
1238         gboolean nocache = *(gboolean *)a;
1239         if (nocache)
1240                 webkit_web_view_reload_bypass_cache(c->view);
1241         else
1242                 webkit_web_view_reload(c->view);
1243 }
1244
1245 void
1246 print(Client *c, const Arg *a)
1247 {
1248         webkit_print_operation_run_dialog(webkit_print_operation_new(c->view),
1249                                           GTK_WINDOW(c->win));
1250 }
1251
1252 void
1253 clipboard(Client *c, const Arg *a)
1254 {
1255         if (a->b) { /* load clipboard uri */
1256                 gtk_clipboard_request_text(gtk_clipboard_get(
1257                                            GDK_SELECTION_PRIMARY),
1258                                            pasteuri, c);
1259         } else { /* copy uri */
1260                 gtk_clipboard_set_text(gtk_clipboard_get(
1261                                        GDK_SELECTION_PRIMARY), c->targeturi
1262                                        ? c->targeturi : geturi(c), -1);
1263         }
1264 }
1265
1266 void
1267 zoom(Client *c, const Arg *a)
1268 {
1269         if (a->i > 0)
1270                 webkit_web_view_set_zoom_level(c->view, zoomlevel + 0.1);
1271         else if (a->i < 0)
1272                 webkit_web_view_set_zoom_level(c->view, zoomlevel - 0.1);
1273         else
1274                 webkit_web_view_set_zoom_level(c->view, 1.0);
1275
1276         zoomlevel = webkit_web_view_get_zoom_level(c->view);
1277 }
1278
1279 void
1280 scroll_v(Client *c, const Arg *a)
1281 {
1282         evalscript(c, "window.scrollBy(0, %d * (window.innerHeight / 100))",
1283                    a->i);
1284 }
1285
1286 void
1287 scroll_h(Client *c, const Arg *a)
1288 {
1289         evalscript(c, "window.scrollBy(%d * (window.innerWidth / 100), 0)",
1290                    a->i);
1291 }
1292
1293 void
1294 navigate(Client *c, const Arg *a)
1295 {
1296         if (a->i < 0)
1297                 webkit_web_view_go_back(c->view);
1298         else if (a->i > 0)
1299                 webkit_web_view_go_forward(c->view);
1300 }
1301
1302 void
1303 stop(Client *c, const Arg *a)
1304 {
1305         webkit_web_view_stop_loading(c->view);
1306 }
1307
1308 void
1309 toggle(Client *c, const Arg *a)
1310 {
1311         WebKitSettings *s = webkit_web_view_get_settings(c->view);
1312
1313         switch ((unsigned int)a->i) {
1314         case CaretBrowsing:
1315                 enablecaretbrowsing = !enablecaretbrowsing;
1316                 webkit_settings_set_enable_caret_browsing(s,
1317                     enablecaretbrowsing);
1318                 updatetitle(c);
1319                 return; /* do not reload */
1320                 break;
1321         case FrameFlattening:
1322                 enableframeflattening = !enableframeflattening;
1323                 webkit_settings_set_enable_frame_flattening(s,
1324                     enableframeflattening);
1325                 break;
1326         case Geolocation:
1327                 allowgeolocation = !allowgeolocation;
1328                 break;
1329         case JavaScript:
1330                 enablescripts = !enablescripts;
1331                 webkit_settings_set_enable_javascript(s, enablescripts);
1332                 break;
1333         case LoadImages:
1334                 loadimages = !loadimages;
1335                 webkit_settings_set_auto_load_images(s, loadimages);
1336                 break;
1337         case Plugins:
1338                 enableplugins = !enableplugins;
1339                 webkit_settings_set_enable_plugins(s, enableplugins);
1340                 break;
1341         case ScrollBars:
1342                 /* Disabled until we write some WebKitWebExtension for
1343                  * manipulating the DOM directly.
1344                 enablescrollbars = !enablescrollbars;
1345                 evalscript(c, "document.documentElement.style.overflow = '%s'",
1346                     enablescrollbars ? "auto" : "hidden");
1347                 */
1348                 return; /* do not reload */
1349                 break;
1350         default:
1351                 break;
1352         }
1353         reload(c, a);
1354 }
1355
1356 void
1357 togglefullscreen(Client *c, const Arg *a)
1358 {
1359         /* toggling value is handled in winevent() */
1360         if (c->fullscreen)
1361                 gtk_window_unfullscreen(GTK_WINDOW(c->win));
1362         else
1363                 gtk_window_fullscreen(GTK_WINDOW(c->win));
1364 }
1365
1366 void
1367 togglecookiepolicy(Client *c, const Arg *a)
1368 {
1369         ++cookiepolicy;
1370         cookiepolicy %= strlen(cookiepolicies);
1371
1372         webkit_cookie_manager_set_accept_policy(
1373             webkit_web_context_get_cookie_manager(
1374             webkit_web_view_get_context(c->view)),
1375             cookiepolicy_get());
1376
1377         updatetitle(c);
1378         /* Do not reload. */
1379 }
1380
1381 void
1382 togglestyle(Client *c, const Arg *a)
1383 {
1384         enablestyle = !enablestyle;
1385         setstyle(c, enablestyle ? getstyle(geturi(c)) : "");
1386
1387         updatetitle(c);
1388 }
1389
1390 void
1391 toggleinspector(Client *c, const Arg *a)
1392 {
1393         if (enableinspector) {
1394                 if (webkit_web_inspector_is_attached(c->inspector))
1395                         webkit_web_inspector_close(c->inspector);
1396                 else
1397                         webkit_web_inspector_show(c->inspector);
1398         }
1399 }
1400
1401 void
1402 find(Client *c, const Arg *a)
1403 {
1404         const char *s, *f;
1405
1406         if (a && a->i) {
1407                 if (a->i > 0)
1408                         webkit_find_controller_search_next(c->finder);
1409                 else
1410                         webkit_find_controller_search_previous(c->finder);
1411         } else {
1412                 s = getatom(c, AtomFind);
1413                 f = webkit_find_controller_get_search_text(c->finder);
1414
1415                 if (g_strcmp0(f, s) == 0) /* reset search */
1416                         webkit_find_controller_search(c->finder, "", findopts,
1417                                                       G_MAXUINT);
1418
1419                 webkit_find_controller_search(c->finder, s, findopts,
1420                                               G_MAXUINT);
1421
1422                 if (strcmp(s, "") == 0)
1423                         webkit_find_controller_search_finish(c->finder);
1424         }
1425 }
1426
1427 void
1428 clicknavigate(Client *c, const Arg *a, WebKitHitTestResult *h)
1429 {
1430         navigate(c, a);
1431 }
1432
1433 void
1434 clicknewwindow(Client *c, const Arg *a, WebKitHitTestResult *h)
1435 {
1436         Arg arg;
1437
1438         arg.v = webkit_hit_test_result_get_link_uri(h);
1439         newwindow(c, &arg, a->b);
1440 }
1441
1442 void
1443 clickexternplayer(Client *c, const Arg *a, WebKitHitTestResult *h)
1444 {
1445         Arg arg;
1446
1447         if (webkit_hit_test_result_get_context(h) & OnMedia) {
1448                 arg = (Arg)VIDEOPLAY(webkit_hit_test_result_get_media_uri(h));
1449                 spawn(c, &arg);
1450         }
1451 }
1452
1453 int
1454 main(int argc, char *argv[])
1455 {
1456         Arg arg;
1457         Client *c;
1458
1459         memset(&arg, 0, sizeof(arg));
1460
1461         /* command line args */
1462         ARGBEGIN {
1463         case 'a':
1464                 cookiepolicies = EARGF(usage());
1465                 break;
1466         case 'b':
1467                 enablescrollbars = 0;
1468                 break;
1469         case 'B':
1470                 enablescrollbars = 1;
1471                 break;
1472         case 'c':
1473                 cookiefile = EARGF(usage());
1474                 break;
1475         case 'd':
1476                 enablecache = 0;
1477                 break;
1478         case 'D':
1479                 enablecache = 1;
1480                 break;
1481         case 'e':
1482                 embed = strtol(EARGF(usage()), NULL, 0);
1483                 break;
1484         case 'f':
1485                 runinfullscreen = 0;
1486                 break;
1487         case 'F':
1488                 runinfullscreen = 1;
1489                 break;
1490         case 'g':
1491                 allowgeolocation = 0;
1492                 break;
1493         case 'G':
1494                 allowgeolocation = 1;
1495                 break;
1496         case 'i':
1497                 loadimages = 0;
1498                 break;
1499         case 'I':
1500                 loadimages = 1;
1501                 break;
1502         case 'k':
1503                 kioskmode = 0;
1504                 break;
1505         case 'K':
1506                 kioskmode = 1;
1507                 break;
1508         case 'm':
1509                 enablestyle = 0;
1510                 break;
1511         case 'M':
1512                 enablestyle = 1;
1513                 break;
1514         case 'n':
1515                 enableinspector = 0;
1516                 break;
1517         case 'N':
1518                 enableinspector = 1;
1519                 break;
1520         case 'p':
1521                 enableplugins = 0;
1522                 break;
1523         case 'P':
1524                 enableplugins = 1;
1525                 break;
1526         case 'r':
1527                 scriptfile = EARGF(usage());
1528                 break;
1529         case 's':
1530                 enablescripts = 0;
1531                 break;
1532         case 'S':
1533                 enablescripts = 1;
1534                 break;
1535         case 't':
1536                 stylefile = EARGF(usage());
1537                 break;
1538         case 'u':
1539                 useragent = EARGF(usage());
1540                 break;
1541         case 'v':
1542                 die("surf-"VERSION", ©2009-2015 surf engineers, "
1543                     "see LICENSE for details\n");
1544         case 'x':
1545                 showxid = TRUE;
1546                 break;
1547         case 'z':
1548                 zoomlevel = strtof(EARGF(usage()), NULL);
1549                 break;
1550         default:
1551                 usage();
1552         } ARGEND;
1553         if (argc > 0)
1554                 arg.v = argv[0];
1555
1556         setup();
1557         c = newclient(NULL);
1558         showview(NULL, c);
1559
1560         if (arg.v)
1561                 loaduri(clients, &arg);
1562         else
1563                 updatetitle(c);
1564
1565         gtk_main();
1566         cleanup();
1567
1568         return EXIT_SUCCESS;
1569 }