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