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