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