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