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