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