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