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