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