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