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