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