Adapt clipboard()
[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 *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 *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 *style)
674 {
675         WebKitWebSettings *settings = webkit_web_view_get_settings(c->view);
676
677         g_object_set(G_OBJECT(settings), "user-stylesheet-uri", style, NULL);
678 }
679
680 void
681 handleplumb(Client *c, const gchar *uri)
682 {
683         Arg arg;
684
685         arg = (Arg)PLUMB(uri);
686         spawn(c, &arg);
687 }
688
689 void
690 downloadstarted(WebKitWebContext *wc, WebKitDownload *d, Client *c)
691 {
692         g_signal_connect(G_OBJECT(d), "notify::response",
693             G_CALLBACK(responsereceived), c);
694 }
695
696 void
697 responsereceived(WebKitDownload *d, GParamSpec *ps, Client *c)
698 {
699         download(c, webkit_download_get_response(d));
700         webkit_download_cancel(d);
701 }
702
703 void
704 download(Client *c, WebKitURIResponse *r)
705 {
706         Arg a;
707
708         a = (Arg)DOWNLOAD(webkit_uri_response_get_uri(r), geturi(c));
709         spawn(c, &a);
710 }
711
712 void
713 inspector(Client *c, const Arg *arg)
714 {
715         if (enableinspector) {
716                 if (c->isinspecting)
717                         webkit_web_inspector_close(c->inspector);
718                 else
719                         webkit_web_inspector_show(c->inspector);
720         }
721 }
722
723 WebKitWebView *
724 inspector_new(WebKitWebInspector *i, WebKitWebView *v, Client *c)
725 {
726         return WEBKIT_WEB_VIEW(webkit_web_view_new());
727 }
728
729 gboolean
730 inspector_show(WebKitWebInspector *i, Client *c)
731 {
732         WebKitWebView *w;
733
734         if (c->isinspecting)
735                 return false;
736
737         w = webkit_web_inspector_get_web_view(i);
738         gtk_paned_pack2(GTK_PANED(c->pane), GTK_WIDGET(w), TRUE, TRUE);
739         gtk_widget_show(GTK_WIDGET(w));
740         c->isinspecting = true;
741
742         return true;
743 }
744
745 gboolean
746 inspector_close(WebKitWebInspector *i, Client *c)
747 {
748         GtkWidget *w;
749
750         if (!c->isinspecting)
751                 return false;
752
753         w = GTK_WIDGET(webkit_web_inspector_get_web_view(i));
754         gtk_widget_hide(w);
755         gtk_widget_destroy(w);
756         c->isinspecting = false;
757
758         return true;
759 }
760
761 void
762 inspector_finished(WebKitWebInspector *i, Client *c)
763 {
764         g_free(c->inspector);
765 }
766
767 gboolean
768 keypress(GtkAccelGroup *group, GObject *obj, guint key, GdkModifierType mods,
769          Client *c)
770 {
771         guint i;
772         gboolean processed = FALSE;
773
774         mods = CLEANMASK(mods);
775         key = gdk_keyval_to_lower(key);
776         updatewinid(c);
777         for (i = 0; i < LENGTH(keys); i++) {
778                 if (key == keys[i].keyval
779                     && mods == keys[i].mod
780                     && keys[i].func) {
781                         keys[i].func(c, &(keys[i].arg));
782                         processed = TRUE;
783                 }
784         }
785
786         return processed;
787 }
788
789 void
790 mousetargetchanged(WebKitWebView *v, WebKitHitTestResult *h, guint modifiers,
791     Client *c)
792 {
793         WebKitHitTestResultContext hc;
794
795         /* Keep the hit test to know where is the pointer on the next click */
796         c->mousepos = h;
797
798         hc = webkit_hit_test_result_get_context(h);
799
800         if (hc & OnLink)
801                 c->targeturi = webkit_hit_test_result_get_link_uri(h);
802         else if (hc & OnImg)
803                 c->targeturi = webkit_hit_test_result_get_image_uri(h);
804         else if (hc & OnMedia)
805                 c->targeturi = webkit_hit_test_result_get_media_uri(h);
806         else
807                 c->targeturi = NULL;
808         updatetitle(c);
809 }
810
811 void
812 loadchanged(WebKitWebView *v, WebKitLoadEvent e, Client *c)
813 {
814         switch (e) {
815         case WEBKIT_LOAD_STARTED:
816                 c->tlsflags = G_TLS_CERTIFICATE_VALIDATE_ALL + 1;
817                 break;
818         case WEBKIT_LOAD_REDIRECTED:
819                 setatom(c, AtomUri, geturi(c));
820                 break;
821         case WEBKIT_LOAD_COMMITTED:
822                 if (!webkit_web_view_get_tls_info(c->view, NULL, &(c->tlsflags)))
823                         c->tlsflags = G_TLS_CERTIFICATE_VALIDATE_ALL + 1;
824
825                 setatom(c, AtomUri, geturi(c));
826
827                 if (enablestyle)
828                         setstyle(c, getstyle(geturi(c)));
829                 break;
830         case WEBKIT_LOAD_FINISHED:
831                 /* Disabled until we write some WebKitWebExtension for
832                  * manipulating the DOM directly.
833                 evalscript(c, "document.documentElement.style.overflow = '%s'",
834                     enablescrollbars ? "auto" : "hidden");
835                 */
836                 runscript(c);
837                 break;
838         }
839         updatetitle(c);
840 }
841
842 void
843 loaduri(Client *c, const Arg *arg)
844 {
845         char *u = NULL, *rp;
846         const char *uri = (char *)arg->v;
847         Arg a = { .b = FALSE };
848         struct stat st;
849
850         if (strcmp(uri, "") == 0)
851                 return;
852
853         /* In case it's a file path. */
854         if (stat(uri, &st) == 0) {
855                 rp = realpath(uri, NULL);
856                 u = g_strdup_printf("file://%s", rp);
857                 free(rp);
858         } else {
859                 u = g_strrstr(uri, "://") ? g_strdup(uri)
860                     : g_strdup_printf("http://%s", uri);
861         }
862
863         setatom(c, AtomUri, uri);
864
865         /* prevents endless loop */
866         if (strcmp(u, geturi(c)) == 0) {
867                 reload(c, &a);
868         } else {
869                 webkit_web_view_load_uri(c->view, u);
870                 c->progress = 0;
871                 c->title = copystr(&c->title, u);
872                 updatetitle(c);
873         }
874         g_free(u);
875 }
876
877 void
878 navigate(Client *c, const Arg *arg)
879 {
880         int steps = *(int *)arg;
881         webkit_web_view_go_back_or_forward(c->view, steps);
882 }
883
884 Client *
885 newclient(Client *rc)
886 {
887         Client *c;
888         gdouble dpi;
889
890         if (!(c = calloc(1, sizeof(Client))))
891                 die("Cannot malloc!\n");
892
893         c->title = NULL;
894         c->progress = 100;
895
896         c->next = clients;
897         clients = c;
898
899         c->view = newview(c, rc ? rc->view : NULL);
900         c->tlsflags = G_TLS_CERTIFICATE_VALIDATE_ALL + 1;
901
902         return c;
903 }
904
905 WebKitWebView *
906 newview(Client *c, WebKitWebView *rv)
907 {
908         WebKitWebView *v;
909         WebKitSettings *settings;
910         WebKitUserContentManager *contentmanager;
911         WebKitWebContext *context;
912         char *ua;
913
914         /* Webview */
915         if (rv) {
916                 v = WEBKIT_WEB_VIEW(
917                     webkit_web_view_new_with_related_view(rv));
918         } else {
919                 settings = webkit_settings_new_with_settings(
920                     "auto-load-images", loadimages,
921                     "default-font-size", defaultfontsize,
922                     "enable-caret-browsing", enablecaretbrowsing,
923                     "enable-developer-extras", enableinspector,
924                     "enable-dns-prefetching", enablednsprefetching,
925                     "enable-frame-flattening", enableframeflattening,
926                     "enable-html5-database", enablecache,
927                     "enable-html5-local-storage", enablecache,
928                     "enable-javascript", enablescripts,
929                     "enable-plugins", enableplugins,
930                     NULL);
931                 if (!(ua = getenv("SURF_USERAGENT")))
932                         ua = useragent;
933                 webkit_settings_set_user_agent(settings, ua);
934                 /* Have a look at http://webkitgtk.org/reference/webkit2gtk/stable/WebKitSettings.html
935                  * for more interesting settings */
936
937                 contentmanager = webkit_user_content_manager_new();
938
939                 context = webkit_web_context_new_with_website_data_manager(
940                     webkit_website_data_manager_new(
941                     "base-cache-directory", cachedir,
942                     "base-data-directory", cachedir,
943                     NULL));
944
945                 /* rendering process model, can be a shared unique one or one for each
946                  * view */
947                 webkit_web_context_set_process_model(context,
948                     WEBKIT_PROCESS_MODEL_MULTIPLE_SECONDARY_PROCESSES);
949                 /* ssl */
950                 webkit_web_context_set_tls_errors_policy(context, strictssl ?
951                     WEBKIT_TLS_ERRORS_POLICY_FAIL : WEBKIT_TLS_ERRORS_POLICY_IGNORE);
952                 /* disk cache */
953                 webkit_web_context_set_cache_model(context, enablecache ?
954                     WEBKIT_CACHE_MODEL_WEB_BROWSER : WEBKIT_CACHE_MODEL_DOCUMENT_VIEWER);
955
956                 /* Currently only works with text file to be compatible with curl */
957                 webkit_cookie_manager_set_persistent_storage(
958                     webkit_web_context_get_cookie_manager(context), cookiefile,
959                     WEBKIT_COOKIE_PERSISTENT_STORAGE_TEXT);
960                 /* cookie policy */
961                 webkit_cookie_manager_set_accept_policy(
962                     webkit_web_context_get_cookie_manager(context),
963                     cookiepolicy_get());
964
965                 g_signal_connect(G_OBJECT(context), "download-started",
966                     G_CALLBACK(downloadstarted), c);
967
968                 v = g_object_new(WEBKIT_TYPE_WEB_VIEW,
969                     "settings", settings,
970                     "user-content-manager", contentmanager,
971                     "web-context", context,
972                     NULL);
973         }
974
975         g_signal_connect(G_OBJECT(v),
976                          "notify::title",
977                          G_CALLBACK(titlechanged), c);
978         g_signal_connect(G_OBJECT(v),
979                          "mouse-target-changed",
980                          G_CALLBACK(mousetargetchanged), c);
981         g_signal_connect(G_OBJECT(v),
982                          "permission-request",
983                          G_CALLBACK(permissionrequested), c);
984         g_signal_connect(G_OBJECT(v),
985                          "create",
986                          G_CALLBACK(createview), c);
987         g_signal_connect(G_OBJECT(v), "ready-to-show",
988                          G_CALLBACK(showview), c);
989         g_signal_connect(G_OBJECT(v),
990                          "decide-policy",
991                          G_CALLBACK(decidepolicy), c);
992         g_signal_connect(G_OBJECT(v),
993                          "load-changed",
994                          G_CALLBACK(loadchanged), c);
995         g_signal_connect(G_OBJECT(v),
996                          "notify::estimated-load-progress",
997                          G_CALLBACK(progresschanged), c);
998         g_signal_connect(G_OBJECT(v),
999                          "button-release-event",
1000                          G_CALLBACK(buttonreleased), c);
1001         g_signal_connect(G_OBJECT(v), "close",
1002                         G_CALLBACK(closeview), c);
1003
1004         return v;
1005 }
1006
1007 void
1008 showview(WebKitWebView *v, Client *c)
1009 {
1010         GdkGeometry hints = { 1, 1 };
1011         GdkRGBA bgcolor = { 0 };
1012         GdkWindow *gwin;
1013
1014         c->win = createwindow(c);
1015
1016         if (!kioskmode)
1017                 addaccelgroup(c);
1018
1019         /* Arranging */
1020         gtk_container_add(GTK_CONTAINER(c->win), GTK_WIDGET(c->view));
1021
1022         /* Setup */
1023         gtk_widget_grab_focus(GTK_WIDGET(c->view));
1024         gtk_widget_show(GTK_WIDGET(c->view));
1025         gtk_widget_show(c->win);
1026         gwin = gtk_widget_get_window(GTK_WIDGET(c->win));
1027         c->xid = gdk_x11_window_get_xid(gwin);
1028         gtk_window_set_geometry_hints(GTK_WINDOW(c->win), NULL, &hints,
1029                                       GDK_HINT_MIN_SIZE);
1030         gdk_window_set_events(gwin, GDK_ALL_EVENTS_MASK);
1031         gdk_window_add_filter(gwin, processx, c);
1032
1033         /* This might conflict with _zoomto96dpi_. */
1034         if (zoomlevel != 1.0)
1035                 webkit_web_view_set_zoom_level(c->view, zoomlevel);
1036
1037         if (runinfullscreen)
1038                 togglefullscreen(c, NULL);
1039
1040         setatom(c, AtomFind, "");
1041         setatom(c, AtomUri, "about:blank");
1042         if (hidebackground)
1043                 webkit_web_view_set_background_color(c->view, &bgcolor);
1044
1045         if (showxid) {
1046                 gdk_display_sync(gtk_widget_get_display(c->win));
1047                 printf("%lu\n", c->xid);
1048                 fflush(NULL);
1049                 if (fclose(stdout) != 0) {
1050                         die("Error closing stdout");
1051                 }
1052         }
1053 }
1054
1055 void
1056 newwindow(Client *c, const Arg *arg, gboolean noembed)
1057 {
1058         guint i = 0;
1059         const char *cmd[18], *uri;
1060         const Arg a = { .v = (void *)cmd };
1061         char tmp[64];
1062
1063         cmd[i++] = argv0;
1064         cmd[i++] = "-a";
1065         cmd[i++] = cookiepolicies;
1066         if (!enablescrollbars)
1067                 cmd[i++] = "-b";
1068         if (embed && !noembed) {
1069                 cmd[i++] = "-e";
1070                 snprintf(tmp, LENGTH(tmp), "%u", (int)embed);
1071                 cmd[i++] = tmp;
1072         }
1073         if (!allowgeolocation)
1074                 cmd[i++] = "-g";
1075         if (!loadimages)
1076                 cmd[i++] = "-i";
1077         if (kioskmode)
1078                 cmd[i++] = "-k";
1079         if (!enableplugins)
1080                 cmd[i++] = "-p";
1081         if (!enablescripts)
1082                 cmd[i++] = "-s";
1083         if (showxid)
1084                 cmd[i++] = "-x";
1085         if (enablediskcache)
1086                 cmd[i++] = "-D";
1087         cmd[i++] = "-c";
1088         cmd[i++] = cookiefile;
1089         cmd[i++] = "--";
1090         uri = arg->v ? (char *)arg->v : c->linkhover;
1091         if (uri)
1092                 cmd[i++] = uri;
1093         cmd[i++] = NULL;
1094         spawn(NULL, &a);
1095 }
1096
1097 GtkWidget *
1098 createwindow(Client *c)
1099 {
1100         GtkWidget *w;
1101
1102         if (embed) {
1103                 w = gtk_plug_new(embed);
1104         } else {
1105                 w = gtk_window_new(GTK_WINDOW_TOPLEVEL);
1106
1107                 /* TA:  20091214:  Despite what the GNOME docs say, the ICCCM
1108                  * is always correct, so we should still call this function.
1109                  * But when doing so, we *must* differentiate between a
1110                  * WM_CLASS and a resource on the window.  By convention, the
1111                  * window class (WM_CLASS) is capped, while the resource is in
1112                  * lowercase.   Both these values come as a pair.
1113                  */
1114                 gtk_window_set_wmclass(GTK_WINDOW(w), "surf", "Surf");
1115
1116                 /* TA:  20091214:  And set the role here as well -- so that
1117                  * sessions can pick this up.
1118                  */
1119                 gtk_window_set_role(GTK_WINDOW(w), "Surf");
1120
1121                 gtk_window_set_default_size(GTK_WINDOW(w), 800, 600);
1122         }
1123
1124         g_signal_connect(G_OBJECT(w), "destroy",
1125             G_CALLBACK(destroywin), c);
1126         g_signal_connect(G_OBJECT(w), "leave-notify-event",
1127             G_CALLBACK(winevent), c);
1128         g_signal_connect(G_OBJECT(w), "window-state-event",
1129             G_CALLBACK(winevent), c);
1130
1131         return w;
1132 }
1133
1134 void
1135 pasteuri(GtkClipboard *clipboard, const char *text, gpointer d)
1136 {
1137         Arg arg = {.v = text };
1138         if (text != NULL)
1139                 loaduri((Client *) d, &arg);
1140 }
1141
1142 void
1143 print(Client *c, const Arg *arg)
1144 {
1145         webkit_web_frame_print(webkit_web_view_get_main_frame(c->view));
1146 }
1147
1148 GdkFilterReturn
1149 processx(GdkXEvent *e, GdkEvent *event, gpointer d)
1150 {
1151         Client *c = (Client *)d;
1152         XPropertyEvent *ev;
1153         Arg arg;
1154
1155         if (((XEvent *)e)->type == PropertyNotify) {
1156                 ev = &((XEvent *)e)->xproperty;
1157                 if (ev->state == PropertyNewValue) {
1158                         if (ev->atom == atoms[AtomFind]) {
1159                                 arg.b = TRUE;
1160                                 find(c, &arg);
1161
1162                                 return GDK_FILTER_REMOVE;
1163                         } else if (ev->atom == atoms[AtomGo]) {
1164                                 arg.v = getatom(c, AtomGo);
1165                                 loaduri(c, &arg);
1166
1167                                 return GDK_FILTER_REMOVE;
1168                         }
1169                 }
1170         }
1171         return GDK_FILTER_CONTINUE;
1172 }
1173
1174 void
1175 progresschanged(WebKitWebView *v, GParamSpec *ps, Client *c)
1176 {
1177         c->progress = webkit_web_view_get_estimated_load_progress(c->view) *
1178             100;
1179         updatetitle(c);
1180 }
1181
1182 void
1183 linkopen(Client *c, const Arg *arg)
1184 {
1185         newwindow(NULL, arg, 1);
1186 }
1187
1188 void
1189 linkopenembed(Client *c, const Arg *arg)
1190 {
1191         newwindow(NULL, arg, 0);
1192 }
1193
1194 void
1195 reload(Client *c, const Arg *arg)
1196 {
1197         gboolean nocache = *(gboolean *)arg;
1198         if (nocache)
1199                 webkit_web_view_reload_bypass_cache(c->view);
1200         else
1201                 webkit_web_view_reload(c->view);
1202 }
1203
1204 void
1205 scroll_h(Client *c, const Arg *arg)
1206 {
1207         scroll(gtk_scrolled_window_get_hadjustment(
1208                GTK_SCROLLED_WINDOW(c->scroll)), arg);
1209 }
1210
1211 void
1212 scroll_v(Client *c, const Arg *arg)
1213 {
1214         scroll(gtk_scrolled_window_get_vadjustment(
1215                GTK_SCROLLED_WINDOW(c->scroll)), arg);
1216 }
1217
1218 void
1219 scroll(GtkAdjustment *a, const Arg *arg)
1220 {
1221         gdouble v;
1222
1223         v = gtk_adjustment_get_value(a);
1224         switch (arg->i) {
1225         case +10000:
1226         case -10000:
1227                 v += gtk_adjustment_get_page_increment(a) * (arg->i / 10000);
1228                 break;
1229         case +20000:
1230         case -20000:
1231         default:
1232                 v += gtk_adjustment_get_step_increment(a) * arg->i;
1233         }
1234
1235         v = MAX(v, 0.0);
1236         v = MIN(v, gtk_adjustment_get_upper(a) -
1237                 gtk_adjustment_get_page_size(a));
1238         gtk_adjustment_set_value(a, v);
1239 }
1240
1241 void
1242 setatom(Client *c, int a, const char *v)
1243 {
1244         XSync(dpy, False);
1245         XChangeProperty(dpy, c->xid,
1246                         atoms[a], XA_STRING, 8, PropModeReplace,
1247                         (unsigned char *)v, strlen(v) + 1);
1248 }
1249
1250 void
1251 setup(void)
1252 {
1253         int i;
1254         char *styledirfile, *stylepath;
1255         WebKitWebContext *context;
1256         GError *error = NULL;
1257
1258         /* clean up any zombies immediately */
1259         sigchld(0);
1260         gtk_init(NULL, NULL);
1261
1262         dpy = GDK_DISPLAY_XDISPLAY(gdk_display_get_default());
1263
1264         /* atoms */
1265         atoms[AtomFind] = XInternAtom(dpy, "_SURF_FIND", False);
1266         atoms[AtomGo] = XInternAtom(dpy, "_SURF_GO", False);
1267         atoms[AtomUri] = XInternAtom(dpy, "_SURF_URI", False);
1268
1269         /* dirs and files */
1270         cookiefile = buildfile(cookiefile);
1271         scriptfile = buildfile(scriptfile);
1272         cachedir   = buildpath(cachedir);
1273         if (stylefile == NULL) {
1274                 styledir = buildpath(styledir);
1275                 for (i = 0; i < LENGTH(styles); i++) {
1276                         if (regcomp(&(styles[i].re), styles[i].regex,
1277                             REG_EXTENDED)) {
1278                                 fprintf(stderr,
1279                                         "Could not compile regex: %s\n",
1280                                         styles[i].regex);
1281                                 styles[i].regex = NULL;
1282                         }
1283                         styledirfile    = g_strconcat(styledir, "/",
1284                                                       styles[i].style, NULL);
1285                         stylepath       = buildfile(styledirfile);
1286                         styles[i].style = g_strconcat("file://", stylepath,
1287                                                       NULL);
1288                         g_free(styledirfile);
1289                         g_free(stylepath);
1290                 }
1291                 g_free(styledir);
1292         } else {
1293                 stylepath = buildfile(stylefile);
1294                 stylefile = g_strconcat("file://", stylepath, NULL);
1295                 g_free(stylepath);
1296         }
1297 }
1298
1299 void
1300 sigchld(int unused)
1301 {
1302         if (signal(SIGCHLD, sigchld) == SIG_ERR)
1303                 die("Can't install SIGCHLD handler");
1304         while (0 < waitpid(-1, NULL, WNOHANG));
1305 }
1306
1307 void
1308 spawn(Client *c, const Arg *arg)
1309 {
1310         if (fork() == 0) {
1311                 if (dpy)
1312                         close(ConnectionNumber(dpy));
1313                 setsid();
1314                 execvp(((char **)arg->v)[0], (char **)arg->v);
1315                 fprintf(stderr, "surf: execvp %s", ((char **)arg->v)[0]);
1316                 perror(" failed");
1317                 exit(0);
1318         }
1319 }
1320
1321 void
1322 stop(Client *c, const Arg *arg)
1323 {
1324         webkit_web_view_stop_loading(c->view);
1325 }
1326
1327 void
1328 titlechanged(WebKitWebView *view, GParamSpec *ps, Client *c)
1329 {
1330         c->title = webkit_web_view_get_title(c->view);
1331         updatetitle(c);
1332 }
1333
1334 gboolean
1335 winevent(GtkWidget *w, GdkEvent *e, Client *c)
1336 {
1337         switch (e->type) {
1338         case GDK_LEAVE_NOTIFY:
1339                 c->targeturi = NULL;
1340                 updatetitle(c);
1341                 break;
1342         case GDK_WINDOW_STATE: /* fallthrough */
1343                 if (e->window_state.changed_mask ==
1344                     GDK_WINDOW_STATE_FULLSCREEN) {
1345                         c->fullscreen = e->window_state.new_window_state &
1346                             GDK_WINDOW_STATE_FULLSCREEN;
1347                         break;
1348                 }
1349         default:
1350                 return FALSE;
1351         }
1352
1353         return TRUE;
1354 }
1355
1356 void
1357 toggle(Client *c, const Arg *arg)
1358 {
1359         WebKitWebSettings *settings;
1360         char *name = (char *)arg->v;
1361         gboolean value;
1362         Arg a = { .b = FALSE };
1363
1364         settings = webkit_web_view_get_settings(c->view);
1365         g_object_get(G_OBJECT(settings), name, &value, NULL);
1366         g_object_set(G_OBJECT(settings), name, !value, NULL);
1367
1368         reload(c, &a);
1369 }
1370
1371 void
1372 togglecookiepolicy(Client *c, const Arg *arg)
1373 {
1374         ++cookiepolicy;
1375         cookiepolicy %= strlen(cookiepolicies);
1376
1377         webkit_cookie_manager_set_accept_policy(
1378             webkit_web_context_get_cookie_manager(
1379             webkit_web_view_get_context(c->view)),
1380             cookiepolicy_get());
1381
1382         updatetitle(c);
1383         /* Do not reload. */
1384 }
1385
1386 void
1387 togglegeolocation(Client *c, const Arg *arg)
1388 {
1389         Arg a = { .b = FALSE };
1390
1391         allowgeolocation ^= 1;
1392         reload(c, &a);
1393 }
1394
1395 void
1396 twitch(Client *c, const Arg *arg)
1397 {
1398         GtkAdjustment *a;
1399         gdouble v;
1400
1401         a = gtk_scrolled_window_get_vadjustment(GTK_SCROLLED_WINDOW(
1402                                                 c->scroll));
1403
1404         v = gtk_adjustment_get_value(a);
1405
1406         v += arg->i;
1407
1408         v = MAX(v, 0.0);
1409         v = MIN(v, gtk_adjustment_get_upper(a) -
1410                 gtk_adjustment_get_page_size(a));
1411         gtk_adjustment_set_value(a, v);
1412 }
1413
1414 void
1415 togglescrollbars(Client *c, const Arg *arg)
1416 {
1417         GtkPolicyType vspolicy;
1418         Arg a;
1419
1420         gtk_scrolled_window_get_policy(GTK_SCROLLED_WINDOW(c->scroll), NULL,
1421                                        &vspolicy);
1422
1423         if (vspolicy == GTK_POLICY_AUTOMATIC) {
1424                 gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(c->scroll),
1425                                                GTK_POLICY_NEVER,
1426                                                GTK_POLICY_NEVER);
1427         } else {
1428                 gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(c->scroll),
1429                                                GTK_POLICY_AUTOMATIC,
1430                                                GTK_POLICY_AUTOMATIC);
1431                 a.i = +1;
1432                 twitch(c, &a);
1433                 a.i = -1;
1434                 twitch(c, &a);
1435         }
1436 }
1437
1438 void
1439 togglestyle(Client *c, const Arg *arg)
1440 {
1441         enablestyle = !enablestyle;
1442         setstyle(c, enablestyle ? getstyle(geturi(c)) : "");
1443
1444         updatetitle(c);
1445 }
1446
1447 void
1448 gettogglestat(Client *c)
1449 {
1450         gboolean value;
1451         int p = 0;
1452         WebKitWebSettings *settings = webkit_web_view_get_settings(c->view);
1453
1454         togglestat[p++] = cookiepolicy_set(cookiepolicy_get());
1455
1456         g_object_get(G_OBJECT(settings), "enable-caret-browsing", &value,
1457                      NULL);
1458         togglestat[p++] = value? 'C': 'c';
1459
1460         togglestat[p++] = allowgeolocation? 'G': 'g';
1461
1462         togglestat[p++] = enablediskcache? 'D': 'd';
1463
1464         g_object_get(G_OBJECT(settings), "auto-load-images", &value, NULL);
1465         togglestat[p++] = value? 'I': 'i';
1466
1467         g_object_get(G_OBJECT(settings), "enable-scripts", &value, NULL);
1468         togglestat[p++] = value? 'S': 's';
1469
1470         g_object_get(G_OBJECT(settings), "enable-plugins", &value, NULL);
1471         togglestat[p++] = value? 'V': 'v';
1472
1473         togglestat[p++] = enablestyle ? 'M': 'm';
1474
1475         togglestat[p] = '\0';
1476 }
1477
1478 void
1479 getpagestat(Client *c)
1480 {
1481         const char *uri = geturi(c);
1482
1483         pagestats[0] = c->tlsflags > G_TLS_CERTIFICATE_VALIDATE_ALL ? '-' :
1484             c->tlsflags > 0 ? 'U' : 'T';
1485         pagestat[1] = '\0';
1486 }
1487
1488 void
1489 updatetitle(Client *c)
1490 {
1491         char *t;
1492
1493         if (showindicators) {
1494                 gettogglestat(c);
1495                 getpagestat(c);
1496
1497                 if (c->linkhover) {
1498                         t = g_strdup_printf("%s:%s | %s", togglestat, pagestat,
1499                                             c->linkhover);
1500                 } else if (c->progress != 100) {
1501                         t = g_strdup_printf("[%i%%] %s:%s | %s", c->progress,
1502                                             togglestat, pagestat,
1503                                             c->title == NULL ? "" : c->title);
1504                 } else {
1505                         t = g_strdup_printf("%s:%s | %s", togglestat, pagestat,
1506                                             c->title == NULL ? "" : c->title);
1507                 }
1508
1509                 gtk_window_set_title(GTK_WINDOW(c->win), t);
1510                 g_free(t);
1511         } else {
1512                 gtk_window_set_title(GTK_WINDOW(c->win), (c->title == NULL) ?
1513                                      "" : c->title);
1514         }
1515 }
1516
1517 void
1518 updatewinid(Client *c)
1519 {
1520         snprintf(winid, LENGTH(winid), "%lu", c->xid);
1521 }
1522
1523 void
1524 usage(void)
1525 {
1526         die("usage: %s [-bBdDfFgGiIkKmMnNpPsSvx] [-a cookiepolicies ] "
1527             "[-c cookiefile] [-e xid] [-r scriptfile] [-t stylefile] "
1528             "[-u useragent] [-z zoomlevel] [uri]\n", basename(argv0));
1529 }
1530
1531 void
1532 zoom(Client *c, const Arg *arg)
1533 {
1534         c->zoomed = TRUE;
1535         if (arg->i < 0) {
1536                 /* zoom out */
1537                 webkit_web_view_zoom_out(c->view);
1538         } else if (arg->i > 0) {
1539                 /* zoom in */
1540                 webkit_web_view_zoom_in(c->view);
1541         } else {
1542                 /* reset */
1543                 c->zoomed = FALSE;
1544                 webkit_web_view_set_zoom_level(c->view, 1.0);
1545         }
1546 }
1547
1548 int
1549 main(int argc, char *argv[])
1550 {
1551         Arg arg;
1552         Client *c;
1553
1554         memset(&arg, 0, sizeof(arg));
1555
1556         /* command line args */
1557         ARGBEGIN {
1558         case 'a':
1559                 cookiepolicies = EARGF(usage());
1560                 break;
1561         case 'b':
1562                 enablescrollbars = 0;
1563                 break;
1564         case 'B':
1565                 enablescrollbars = 1;
1566                 break;
1567         case 'c':
1568                 cookiefile = EARGF(usage());
1569                 break;
1570         case 'd':
1571                 enablediskcache = 0;
1572                 break;
1573         case 'D':
1574                 enablediskcache = 1;
1575                 break;
1576         case 'e':
1577                 embed = strtol(EARGF(usage()), NULL, 0);
1578                 break;
1579         case 'f':
1580                 runinfullscreen = 0;
1581                 break;
1582         case 'F':
1583                 runinfullscreen = 1;
1584                 break;
1585         case 'g':
1586                 allowgeolocation = 0;
1587                 break;
1588         case 'G':
1589                 allowgeolocation = 1;
1590                 break;
1591         case 'i':
1592                 loadimages = 0;
1593                 break;
1594         case 'I':
1595                 loadimages = 1;
1596                 break;
1597         case 'k':
1598                 kioskmode = 0;
1599                 break;
1600         case 'K':
1601                 kioskmode = 1;
1602                 break;
1603         case 'm':
1604                 enablestyle = 0;
1605                 break;
1606         case 'M':
1607                 enablestyle = 1;
1608                 break;
1609         case 'n':
1610                 enableinspector = 0;
1611                 break;
1612         case 'N':
1613                 enableinspector = 1;
1614                 break;
1615         case 'p':
1616                 enableplugins = 0;
1617                 break;
1618         case 'P':
1619                 enableplugins = 1;
1620                 break;
1621         case 'r':
1622                 scriptfile = EARGF(usage());
1623                 break;
1624         case 's':
1625                 enablescripts = 0;
1626                 break;
1627         case 'S':
1628                 enablescripts = 1;
1629                 break;
1630         case 't':
1631                 stylefile = EARGF(usage());
1632                 break;
1633         case 'u':
1634                 useragent = EARGF(usage());
1635                 break;
1636         case 'v':
1637                 die("surf-"VERSION", ©2009-2015 surf engineers, "
1638                     "see LICENSE for details\n");
1639         case 'x':
1640                 showxid = TRUE;
1641                 break;
1642         case 'z':
1643                 zoomlevel = strtof(EARGF(usage()), NULL);
1644                 break;
1645         default:
1646                 usage();
1647         } ARGEND;
1648         if (argc > 0)
1649                 arg.v = argv[0];
1650
1651         setup();
1652         c = newclient(NULL);
1653         showview(NULL, c);
1654         if (arg.v)
1655                 loaduri(clients, &arg);
1656         else
1657                 updatetitle(c);
1658
1659         gtk_main();
1660         cleanup();
1661
1662         return EXIT_SUCCESS;
1663 }
1664