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