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