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