Adapted progresschanged()
[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 click;
80         unsigned int mask;
81         guint button;
82         void (*func)(Client *c, const Arg *arg);
83         const Arg arg;
84 } Button;
85
86 typedef struct {
87         char *regex;
88         char *style;
89         regex_t re;
90 } SiteStyle;
91
92 static Display *dpy;
93 static Atom atoms[AtomLast];
94 static Client *clients = NULL;
95 static Window embed = 0;
96 static gboolean showxid = FALSE;
97 static char winid[64];
98 static char togglestat[9];
99 static char pagestat[3];
100 static GTlsDatabase *tlsdb;
101 static int cookiepolicy;
102 static char *stylefile = NULL;
103
104 static void addaccelgroup(Client *c);
105 static void beforerequest(WebKitWebView *w, WebKitWebFrame *f,
106                           WebKitWebResource *r, WebKitNetworkRequest *req,
107                           WebKitNetworkResponse *resp, Client *c);
108 static char *buildfile(const char *path);
109 static char *buildpath(const char *path);
110 static gboolean buttonrelease(WebKitWebView *web, GdkEventButton *e, Client *c);
111 static void cleanup(void);
112 static void clipboard(Client *c, const Arg *arg);
113
114 static WebKitCookieAcceptPolicy cookiepolicy_get(void);
115 static char cookiepolicy_set(const WebKitCookieAcceptPolicy p);
116
117 static char *copystr(char **str, const char *src);
118 static GtkWidget *createview(WebKitWebView *v, WebKitNavigationAction *a,
119                 Client *c);
120 static gboolean decidepolicy(WebKitWebView *v, WebKitPolicyDecision *d,
121     WebKitPolicyDecisionType dt, Client *c);
122 static void decidenavigation(WebKitPolicyDecision *d, Client *c);
123 static void decidenewwindow(WebKitPolicyDecision *d, Client *c);
124 static void decideresource(WebKitPolicyDecision *d, Client *c);
125 static gboolean deletion_interface(WebKitWebView *view,
126                                    WebKitDOMHTMLElement *arg1, Client *c);
127 static void destroyclient(Client *c);
128 static void destroywin(GtkWidget* w, Client *c);
129 static void die(const char *errstr, ...);
130 static void eval(Client *c, const Arg *arg);
131 static void find(Client *c, const Arg *arg);
132 static void fullscreen(Client *c, const Arg *arg);
133 static gboolean permissionrequested(WebKitWebView *v,
134                 WebKitPermissionRequest *r, Client *c);
135 static const char *getatom(Client *c, int a);
136 static void gettogglestat(Client *c);
137 static void getpagestat(Client *c);
138 static char *geturi(Client *c);
139 static const gchar *getstyle(const char *uri);
140 static void setstyle(Client *c, const char *style);
141
142 static void handleplumb(Client *c, WebKitWebView *w, const gchar *uri);
143
144 static gboolean initdownload(WebKitWebView *v, WebKitDownload *o, Client *c);
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 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 progresschanged(WebKitWebView *v, GParamSpec *ps, 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 loadchanged(WebKitWebView *v, WebKitLoadEvent e, Client *c)
813 {
814         switch (e) {
815         case WEBKIT_LOAD_STARTED:
816                 c->tlsflags = G_TLS_CERTIFICATE_VALIDATE_ALL + 1;
817                 break;
818         case WEBKIT_LOAD_REDIRECTED:
819                 setatom(c, AtomUri, geturi(c));
820                 break;
821         case WEBKIT_LOAD_COMMITTED:
822                 if (!webkit_web_view_get_tls_info(c->view, NULL, &(c->tlsflags)))
823                         c->tlsflags = G_TLS_CERTIFICATE_VALIDATE_ALL + 1;
824
825                 setatom(c, AtomUri, geturi(c));
826
827                 if (enablestyle)
828                         setstyle(c, getstyle(geturi(c)));
829                 break;
830         case WEBKIT_LOAD_FINISHED:
831                 /* Disabled until we write some WebKitWebExtension for
832                  * manipulating the DOM directly.
833                 evalscript(c, "document.documentElement.style.overflow = '%s'",
834                     enablescrollbars ? "auto" : "hidden");
835                 */
836                 runscript(c);
837                 break;
838         }
839         updatetitle(c);
840 }
841
842 void
843 loaduri(Client *c, const Arg *arg)
844 {
845         char *u = NULL, *rp;
846         const char *uri = (char *)arg->v;
847         Arg a = { .b = FALSE };
848         struct stat st;
849
850         if (strcmp(uri, "") == 0)
851                 return;
852
853         /* In case it's a file path. */
854         if (stat(uri, &st) == 0) {
855                 rp = realpath(uri, NULL);
856                 u = g_strdup_printf("file://%s", rp);
857                 free(rp);
858         } else {
859                 u = g_strrstr(uri, "://") ? g_strdup(uri)
860                     : g_strdup_printf("http://%s", uri);
861         }
862
863         setatom(c, AtomUri, uri);
864
865         /* prevents endless loop */
866         if (strcmp(u, geturi(c)) == 0) {
867                 reload(c, &a);
868         } else {
869                 webkit_web_view_load_uri(c->view, u);
870                 c->progress = 0;
871                 c->title = copystr(&c->title, u);
872                 updatetitle(c);
873         }
874         g_free(u);
875 }
876
877 void
878 navigate(Client *c, const Arg *arg)
879 {
880         int steps = *(int *)arg;
881         webkit_web_view_go_back_or_forward(c->view, steps);
882 }
883
884 Client *
885 newclient(Client *rc)
886 {
887         Client *c;
888         gdouble dpi;
889
890         if (!(c = calloc(1, sizeof(Client))))
891                 die("Cannot malloc!\n");
892
893         c->title = NULL;
894         c->progress = 100;
895
896         c->next = clients;
897         clients = c;
898
899         c->view = newview(c, rc ? rc->view : NULL);
900         c->tlsflags = G_TLS_CERTIFICATE_VALIDATE_ALL + 1;
901
902         return c;
903 }
904
905 WebKitWebView *
906 newview(Client *c, WebKitWebView *rv)
907 {
908         WebKitWebView *v;
909         WebKitSettings *settings;
910         WebKitUserContentManager *contentmanager;
911         WebKitWebContext *context;
912         char *ua;
913
914         /* Webview */
915         if (rv) {
916                 v = WEBKIT_WEB_VIEW(
917                     webkit_web_view_new_with_related_view(rv));
918         } else {
919                 settings = webkit_settings_new_with_settings(
920                     "auto-load-images", loadimages,
921                     "default-font-size", defaultfontsize,
922                     "enable-caret-browsing", enablecaretbrowsing,
923                     "enable-developer-extras", enableinspector,
924                     "enable-dns-prefetching", enablednsprefetching,
925                     "enable-frame-flattening", enableframeflattening,
926                     "enable-html5-database", enablecache,
927                     "enable-html5-local-storage", enablecache,
928                     "enable-javascript", enablescripts,
929                     "enable-plugins", enableplugins,
930                     NULL);
931                 if (!(ua = getenv("SURF_USERAGENT")))
932                         ua = useragent;
933                 webkit_settings_set_user_agent(settings, ua);
934                 /* Have a look at http://webkitgtk.org/reference/webkit2gtk/stable/WebKitSettings.html
935                  * for more interesting settings */
936
937                 contentmanager = webkit_user_content_manager_new();
938
939                 context = webkit_web_context_new_with_website_data_manager(
940                     webkit_website_data_manager_new(
941                     "base-cache-directory", cachedir,
942                     "base-data-directory", cachedir,
943                     NULL));
944
945                 /* rendering process model, can be a shared unique one or one for each
946                  * view */
947                 webkit_web_context_set_process_model(context,
948                     WEBKIT_PROCESS_MODEL_MULTIPLE_SECONDARY_PROCESSES);
949                 /* ssl */
950                 webkit_web_context_set_tls_errors_policy(context, strictssl ?
951                     WEBKIT_TLS_ERRORS_POLICY_FAIL : WEBKIT_TLS_ERRORS_POLICY_IGNORE);
952                 /* disk cache */
953                 webkit_web_context_set_cache_model(context, enablecache ?
954                     WEBKIT_CACHE_MODEL_WEB_BROWSER : WEBKIT_CACHE_MODEL_DOCUMENT_VIEWER);
955
956                 /* Currently only works with text file to be compatible with curl */
957                 webkit_cookie_manager_set_persistent_storage(
958                     webkit_web_context_get_cookie_manager(context), cookiefile,
959                     WEBKIT_COOKIE_PERSISTENT_STORAGE_TEXT);
960                 /* cookie policy */
961                 webkit_cookie_manager_set_accept_policy(
962                     webkit_web_context_get_cookie_manager(context),
963                     cookiepolicy_get());
964
965                 v = g_object_new(WEBKIT_TYPE_WEB_VIEW,
966                     "settings", settings,
967                     "user-content-manager", contentmanager,
968                     "web-context", context,
969                     NULL);
970         }
971
972         g_signal_connect(G_OBJECT(v),
973                          "notify::title",
974                          G_CALLBACK(titlechanged), c);
975         g_signal_connect(G_OBJECT(v),
976                          "mouse-target-changed",
977                          G_CALLBACK(mousetargetchanged), c);
978         g_signal_connect(G_OBJECT(v),
979                          "permission-request",
980                          G_CALLBACK(permissionrequested), c);
981         g_signal_connect(G_OBJECT(v),
982                          "create",
983                          G_CALLBACK(createview), c);
984         g_signal_connect(G_OBJECT(v), "ready-to-show",
985                          G_CALLBACK(showview), c);
986         g_signal_connect(G_OBJECT(v),
987                          "decide-policy",
988                          G_CALLBACK(decidepolicy), c);
989         g_signal_connect(G_OBJECT(v),
990                          "window-object-cleared",
991                          G_CALLBACK(windowobjectcleared), c);
992         g_signal_connect(G_OBJECT(v),
993                          "load-changed",
994                          G_CALLBACK(loadchanged), c);
995         g_signal_connect(G_OBJECT(v),
996                          "notify::estimated-load-progress",
997                          G_CALLBACK(progresschanged), c);
998         g_signal_connect(G_OBJECT(v),
999                          "download-requested",
1000                          G_CALLBACK(initdownload), c);
1001         g_signal_connect(G_OBJECT(v),
1002                          "button-release-event",
1003                          G_CALLBACK(buttonrelease), c);
1004         g_signal_connect(G_OBJECT(v),
1005                          "context-menu",
1006                          G_CALLBACK(contextmenu), c);
1007         g_signal_connect(G_OBJECT(v),
1008                          "resource-request-starting",
1009                          G_CALLBACK(beforerequest), c);
1010         g_signal_connect(G_OBJECT(v),
1011                          "should-show-delete-interface-for-element",
1012                          G_CALLBACK(deletion_interface), c);
1013
1014         return v;
1015 }
1016
1017 void
1018 showview(WebKitWebView *v, Client *c)
1019 {
1020         GdkGeometry hints = { 1, 1 };
1021         GdkRGBA bgcolor = { 0 };
1022         GdkWindow *gwin;
1023
1024         /* Window */
1025         if (embed) {
1026                 c->win = gtk_plug_new(embed);
1027         } else {
1028                 c->win = gtk_window_new(GTK_WINDOW_TOPLEVEL);
1029
1030                 /* TA:  20091214:  Despite what the GNOME docs say, the ICCCM
1031                  * is always correct, so we should still call this function.
1032                  * But when doing so, we *must* differentiate between a
1033                  * WM_CLASS and a resource on the window.  By convention, the
1034                  * window class (WM_CLASS) is capped, while the resource is in
1035                  * lowercase.   Both these values come as a pair.
1036                  */
1037                 gtk_window_set_wmclass(GTK_WINDOW(c->win), "surf", "Surf");
1038
1039                 /* TA:  20091214:  And set the role here as well -- so that
1040                  * sessions can pick this up.
1041                  */
1042                 gtk_window_set_role(GTK_WINDOW(c->win), "Surf");
1043         }
1044         gtk_window_set_default_size(GTK_WINDOW(c->win), 800, 600);
1045         g_signal_connect(G_OBJECT(c->win),
1046                          "destroy",
1047                          G_CALLBACK(destroywin), c);
1048         g_signal_connect(G_OBJECT(c->win),
1049                          "leave_notify_event",
1050                          G_CALLBACK(titlechangeleave), c);
1051
1052         if (!kioskmode)
1053                 addaccelgroup(c);
1054
1055         /* Arranging */
1056         gtk_container_add(GTK_CONTAINER(c->win), GTK_WIDGET(c->view));
1057
1058         /* Setup */
1059         gtk_widget_grab_focus(GTK_WIDGET(c->view));
1060         gtk_widget_show(GTK_WIDGET(c->view));
1061         gtk_widget_show(c->win);
1062         gwin = gtk_widget_get_window(GTK_WIDGET(c->win));
1063         c->xid = gdk_x11_window_get_xid(gwin);
1064         gtk_window_set_geometry_hints(GTK_WINDOW(c->win), NULL, &hints,
1065                                       GDK_HINT_MIN_SIZE);
1066         gdk_window_set_events(gwin, GDK_ALL_EVENTS_MASK);
1067         gdk_window_add_filter(gwin, processx, c);
1068
1069         runscript(frame);
1070
1071         /* This might conflict with _zoomto96dpi_. */
1072         if (zoomlevel != 1.0)
1073                 webkit_web_view_set_zoom_level(c->view, zoomlevel);
1074
1075         if (runinfullscreen)
1076                 fullscreen(c, NULL);
1077
1078         setatom(c, AtomFind, "");
1079         setatom(c, AtomUri, "about:blank");
1080         if (hidebackground)
1081                 webkit_web_view_set_background_color(c->view, &bgcolor);
1082
1083         if (showxid) {
1084                 gdk_display_sync(gtk_widget_get_display(c->win));
1085                 printf("%lu\n", c->xid);
1086                 fflush(NULL);
1087                 if (fclose(stdout) != 0) {
1088                         die("Error closing stdout");
1089                 }
1090         }
1091 }
1092
1093 void
1094 newwindow(Client *c, const Arg *arg, gboolean noembed)
1095 {
1096         guint i = 0;
1097         const char *cmd[18], *uri;
1098         const Arg a = { .v = (void *)cmd };
1099         char tmp[64];
1100
1101         cmd[i++] = argv0;
1102         cmd[i++] = "-a";
1103         cmd[i++] = cookiepolicies;
1104         if (!enablescrollbars)
1105                 cmd[i++] = "-b";
1106         if (embed && !noembed) {
1107                 cmd[i++] = "-e";
1108                 snprintf(tmp, LENGTH(tmp), "%u", (int)embed);
1109                 cmd[i++] = tmp;
1110         }
1111         if (!allowgeolocation)
1112                 cmd[i++] = "-g";
1113         if (!loadimages)
1114                 cmd[i++] = "-i";
1115         if (kioskmode)
1116                 cmd[i++] = "-k";
1117         if (!enableplugins)
1118                 cmd[i++] = "-p";
1119         if (!enablescripts)
1120                 cmd[i++] = "-s";
1121         if (showxid)
1122                 cmd[i++] = "-x";
1123         if (enablediskcache)
1124                 cmd[i++] = "-D";
1125         cmd[i++] = "-c";
1126         cmd[i++] = cookiefile;
1127         cmd[i++] = "--";
1128         uri = arg->v ? (char *)arg->v : c->linkhover;
1129         if (uri)
1130                 cmd[i++] = uri;
1131         cmd[i++] = NULL;
1132         spawn(NULL, &a);
1133 }
1134
1135 gboolean
1136 contextmenu(WebKitWebView *view, GtkWidget *menu, WebKitHitTestResult *target,
1137             gboolean keyboard, Client *c)
1138 {
1139         GList *items = gtk_container_get_children(GTK_CONTAINER(GTK_MENU(menu)));
1140
1141         for (GList *l = items; l; l = l->next)
1142                 g_signal_connect(l->data, "activate", G_CALLBACK(menuactivate), c);
1143
1144         g_list_free(items);
1145         return FALSE;
1146 }
1147
1148 void
1149 menuactivate(GtkMenuItem *item, Client *c)
1150 {
1151         /*
1152          * context-menu-action-2000 open link
1153          * context-menu-action-1    open link in window
1154          * context-menu-action-2    download linked file
1155          * context-menu-action-3    copy link location
1156          * context-menu-action-7    copy image address
1157          * context-menu-action-13   reload
1158          * context-menu-action-10   back
1159          * context-menu-action-11   forward
1160          * context-menu-action-12   stop
1161          */
1162
1163         const gchar *name, *uri;
1164         GtkClipboard *prisel, *clpbrd;
1165
1166         name = gtk_actionable_get_action_name(GTK_ACTIONABLE(item));
1167         if (name == NULL)
1168                 return;
1169
1170         if (!g_strcmp0(name, "context-menu-action-3")) {
1171                 prisel = gtk_clipboard_get(GDK_SELECTION_PRIMARY);
1172                 gtk_clipboard_set_text(prisel, c->linkhover, -1);
1173         } else if (!g_strcmp0(name, "context-menu-action-7")) {
1174                 prisel = gtk_clipboard_get(GDK_SELECTION_PRIMARY);
1175                 clpbrd = gtk_clipboard_get(GDK_SELECTION_CLIPBOARD);
1176                 uri = gtk_clipboard_wait_for_text(clpbrd);
1177                 if (uri)
1178                         gtk_clipboard_set_text(prisel, uri, -1);
1179         }
1180 }
1181
1182 void
1183 pasteuri(GtkClipboard *clipboard, const char *text, gpointer d)
1184 {
1185         Arg arg = {.v = text };
1186         if (text != NULL)
1187                 loaduri((Client *) d, &arg);
1188 }
1189
1190 void
1191 print(Client *c, const Arg *arg)
1192 {
1193         webkit_web_frame_print(webkit_web_view_get_main_frame(c->view));
1194 }
1195
1196 GdkFilterReturn
1197 processx(GdkXEvent *e, GdkEvent *event, gpointer d)
1198 {
1199         Client *c = (Client *)d;
1200         XPropertyEvent *ev;
1201         Arg arg;
1202
1203         if (((XEvent *)e)->type == PropertyNotify) {
1204                 ev = &((XEvent *)e)->xproperty;
1205                 if (ev->state == PropertyNewValue) {
1206                         if (ev->atom == atoms[AtomFind]) {
1207                                 arg.b = TRUE;
1208                                 find(c, &arg);
1209
1210                                 return GDK_FILTER_REMOVE;
1211                         } else if (ev->atom == atoms[AtomGo]) {
1212                                 arg.v = getatom(c, AtomGo);
1213                                 loaduri(c, &arg);
1214
1215                                 return GDK_FILTER_REMOVE;
1216                         }
1217                 }
1218         }
1219         return GDK_FILTER_CONTINUE;
1220 }
1221
1222 void
1223 progresschanged(WebKitWebView *v, GParamSpec *ps, Client *c)
1224 {
1225         c->progress = webkit_web_view_get_estimated_load_progress(c->view) *
1226             100;
1227         updatetitle(c);
1228 }
1229
1230 void
1231 linkopen(Client *c, const Arg *arg)
1232 {
1233         newwindow(NULL, arg, 1);
1234 }
1235
1236 void
1237 linkopenembed(Client *c, const Arg *arg)
1238 {
1239         newwindow(NULL, arg, 0);
1240 }
1241
1242 void
1243 reload(Client *c, const Arg *arg)
1244 {
1245         gboolean nocache = *(gboolean *)arg;
1246         if (nocache)
1247                 webkit_web_view_reload_bypass_cache(c->view);
1248         else
1249                 webkit_web_view_reload(c->view);
1250 }
1251
1252 void
1253 scroll_h(Client *c, const Arg *arg)
1254 {
1255         scroll(gtk_scrolled_window_get_hadjustment(
1256                GTK_SCROLLED_WINDOW(c->scroll)), arg);
1257 }
1258
1259 void
1260 scroll_v(Client *c, const Arg *arg)
1261 {
1262         scroll(gtk_scrolled_window_get_vadjustment(
1263                GTK_SCROLLED_WINDOW(c->scroll)), arg);
1264 }
1265
1266 void
1267 scroll(GtkAdjustment *a, const Arg *arg)
1268 {
1269         gdouble v;
1270
1271         v = gtk_adjustment_get_value(a);
1272         switch (arg->i) {
1273         case +10000:
1274         case -10000:
1275                 v += gtk_adjustment_get_page_increment(a) * (arg->i / 10000);
1276                 break;
1277         case +20000:
1278         case -20000:
1279         default:
1280                 v += gtk_adjustment_get_step_increment(a) * arg->i;
1281         }
1282
1283         v = MAX(v, 0.0);
1284         v = MIN(v, gtk_adjustment_get_upper(a) -
1285                 gtk_adjustment_get_page_size(a));
1286         gtk_adjustment_set_value(a, v);
1287 }
1288
1289 void
1290 setatom(Client *c, int a, const char *v)
1291 {
1292         XSync(dpy, False);
1293         XChangeProperty(dpy, c->xid,
1294                         atoms[a], XA_STRING, 8, PropModeReplace,
1295                         (unsigned char *)v, strlen(v) + 1);
1296 }
1297
1298 void
1299 setup(void)
1300 {
1301         int i;
1302         char *styledirfile, *stylepath;
1303         WebKitWebContext *context;
1304         GError *error = NULL;
1305
1306         /* clean up any zombies immediately */
1307         sigchld(0);
1308         gtk_init(NULL, NULL);
1309
1310         dpy = GDK_DISPLAY_XDISPLAY(gdk_display_get_default());
1311
1312         /* atoms */
1313         atoms[AtomFind] = XInternAtom(dpy, "_SURF_FIND", False);
1314         atoms[AtomGo] = XInternAtom(dpy, "_SURF_GO", False);
1315         atoms[AtomUri] = XInternAtom(dpy, "_SURF_URI", False);
1316
1317         /* dirs and files */
1318         cookiefile = buildfile(cookiefile);
1319         scriptfile = buildfile(scriptfile);
1320         cachedir   = buildpath(cachedir);
1321         if (stylefile == NULL) {
1322                 styledir = buildpath(styledir);
1323                 for (i = 0; i < LENGTH(styles); i++) {
1324                         if (regcomp(&(styles[i].re), styles[i].regex,
1325                             REG_EXTENDED)) {
1326                                 fprintf(stderr,
1327                                         "Could not compile regex: %s\n",
1328                                         styles[i].regex);
1329                                 styles[i].regex = NULL;
1330                         }
1331                         styledirfile    = g_strconcat(styledir, "/",
1332                                                       styles[i].style, NULL);
1333                         stylepath       = buildfile(styledirfile);
1334                         styles[i].style = g_strconcat("file://", stylepath,
1335                                                       NULL);
1336                         g_free(styledirfile);
1337                         g_free(stylepath);
1338                 }
1339                 g_free(styledir);
1340         } else {
1341                 stylepath = buildfile(stylefile);
1342                 stylefile = g_strconcat("file://", stylepath, NULL);
1343                 g_free(stylepath);
1344         }
1345 }
1346
1347 void
1348 sigchld(int unused)
1349 {
1350         if (signal(SIGCHLD, sigchld) == SIG_ERR)
1351                 die("Can't install SIGCHLD handler");
1352         while (0 < waitpid(-1, NULL, WNOHANG));
1353 }
1354
1355 void
1356 spawn(Client *c, const Arg *arg)
1357 {
1358         if (fork() == 0) {
1359                 if (dpy)
1360                         close(ConnectionNumber(dpy));
1361                 setsid();
1362                 execvp(((char **)arg->v)[0], (char **)arg->v);
1363                 fprintf(stderr, "surf: execvp %s", ((char **)arg->v)[0]);
1364                 perror(" failed");
1365                 exit(0);
1366         }
1367 }
1368
1369 void
1370 eval(Client *c, const Arg *arg)
1371 {
1372         WebKitWebFrame *frame = webkit_web_view_get_main_frame(c->view);
1373         evalscript(webkit_web_frame_get_global_context(frame),
1374                    ((char **)arg->v)[0], "");
1375 }
1376
1377 void
1378 stop(Client *c, const Arg *arg)
1379 {
1380         webkit_web_view_stop_loading(c->view);
1381 }
1382
1383 void
1384 titlechanged(WebKitWebView *view, GParamSpec *ps, Client *c)
1385 {
1386         c->title = webkit_web_view_get_title(c->view);
1387         updatetitle(c);
1388 }
1389
1390 void
1391 titlechangeleave(void *a, void *b, Client *c)
1392 {
1393         c->linkhover = NULL;
1394         updatetitle(c);
1395 }
1396
1397 void
1398 toggle(Client *c, const Arg *arg)
1399 {
1400         WebKitWebSettings *settings;
1401         char *name = (char *)arg->v;
1402         gboolean value;
1403         Arg a = { .b = FALSE };
1404
1405         settings = webkit_web_view_get_settings(c->view);
1406         g_object_get(G_OBJECT(settings), name, &value, NULL);
1407         g_object_set(G_OBJECT(settings), name, !value, NULL);
1408
1409         reload(c, &a);
1410 }
1411
1412 void
1413 togglecookiepolicy(Client *c, const Arg *arg)
1414 {
1415         ++cookiepolicy;
1416         cookiepolicy %= strlen(cookiepolicies);
1417
1418         webkit_cookie_manager_set_accept_policy(
1419             webkit_web_context_get_cookie_manager(
1420             webkit_web_view_get_context(c->view)),
1421             cookiepolicy_get());
1422
1423         updatetitle(c);
1424         /* Do not reload. */
1425 }
1426
1427 void
1428 togglegeolocation(Client *c, const Arg *arg)
1429 {
1430         Arg a = { .b = FALSE };
1431
1432         allowgeolocation ^= 1;
1433         reload(c, &a);
1434 }
1435
1436 void
1437 twitch(Client *c, const Arg *arg)
1438 {
1439         GtkAdjustment *a;
1440         gdouble v;
1441
1442         a = gtk_scrolled_window_get_vadjustment(GTK_SCROLLED_WINDOW(
1443                                                 c->scroll));
1444
1445         v = gtk_adjustment_get_value(a);
1446
1447         v += arg->i;
1448
1449         v = MAX(v, 0.0);
1450         v = MIN(v, gtk_adjustment_get_upper(a) -
1451                 gtk_adjustment_get_page_size(a));
1452         gtk_adjustment_set_value(a, v);
1453 }
1454
1455 void
1456 togglescrollbars(Client *c, const Arg *arg)
1457 {
1458         GtkPolicyType vspolicy;
1459         Arg a;
1460
1461         gtk_scrolled_window_get_policy(GTK_SCROLLED_WINDOW(c->scroll), NULL,
1462                                        &vspolicy);
1463
1464         if (vspolicy == GTK_POLICY_AUTOMATIC) {
1465                 gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(c->scroll),
1466                                                GTK_POLICY_NEVER,
1467                                                GTK_POLICY_NEVER);
1468         } else {
1469                 gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(c->scroll),
1470                                                GTK_POLICY_AUTOMATIC,
1471                                                GTK_POLICY_AUTOMATIC);
1472                 a.i = +1;
1473                 twitch(c, &a);
1474                 a.i = -1;
1475                 twitch(c, &a);
1476         }
1477 }
1478
1479 void
1480 togglestyle(Client *c, const Arg *arg)
1481 {
1482         enablestyle = !enablestyle;
1483         setstyle(c, enablestyle ? getstyle(geturi(c)) : "");
1484
1485         updatetitle(c);
1486 }
1487
1488 void
1489 gettogglestat(Client *c)
1490 {
1491         gboolean value;
1492         int p = 0;
1493         WebKitWebSettings *settings = webkit_web_view_get_settings(c->view);
1494
1495         togglestat[p++] = cookiepolicy_set(cookiepolicy_get());
1496
1497         g_object_get(G_OBJECT(settings), "enable-caret-browsing", &value,
1498                      NULL);
1499         togglestat[p++] = value? 'C': 'c';
1500
1501         togglestat[p++] = allowgeolocation? 'G': 'g';
1502
1503         togglestat[p++] = enablediskcache? 'D': 'd';
1504
1505         g_object_get(G_OBJECT(settings), "auto-load-images", &value, NULL);
1506         togglestat[p++] = value? 'I': 'i';
1507
1508         g_object_get(G_OBJECT(settings), "enable-scripts", &value, NULL);
1509         togglestat[p++] = value? 'S': 's';
1510
1511         g_object_get(G_OBJECT(settings), "enable-plugins", &value, NULL);
1512         togglestat[p++] = value? 'V': 'v';
1513
1514         togglestat[p++] = enablestyle ? 'M': 'm';
1515
1516         togglestat[p] = '\0';
1517 }
1518
1519 void
1520 getpagestat(Client *c)
1521 {
1522         const char *uri = geturi(c);
1523
1524         pagestats[0] = c->tlsflags > G_TLS_CERTIFICATE_VALIDATE_ALL ? '-' :
1525             c->tlsflags > 0 ? 'U' : 'T';
1526         pagestat[1] = '\0';
1527 }
1528
1529 void
1530 updatetitle(Client *c)
1531 {
1532         char *t;
1533
1534         if (showindicators) {
1535                 gettogglestat(c);
1536                 getpagestat(c);
1537
1538                 if (c->linkhover) {
1539                         t = g_strdup_printf("%s:%s | %s", togglestat, pagestat,
1540                                             c->linkhover);
1541                 } else if (c->progress != 100) {
1542                         t = g_strdup_printf("[%i%%] %s:%s | %s", c->progress,
1543                                             togglestat, pagestat,
1544                                             c->title == NULL ? "" : c->title);
1545                 } else {
1546                         t = g_strdup_printf("%s:%s | %s", togglestat, pagestat,
1547                                             c->title == NULL ? "" : c->title);
1548                 }
1549
1550                 gtk_window_set_title(GTK_WINDOW(c->win), t);
1551                 g_free(t);
1552         } else {
1553                 gtk_window_set_title(GTK_WINDOW(c->win), (c->title == NULL) ?
1554                                      "" : c->title);
1555         }
1556 }
1557
1558 void
1559 updatewinid(Client *c)
1560 {
1561         snprintf(winid, LENGTH(winid), "%lu", c->xid);
1562 }
1563
1564 void
1565 usage(void)
1566 {
1567         die("usage: %s [-bBdDfFgGiIkKmMnNpPsSvx] [-a cookiepolicies ] "
1568             "[-c cookiefile] [-e xid] [-r scriptfile] [-t stylefile] "
1569             "[-u useragent] [-z zoomlevel] [uri]\n", basename(argv0));
1570 }
1571
1572 void
1573 windowobjectcleared(GtkWidget *w, WebKitWebFrame *frame, JSContextRef js,
1574                     JSObjectRef win, Client *c)
1575 {
1576         runscript(frame);
1577 }
1578
1579 void
1580 zoom(Client *c, const Arg *arg)
1581 {
1582         c->zoomed = TRUE;
1583         if (arg->i < 0) {
1584                 /* zoom out */
1585                 webkit_web_view_zoom_out(c->view);
1586         } else if (arg->i > 0) {
1587                 /* zoom in */
1588                 webkit_web_view_zoom_in(c->view);
1589         } else {
1590                 /* reset */
1591                 c->zoomed = FALSE;
1592                 webkit_web_view_set_zoom_level(c->view, 1.0);
1593         }
1594 }
1595
1596 int
1597 main(int argc, char *argv[])
1598 {
1599         Arg arg;
1600         Client *c;
1601
1602         memset(&arg, 0, sizeof(arg));
1603
1604         /* command line args */
1605         ARGBEGIN {
1606         case 'a':
1607                 cookiepolicies = EARGF(usage());
1608                 break;
1609         case 'b':
1610                 enablescrollbars = 0;
1611                 break;
1612         case 'B':
1613                 enablescrollbars = 1;
1614                 break;
1615         case 'c':
1616                 cookiefile = EARGF(usage());
1617                 break;
1618         case 'd':
1619                 enablediskcache = 0;
1620                 break;
1621         case 'D':
1622                 enablediskcache = 1;
1623                 break;
1624         case 'e':
1625                 embed = strtol(EARGF(usage()), NULL, 0);
1626                 break;
1627         case 'f':
1628                 runinfullscreen = 0;
1629                 break;
1630         case 'F':
1631                 runinfullscreen = 1;
1632                 break;
1633         case 'g':
1634                 allowgeolocation = 0;
1635                 break;
1636         case 'G':
1637                 allowgeolocation = 1;
1638                 break;
1639         case 'i':
1640                 loadimages = 0;
1641                 break;
1642         case 'I':
1643                 loadimages = 1;
1644                 break;
1645         case 'k':
1646                 kioskmode = 0;
1647                 break;
1648         case 'K':
1649                 kioskmode = 1;
1650                 break;
1651         case 'm':
1652                 enablestyle = 0;
1653                 break;
1654         case 'M':
1655                 enablestyle = 1;
1656                 break;
1657         case 'n':
1658                 enableinspector = 0;
1659                 break;
1660         case 'N':
1661                 enableinspector = 1;
1662                 break;
1663         case 'p':
1664                 enableplugins = 0;
1665                 break;
1666         case 'P':
1667                 enableplugins = 1;
1668                 break;
1669         case 'r':
1670                 scriptfile = EARGF(usage());
1671                 break;
1672         case 's':
1673                 enablescripts = 0;
1674                 break;
1675         case 'S':
1676                 enablescripts = 1;
1677                 break;
1678         case 't':
1679                 stylefile = EARGF(usage());
1680                 break;
1681         case 'u':
1682                 useragent = EARGF(usage());
1683                 break;
1684         case 'v':
1685                 die("surf-"VERSION", ©2009-2015 surf engineers, "
1686                     "see LICENSE for details\n");
1687         case 'x':
1688                 showxid = TRUE;
1689                 break;
1690         case 'z':
1691                 zoomlevel = strtof(EARGF(usage()), NULL);
1692                 break;
1693         default:
1694                 usage();
1695         } ARGEND;
1696         if (argc > 0)
1697                 arg.v = argv[0];
1698
1699         setup();
1700         c = newclient(NULL);
1701         showview(NULL, c);
1702         if (arg.v)
1703                 loaduri(clients, &arg);
1704         else
1705                 updatetitle(c);
1706
1707         gtk_main();
1708         cleanup();
1709
1710         return EXIT_SUCCESS;
1711 }
1712