Data: is part of the browser too.
[surf.git] / surf.c
1 /* See LICENSE file for copyright and license details.
2  *
3  * To understand surf, start reading main().
4  */
5
6 #include <signal.h>
7 #include <X11/X.h>
8 #include <X11/Xatom.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 <webkit/webkit.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
28 #include "arg.h"
29
30 char *argv0;
31
32 #define LENGTH(x)               (sizeof x / sizeof x[0])
33 #define CLEANMASK(mask)         (mask & (MODKEY|GDK_SHIFT_MASK))
34 #define COOKIEJAR_TYPE          (cookiejar_get_type ())
35 #define COOKIEJAR(obj)          (G_TYPE_CHECK_INSTANCE_CAST ((obj), COOKIEJAR_TYPE, CookieJar))
36
37 enum { AtomFind, AtomGo, AtomUri, AtomLast };
38
39 typedef union Arg Arg;
40 union Arg {
41         gboolean b;
42         gint i;
43         const void *v;
44 };
45
46 typedef struct Client {
47         GtkWidget *win, *scroll, *vbox, *pane;
48         WebKitWebView *view;
49         WebKitWebInspector *inspector;
50         char *title, *linkhover;
51         const char *needle;
52         gint progress;
53         struct Client *next;
54         gboolean zoomed, fullscreen, isinspecting, sslfailed;
55 } Client;
56
57 typedef struct {
58         guint mod;
59         guint keyval;
60         void (*func)(Client *c, const Arg *arg);
61         const Arg arg;
62 } Key;
63
64 typedef struct {
65         SoupCookieJarText parent_instance;
66         int lock;
67 } CookieJar;
68
69 typedef struct {
70         SoupCookieJarTextClass parent_class;
71 } CookieJarClass;
72
73 G_DEFINE_TYPE(CookieJar, cookiejar, SOUP_TYPE_COOKIE_JAR_TEXT)
74
75 typedef struct {
76         char *regex;
77         char *style;
78         regex_t re;
79 } SiteStyle;
80
81 static Display *dpy;
82 static Atom atoms[AtomLast];
83 static Client *clients = NULL;
84 static GdkNativeWindow embed = 0;
85 static gboolean showxid = FALSE;
86 static char winid[64];
87 static gboolean usingproxy = 0;
88 static char togglestat[9];
89 static char pagestat[3];
90 static GTlsDatabase *tlsdb;
91 static int policysel = 0;
92 static char *stylefile = NULL;
93 static SoupCache *diskcache = NULL;
94
95 static void addaccelgroup(Client *c);
96 static void beforerequest(WebKitWebView *w, WebKitWebFrame *f,
97                 WebKitWebResource *r, WebKitNetworkRequest *req,
98                 WebKitNetworkResponse *resp, Client *c);
99 static char *buildpath(const char *path);
100 static gboolean buttonrelease(WebKitWebView *web, GdkEventButton *e,
101                 GList *gl);
102 static void cleanup(void);
103 static void clipboard(Client *c, const Arg *arg);
104
105 /* Cookiejar implementation */
106 static void cookiejar_changed(SoupCookieJar *self, SoupCookie *old_cookie,
107                 SoupCookie *new_cookie);
108 static void cookiejar_finalize(GObject *self);
109 static SoupCookieJarAcceptPolicy cookiepolicy_get(void);
110 static SoupCookieJar *cookiejar_new(const char *filename, gboolean read_only,
111                 SoupCookieJarAcceptPolicy policy);
112 static void cookiejar_set_property(GObject *self, guint prop_id,
113                 const GValue *value, GParamSpec *pspec);
114 static char cookiepolicy_set(const SoupCookieJarAcceptPolicy p);
115
116 static char *copystr(char **str, const char *src);
117 static WebKitWebView *createwindow(WebKitWebView *v, WebKitWebFrame *f,
118                 Client *c);
119 static gboolean decidedownload(WebKitWebView *v, WebKitWebFrame *f,
120                 WebKitNetworkRequest *r, gchar *m,  WebKitWebPolicyDecision *p,
121                 Client *c);
122 static gboolean decidewindow(WebKitWebView *v, WebKitWebFrame *f,
123                 WebKitNetworkRequest *r, WebKitWebNavigationAction *n,
124                 WebKitWebPolicyDecision *p, Client *c);
125 static gboolean deletion_interface(WebKitWebView *view,
126                 WebKitDOMHTMLElement *arg1, Client *c);
127 static void destroyclient(Client *c);
128 static void destroywin(GtkWidget* w, Client *c);
129 static void die(const char *errstr, ...);
130 static void eval(Client *c, const Arg *arg);
131 static void find(Client *c, const Arg *arg);
132 static void fullscreen(Client *c, const Arg *arg);
133 static void geopolicyrequested(WebKitWebView *v, WebKitWebFrame *f,
134                 WebKitGeolocationPolicyDecision *d, Client *c);
135 static const char *getatom(Client *c, int a);
136 static void gettogglestat(Client *c);
137 static void getpagestat(Client *c);
138 static char *geturi(Client *c);
139 static gchar *getstyle(const char *uri);
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,
153                 GObject *obj, guint key, GdkModifierType mods,
154                 Client *c);
155 static void linkhover(WebKitWebView *v, const char* t, const char* l,
156                 Client *c);
157 static void loadstatuschange(WebKitWebView *view, GParamSpec *pspec,
158                 Client *c);
159 static void loaduri(Client *c, const Arg *arg);
160 static void navigate(Client *c, const Arg *arg);
161 static Client *newclient(void);
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, Client *c);
166 static void menuactivate(GtkMenuItem *item, Client *c);
167 static void print(Client *c, const Arg *arg);
168 static GdkFilterReturn processx(GdkXEvent *xevent, GdkEvent *event,
169                 gpointer d);
170 static void progresschange(WebKitWebView *view, GParamSpec *pspec, Client *c);
171 static void reload(Client *c, const Arg *arg);
172 static void scroll_h(Client *c, const Arg *arg);
173 static void scroll_v(Client *c, const Arg *arg);
174 static void scroll(GtkAdjustment *a, const Arg *arg);
175 static void setatom(Client *c, int a, const char *v);
176 static void setup(void);
177 static void sigchld(int unused);
178 static void source(Client *c, const Arg *arg);
179 static void spawn(Client *c, const Arg *arg);
180 static void stop(Client *c, const Arg *arg);
181 static void titlechange(WebKitWebView *view, GParamSpec *pspec, Client *c);
182 static void toggle(Client *c, const Arg *arg);
183 static void togglecookiepolicy(Client *c, const Arg *arg);
184 static void togglegeolocation(Client *c, const Arg *arg);
185 static void togglescrollbars(Client *c, const Arg *arg);
186 static void togglestyle(Client *c, const Arg *arg);
187 static void updatetitle(Client *c);
188 static void updatewinid(Client *c);
189 static void usage(void);
190 static void windowobjectcleared(GtkWidget *w, WebKitWebFrame *frame,
191                 JSContextRef js, JSObjectRef win, Client *c);
192 static void zoom(Client *c, const Arg *arg);
193
194 /* configuration, allows nested code to access above variables */
195 #include "config.h"
196
197 static void
198 addaccelgroup(Client *c) {
199         int i;
200         GtkAccelGroup *group = gtk_accel_group_new();
201         GClosure *closure;
202
203         for(i = 0; i < LENGTH(keys); i++) {
204                 closure = g_cclosure_new(G_CALLBACK(keypress), c, NULL);
205                 gtk_accel_group_connect(group, keys[i].keyval, keys[i].mod,
206                                 0, closure);
207         }
208         gtk_window_add_accel_group(GTK_WINDOW(c->win), group);
209 }
210
211 static void
212 beforerequest(WebKitWebView *w, WebKitWebFrame *f, WebKitWebResource *r,
213                 WebKitNetworkRequest *req, WebKitNetworkResponse *resp,
214                 Client *c) {
215         const gchar *uri = webkit_network_request_get_uri(req);
216
217         if(g_str_has_suffix(uri, "/favicon.ico"))
218                 webkit_network_request_set_uri(req, "about:blank");
219
220         if(!g_str_has_prefix(uri, "http://") \
221                         && !g_str_has_prefix(uri, "https://") \
222                         && !g_str_has_prefix(uri, "about:") \
223                         && !g_str_has_prefix(uri, "file://") \
224                         && !g_str_has_prefix(uri, "data:") \
225                         && strlen(uri) > 0) {
226                 handleplumb(c, w, uri);
227         }
228 }
229
230 static char *
231 buildpath(const char *path) {
232         char *apath, *p;
233         FILE *f;
234
235         /* creating directory */
236         if(path[0] == '/') {
237                 apath = g_strdup(path);
238         } else if(path[0] == '~') {
239                 if(path[1] == '/') {
240                         apath = g_strconcat(g_get_home_dir(), &path[1], NULL);
241                 } else {
242                         apath = g_strconcat(g_get_home_dir(), "/",
243                                         &path[1], NULL);
244                 }
245         } else {
246                 apath = g_strconcat(g_get_current_dir(), "/", path, NULL);
247         }
248
249         if((p = strrchr(apath, '/'))) {
250                 *p = '\0';
251                 g_mkdir_with_parents(apath, 0700);
252                 g_chmod(apath, 0700); /* in case it existed */
253                 *p = '/';
254         }
255         /* creating file (gives error when apath ends with "/") */
256         if((f = fopen(apath, "a"))) {
257                 g_chmod(apath, 0600); /* always */
258                 fclose(f);
259         }
260
261         return apath;
262 }
263
264 static gboolean
265 buttonrelease(WebKitWebView *web, GdkEventButton *e, GList *gl) {
266         WebKitHitTestResultContext context;
267         WebKitHitTestResult *result = webkit_web_view_get_hit_test_result(web,
268                         e);
269         Arg arg;
270
271         g_object_get(result, "context", &context, NULL);
272         if(context & WEBKIT_HIT_TEST_RESULT_CONTEXT_LINK) {
273                 if(e->button == 2 ||
274                                 (e->button == 1 && CLEANMASK(e->state) == CLEANMASK(MODKEY))) {
275                         g_object_get(result, "link-uri", &arg.v, NULL);
276                         newwindow(NULL, &arg, e->state & GDK_CONTROL_MASK);
277                         return true;
278                 }
279         }
280         return false;
281 }
282
283 static void
284 cleanup(void) {
285         if (diskcache) {
286                 soup_cache_flush(diskcache);
287                 soup_cache_dump(diskcache);
288         }
289         while(clients)
290                 destroyclient(clients);
291         g_free(cookiefile);
292         g_free(scriptfile);
293         g_free(stylefile);
294 }
295
296 static void
297 cookiejar_changed(SoupCookieJar *self, SoupCookie *old_cookie,
298                 SoupCookie *new_cookie) {
299         flock(COOKIEJAR(self)->lock, LOCK_EX);
300         if(new_cookie && !new_cookie->expires && sessiontime) {
301                 soup_cookie_set_expires(new_cookie,
302                                 soup_date_new_from_now(sessiontime));
303         }
304         SOUP_COOKIE_JAR_CLASS(cookiejar_parent_class)->changed(self,
305                         old_cookie, new_cookie);
306         flock(COOKIEJAR(self)->lock, LOCK_UN);
307 }
308
309 static void
310 cookiejar_class_init(CookieJarClass *klass) {
311         SOUP_COOKIE_JAR_CLASS(klass)->changed = cookiejar_changed;
312         G_OBJECT_CLASS(klass)->get_property =
313                 G_OBJECT_CLASS(cookiejar_parent_class)->get_property;
314         G_OBJECT_CLASS(klass)->set_property = cookiejar_set_property;
315         G_OBJECT_CLASS(klass)->finalize = cookiejar_finalize;
316         g_object_class_override_property(G_OBJECT_CLASS(klass), 1, "filename");
317 }
318
319 static void
320 cookiejar_finalize(GObject *self) {
321         close(COOKIEJAR(self)->lock);
322         G_OBJECT_CLASS(cookiejar_parent_class)->finalize(self);
323 }
324
325 static void
326 cookiejar_init(CookieJar *self) {
327         self->lock = open(cookiefile, 0);
328 }
329
330 static SoupCookieJar *
331 cookiejar_new(const char *filename, gboolean read_only,
332                 SoupCookieJarAcceptPolicy policy) {
333         return g_object_new(COOKIEJAR_TYPE,
334                             SOUP_COOKIE_JAR_TEXT_FILENAME, filename,
335                             SOUP_COOKIE_JAR_READ_ONLY, read_only,
336                             SOUP_COOKIE_JAR_ACCEPT_POLICY, policy, NULL);
337 }
338
339 static void
340 cookiejar_set_property(GObject *self, guint prop_id, const GValue *value,
341                 GParamSpec *pspec) {
342         flock(COOKIEJAR(self)->lock, LOCK_SH);
343         G_OBJECT_CLASS(cookiejar_parent_class)->set_property(self, prop_id,
344                         value, pspec);
345         flock(COOKIEJAR(self)->lock, LOCK_UN);
346 }
347
348 static SoupCookieJarAcceptPolicy
349 cookiepolicy_get(void) {
350         switch(cookiepolicies[policysel]) {
351         case 'a':
352                 return SOUP_COOKIE_JAR_ACCEPT_NEVER;
353         case '@':
354                 return SOUP_COOKIE_JAR_ACCEPT_NO_THIRD_PARTY;
355         case 'A':
356         default:
357                 break;
358         }
359
360         return SOUP_COOKIE_JAR_ACCEPT_ALWAYS;
361 }
362
363 static char
364 cookiepolicy_set(const SoupCookieJarAcceptPolicy ep) {
365         switch(ep) {
366         case SOUP_COOKIE_JAR_ACCEPT_NEVER:
367                 return 'a';
368         case SOUP_COOKIE_JAR_ACCEPT_NO_THIRD_PARTY:
369                 return '@';
370         case SOUP_COOKIE_JAR_ACCEPT_ALWAYS:
371         default:
372                 break;
373         }
374
375         return 'A';
376 }
377
378 static void
379 evalscript(JSContextRef js, char *script, char* scriptname) {
380         JSStringRef jsscript, jsscriptname;
381         JSValueRef exception = NULL;
382
383         jsscript = JSStringCreateWithUTF8CString(script);
384         jsscriptname = JSStringCreateWithUTF8CString(scriptname);
385         JSEvaluateScript(js, jsscript, JSContextGetGlobalObject(js),
386                         jsscriptname, 0, &exception);
387         JSStringRelease(jsscript);
388         JSStringRelease(jsscriptname);
389 }
390
391 static void
392 runscript(WebKitWebFrame *frame) {
393         char *script;
394         GError *error;
395
396         if(g_file_get_contents(scriptfile, &script, NULL, &error)) {
397                 evalscript(webkit_web_frame_get_global_context(frame),
398                                 script, scriptfile);
399         }
400 }
401
402 static void
403 clipboard(Client *c, const Arg *arg) {
404         gboolean paste = *(gboolean *)arg;
405
406         if(paste) {
407                 gtk_clipboard_request_text(
408                                 gtk_clipboard_get(GDK_SELECTION_PRIMARY),
409                                 pasteuri, c);
410         } else {
411                 gtk_clipboard_set_text(
412                                 gtk_clipboard_get(GDK_SELECTION_PRIMARY),
413                                 c->linkhover ? c->linkhover : geturi(c), -1);
414         }
415 }
416
417 static char *
418 copystr(char **str, const char *src) {
419         char *tmp;
420         tmp = g_strdup(src);
421
422         if(str && *str) {
423                 g_free(*str);
424                 *str = tmp;
425         }
426         return tmp;
427 }
428
429 static WebKitWebView *
430 createwindow(WebKitWebView  *v, WebKitWebFrame *f, Client *c) {
431         Client *n = newclient();
432         return n->view;
433 }
434
435 static gboolean
436 decidedownload(WebKitWebView *v, WebKitWebFrame *f, WebKitNetworkRequest *r,
437                 gchar *m,  WebKitWebPolicyDecision *p, Client *c) {
438         if(!webkit_web_view_can_show_mime_type(v, m)) {
439                 webkit_web_policy_decision_download(p);
440                 return TRUE;
441         }
442         return FALSE;
443 }
444
445 static gboolean
446 decidewindow(WebKitWebView *view, WebKitWebFrame *f, WebKitNetworkRequest *r,
447                 WebKitWebNavigationAction *n, WebKitWebPolicyDecision *p,
448                 Client *c) {
449         Arg arg;
450
451         if(webkit_web_navigation_action_get_reason(n) ==
452                         WEBKIT_WEB_NAVIGATION_REASON_LINK_CLICKED) {
453                 webkit_web_policy_decision_ignore(p);
454                 arg.v = (void *)webkit_network_request_get_uri(r);
455                 newwindow(NULL, &arg, 0);
456                 return TRUE;
457         }
458         return FALSE;
459 }
460
461 static gboolean
462 deletion_interface(WebKitWebView *view,
463                 WebKitDOMHTMLElement *arg1, Client *c) {
464         return FALSE;
465 }
466
467 static void
468 destroyclient(Client *c) {
469         Client *p;
470
471         webkit_web_view_stop_loading(c->view);
472         gtk_widget_destroy(GTK_WIDGET(c->view));
473         gtk_widget_destroy(c->scroll);
474         gtk_widget_destroy(c->vbox);
475         gtk_widget_destroy(c->win);
476
477         for(p = clients; p && p->next != c; p = p->next);
478         if(p) {
479                 p->next = c->next;
480         } else {
481                 clients = c->next;
482         }
483         free(c);
484         if(clients == NULL)
485                 gtk_main_quit();
486 }
487
488 static void
489 destroywin(GtkWidget* w, Client *c) {
490         destroyclient(c);
491 }
492
493 static void
494 die(const char *errstr, ...) {
495         va_list ap;
496
497         va_start(ap, errstr);
498         vfprintf(stderr, errstr, ap);
499         va_end(ap);
500         exit(EXIT_FAILURE);
501 }
502
503 static void
504 find(Client *c, const Arg *arg) {
505         const char *s;
506
507         s = getatom(c, AtomFind);
508         gboolean forward = *(gboolean *)arg;
509         webkit_web_view_search_text(c->view, s, FALSE, forward, TRUE);
510 }
511
512 static void
513 fullscreen(Client *c, const Arg *arg) {
514         if(c->fullscreen) {
515                 gtk_window_unfullscreen(GTK_WINDOW(c->win));
516         } else {
517                 gtk_window_fullscreen(GTK_WINDOW(c->win));
518         }
519         c->fullscreen = !c->fullscreen;
520 }
521
522 static void
523 geopolicyrequested(WebKitWebView *v, WebKitWebFrame *f,
524                 WebKitGeolocationPolicyDecision *d, Client *c) {
525         if(allowgeolocation) {
526                 webkit_geolocation_policy_allow(d);
527         } else {
528                 webkit_geolocation_policy_deny(d);
529         }
530 }
531
532 static const char *
533 getatom(Client *c, int a) {
534         static char buf[BUFSIZ];
535         Atom adummy;
536         int idummy;
537         unsigned long ldummy;
538         unsigned char *p = NULL;
539
540         XGetWindowProperty(dpy, GDK_WINDOW_XID(GTK_WIDGET(c->win)->window),
541                         atoms[a], 0L, BUFSIZ, False, XA_STRING,
542                         &adummy, &idummy, &ldummy, &ldummy, &p);
543         if(p) {
544                 strncpy(buf, (char *)p, LENGTH(buf)-1);
545         } else {
546                 buf[0] = '\0';
547         }
548         XFree(p);
549
550         return buf;
551 }
552
553 static char *
554 geturi(Client *c) {
555         char *uri;
556
557         if(!(uri = (char *)webkit_web_view_get_uri(c->view)))
558                 uri = "about:blank";
559         return uri;
560 }
561
562 static gchar *
563 getstyle(const char *uri) {
564         int i;
565
566         for(i = 0; i < LENGTH(styles); i++) {
567                 if(styles[i].regex && !regexec(&(styles[i].re), uri, 0,
568                                         NULL, 0)) {
569                         return g_strconcat("file://", styles[i].style, NULL);
570                 }
571         }
572         return g_strdup("");
573 }
574
575 static void
576 handleplumb(Client *c, WebKitWebView *w, const gchar *uri) {
577         Arg arg;
578
579         webkit_web_view_stop_loading(w);
580         arg = (Arg)PLUMB((char *)uri);
581         spawn(c, &arg);
582 }
583
584 static gboolean
585 initdownload(WebKitWebView *view, WebKitDownload *o, Client *c) {
586         Arg arg;
587
588         updatewinid(c);
589         arg = (Arg)DOWNLOAD((char *)webkit_download_get_uri(o), geturi(c));
590         spawn(c, &arg);
591         return FALSE;
592 }
593
594 static void
595 inspector(Client *c, const Arg *arg) {
596         if(c->isinspecting) {
597                 webkit_web_inspector_close(c->inspector);
598         } else {
599                 webkit_web_inspector_show(c->inspector);
600         }
601 }
602
603 static WebKitWebView *
604 inspector_new(WebKitWebInspector *i, WebKitWebView *v, Client *c) {
605         return WEBKIT_WEB_VIEW(webkit_web_view_new());
606 }
607
608 static gboolean
609 inspector_show(WebKitWebInspector *i, Client *c) {
610         WebKitWebView *w;
611
612         if(c->isinspecting)
613                 return false;
614
615         w = webkit_web_inspector_get_web_view(i);
616         gtk_paned_pack2(GTK_PANED(c->pane), GTK_WIDGET(w), TRUE, TRUE);
617         gtk_widget_show(GTK_WIDGET(w));
618         c->isinspecting = true;
619
620         return true;
621 }
622
623 static gboolean
624 inspector_close(WebKitWebInspector *i, Client *c) {
625         GtkWidget *w;
626
627         if(!c->isinspecting)
628                 return false;
629
630         w = GTK_WIDGET(webkit_web_inspector_get_web_view(i));
631         gtk_widget_hide(w);
632         gtk_widget_destroy(w);
633         c->isinspecting = false;
634
635         return true;
636 }
637
638 static void
639 inspector_finished(WebKitWebInspector *i, Client *c) {
640         g_free(c->inspector);
641 }
642
643 static gboolean
644 keypress(GtkAccelGroup *group, GObject *obj,
645                 guint key, GdkModifierType mods, Client *c) {
646         guint i;
647         gboolean processed = FALSE;
648
649         mods = CLEANMASK(mods);
650         key = gdk_keyval_to_lower(key);
651         updatewinid(c);
652         for(i = 0; i < LENGTH(keys); i++) {
653                 if(key == keys[i].keyval
654                                 && mods == keys[i].mod
655                                 && keys[i].func) {
656                         keys[i].func(c, &(keys[i].arg));
657                         processed = TRUE;
658                 }
659         }
660
661         return processed;
662 }
663
664 static void
665 linkhover(WebKitWebView *v, const char* t, const char* l, Client *c) {
666         if(l) {
667                 c->linkhover = copystr(&c->linkhover, l);
668         } else if(c->linkhover) {
669                 free(c->linkhover);
670                 c->linkhover = NULL;
671         }
672         updatetitle(c);
673 }
674
675 static void
676 loadstatuschange(WebKitWebView *view, GParamSpec *pspec, Client *c) {
677         WebKitWebFrame *frame;
678         WebKitWebDataSource *src;
679         WebKitNetworkRequest *request;
680         WebKitWebSettings *set = webkit_web_view_get_settings(c->view);
681         SoupMessage *msg;
682         char *uri;
683
684         switch(webkit_web_view_get_load_status (c->view)) {
685         case WEBKIT_LOAD_COMMITTED:
686                 uri = geturi(c);
687                 if(strstr(uri, "https://") == uri) {
688                         frame = webkit_web_view_get_main_frame(c->view);
689                         src = webkit_web_frame_get_data_source(frame);
690                         request = webkit_web_data_source_get_request(src);
691                         msg = webkit_network_request_get_message(request);
692                         c->sslfailed = !(soup_message_get_flags(msg)
693                                         & SOUP_MESSAGE_CERTIFICATE_TRUSTED);
694                 }
695                 setatom(c, AtomUri, uri);
696
697                 if(stylefile == NULL && enablestyles) {
698                         g_object_set(G_OBJECT(set), "user-stylesheet-uri",
699                                         getstyle(uri), NULL);
700                 }
701                 break;
702         case WEBKIT_LOAD_FINISHED:
703                 c->progress = 100;
704                 updatetitle(c);
705                 if (diskcache) {
706                         soup_cache_flush(diskcache);
707                         soup_cache_dump(diskcache);
708                 }
709                 break;
710         default:
711                 break;
712         }
713 }
714
715 static void
716 loaduri(Client *c, const Arg *arg) {
717         char *u = NULL, *rp;
718         const char *uri = (char *)arg->v;
719         Arg a = { .b = FALSE };
720         struct stat st;
721
722         if(strcmp(uri, "") == 0)
723                 return;
724
725         /* In case it's a file path. */
726         if(stat(uri, &st) == 0) {
727                 rp = realpath(uri, NULL);
728                 u = g_strdup_printf("file://%s", rp);
729                 free(rp);
730         } else {
731                 u = g_strrstr(uri, "://") ? g_strdup(uri)
732                         : g_strdup_printf("http://%s", uri);
733         }
734
735         setatom(c, AtomUri, uri);
736
737         /* prevents endless loop */
738         if(strcmp(u, geturi(c)) == 0) {
739                 reload(c, &a);
740         } else {
741                 webkit_web_view_load_uri(c->view, u);
742                 c->progress = 0;
743                 c->title = copystr(&c->title, u);
744                 updatetitle(c);
745         }
746         g_free(u);
747 }
748
749 static void
750 navigate(Client *c, const Arg *arg) {
751         int steps = *(int *)arg;
752         webkit_web_view_go_back_or_forward(c->view, steps);
753 }
754
755 static Client *
756 newclient(void) {
757         Client *c;
758         WebKitWebSettings *settings;
759         WebKitWebFrame *frame;
760         GdkGeometry hints = { 1, 1 };
761         GdkScreen *screen;
762         gdouble dpi;
763         char *uri = NULL, *ua;
764
765         if(!(c = calloc(1, sizeof(Client))))
766                 die("Cannot malloc!\n");
767
768         c->title = NULL;
769         c->progress = 100;
770
771         /* Window */
772         if(embed) {
773                 c->win = gtk_plug_new(embed);
774         } else {
775                 c->win = gtk_window_new(GTK_WINDOW_TOPLEVEL);
776
777                 /* TA:  20091214:  Despite what the GNOME docs say, the ICCCM
778                  * is always correct, so we should still call this function.
779                  * But when doing so, we *must* differentiate between a
780                  * WM_CLASS and a resource on the window.  By convention, the
781                  * window class (WM_CLASS) is capped, while the resource is in
782                  * lowercase.   Both these values come as a pair.
783                  */
784                 gtk_window_set_wmclass(GTK_WINDOW(c->win), "surf", "Surf");
785
786                 /* TA:  20091214:  And set the role here as well -- so that
787                  * sessions can pick this up.
788                  */
789                 gtk_window_set_role(GTK_WINDOW(c->win), "Surf");
790         }
791         gtk_window_set_default_size(GTK_WINDOW(c->win), 800, 600);
792         g_signal_connect(G_OBJECT(c->win),
793                         "destroy",
794                         G_CALLBACK(destroywin), c);
795
796         if(!kioskmode)
797                 addaccelgroup(c);
798
799         /* Pane */
800         c->pane = gtk_vpaned_new();
801
802         /* VBox */
803         c->vbox = gtk_vbox_new(FALSE, 0);
804         gtk_paned_pack1(GTK_PANED(c->pane), c->vbox, TRUE, TRUE);
805
806         /* Webview */
807         c->view = WEBKIT_WEB_VIEW(webkit_web_view_new());
808
809         g_signal_connect(G_OBJECT(c->view),
810                         "notify::title",
811                         G_CALLBACK(titlechange), c);
812         g_signal_connect(G_OBJECT(c->view),
813                         "hovering-over-link",
814                         G_CALLBACK(linkhover), c);
815         g_signal_connect(G_OBJECT(c->view),
816                         "geolocation-policy-decision-requested",
817                         G_CALLBACK(geopolicyrequested), c);
818         g_signal_connect(G_OBJECT(c->view),
819                         "create-web-view",
820                         G_CALLBACK(createwindow), c);
821         g_signal_connect(G_OBJECT(c->view),
822                         "new-window-policy-decision-requested",
823                         G_CALLBACK(decidewindow), c);
824         g_signal_connect(G_OBJECT(c->view),
825                         "mime-type-policy-decision-requested",
826                         G_CALLBACK(decidedownload), c);
827         g_signal_connect(G_OBJECT(c->view),
828                         "window-object-cleared",
829                         G_CALLBACK(windowobjectcleared), c);
830         g_signal_connect(G_OBJECT(c->view),
831                         "notify::load-status",
832                         G_CALLBACK(loadstatuschange), c);
833         g_signal_connect(G_OBJECT(c->view),
834                         "notify::progress",
835                         G_CALLBACK(progresschange), c);
836         g_signal_connect(G_OBJECT(c->view),
837                         "download-requested",
838                         G_CALLBACK(initdownload), c);
839         g_signal_connect(G_OBJECT(c->view),
840                         "button-release-event",
841                         G_CALLBACK(buttonrelease), c);
842         g_signal_connect(G_OBJECT(c->view),
843                         "context-menu",
844                         G_CALLBACK(contextmenu), c);
845         g_signal_connect(G_OBJECT(c->view),
846                         "resource-request-starting",
847                         G_CALLBACK(beforerequest), c);
848         g_signal_connect(G_OBJECT(c->view),
849                         "should-show-delete-interface-for-element",
850                         G_CALLBACK(deletion_interface), c);
851
852         /* Scrolled Window */
853         c->scroll = gtk_scrolled_window_new(NULL, NULL);
854
855         frame = webkit_web_view_get_main_frame(WEBKIT_WEB_VIEW(c->view));
856         g_signal_connect(G_OBJECT(frame), "scrollbars-policy-changed",
857                         G_CALLBACK(gtk_true), NULL);
858
859         if(!enablescrollbars) {
860                 gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(c->scroll),
861                                 GTK_POLICY_NEVER, GTK_POLICY_NEVER);
862         } else {
863                 gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(c->scroll),
864                                 GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);
865         }
866
867         /* Arranging */
868         gtk_container_add(GTK_CONTAINER(c->scroll), GTK_WIDGET(c->view));
869         gtk_container_add(GTK_CONTAINER(c->win), c->pane);
870         gtk_container_add(GTK_CONTAINER(c->vbox), c->scroll);
871
872         /* Setup */
873         gtk_box_set_child_packing(GTK_BOX(c->vbox), c->scroll, TRUE,
874                         TRUE, 0, GTK_PACK_START);
875         gtk_widget_grab_focus(GTK_WIDGET(c->view));
876         gtk_widget_show(c->pane);
877         gtk_widget_show(c->vbox);
878         gtk_widget_show(c->scroll);
879         gtk_widget_show(GTK_WIDGET(c->view));
880         gtk_widget_show(c->win);
881         gtk_window_set_geometry_hints(GTK_WINDOW(c->win), NULL, &hints,
882                         GDK_HINT_MIN_SIZE);
883         gdk_window_set_events(GTK_WIDGET(c->win)->window, GDK_ALL_EVENTS_MASK);
884         gdk_window_add_filter(GTK_WIDGET(c->win)->window, processx, c);
885         webkit_web_view_set_full_content_zoom(c->view, TRUE);
886
887         runscript(frame);
888
889         settings = webkit_web_view_get_settings(c->view);
890         if(!(ua = getenv("SURF_USERAGENT")))
891                 ua = useragent;
892         g_object_set(G_OBJECT(settings), "user-agent", ua, NULL);
893         if (stylefile != NULL) {
894                 uri = g_strconcat("file://", stylefile, NULL);
895                 g_object_set(G_OBJECT(settings), "user-stylesheet-uri", uri, NULL);
896         }
897         g_object_set(G_OBJECT(settings), "auto-load-images", loadimages,
898                         NULL);
899         g_object_set(G_OBJECT(settings), "enable-plugins", enableplugins,
900                         NULL);
901         g_object_set(G_OBJECT(settings), "enable-scripts", enablescripts,
902                         NULL);
903         g_object_set(G_OBJECT(settings), "enable-spatial-navigation",
904                         enablespatialbrowsing, NULL);
905         g_object_set(G_OBJECT(settings), "enable-developer-extras",
906                         enableinspector, NULL);
907         g_object_set(G_OBJECT(settings), "enable-default-context-menu",
908                         kioskmode ^ 1, NULL);
909         g_object_set(G_OBJECT(settings), "default-font-size",
910                         defaultfontsize, NULL);
911         g_object_set(G_OBJECT(settings), "resizable-text-areas",
912                         1, NULL);
913
914         /*
915          * While stupid, CSS specifies that a pixel represents 1/96 of an inch.
916          * This ensures websites are not unusably small with a high DPI screen.
917          * It is equivalent to firefox's "layout.css.devPixelsPerPx" setting.
918          */
919         if(zoomto96dpi) {
920                 screen = gdk_window_get_screen(GTK_WIDGET(c->win)->window);
921                 dpi = gdk_screen_get_resolution(screen);
922                 if(dpi != -1) {
923                         g_object_set(G_OBJECT(settings), "enforce-96-dpi", true,
924                                         NULL);
925                         webkit_web_view_set_zoom_level(c->view, dpi/96);
926                 }
927         }
928         /* This might conflict with _zoomto96dpi_. */
929         if(zoomlevel != 1.0)
930                 webkit_web_view_set_zoom_level(c->view, zoomlevel);
931
932         if(enableinspector) {
933                 c->inspector = WEBKIT_WEB_INSPECTOR(
934                                 webkit_web_view_get_inspector(c->view));
935                 g_signal_connect(G_OBJECT(c->inspector), "inspect-web-view",
936                                 G_CALLBACK(inspector_new), c);
937                 g_signal_connect(G_OBJECT(c->inspector), "show-window",
938                                 G_CALLBACK(inspector_show), c);
939                 g_signal_connect(G_OBJECT(c->inspector), "close-window",
940                                 G_CALLBACK(inspector_close), c);
941                 g_signal_connect(G_OBJECT(c->inspector), "finished",
942                                 G_CALLBACK(inspector_finished), c);
943                 c->isinspecting = false;
944         }
945
946         if(runinfullscreen) {
947                 c->fullscreen = 0;
948                 fullscreen(c, NULL);
949         }
950
951         if(stylefile != NULL)
952                 g_free(uri);
953
954         setatom(c, AtomFind, "");
955         setatom(c, AtomUri, "about:blank");
956         if(hidebackground)
957                 webkit_web_view_set_transparent(c->view, TRUE);
958
959         c->next = clients;
960         clients = c;
961
962         if(showxid) {
963                 gdk_display_sync(gtk_widget_get_display(c->win));
964                 printf("%u\n",
965                         (guint)GDK_WINDOW_XID(GTK_WIDGET(c->win)->window));
966                 fflush(NULL);
967                 if (fclose(stdout) != 0) {
968                         die("Error closing stdout");
969                 }
970         }
971
972         return c;
973 }
974
975 static void
976 newwindow(Client *c, const Arg *arg, gboolean noembed) {
977         guint i = 0;
978         const char *cmd[18], *uri;
979         const Arg a = { .v = (void *)cmd };
980         char tmp[64];
981
982         cmd[i++] = argv0;
983         cmd[i++] = "-a";
984         cmd[i++] = cookiepolicies;
985         if(!enablescrollbars)
986                 cmd[i++] = "-b";
987         if(embed && !noembed) {
988                 cmd[i++] = "-e";
989                 snprintf(tmp, LENGTH(tmp), "%u", (int)embed);
990                 cmd[i++] = tmp;
991         }
992         if(!allowgeolocation)
993                 cmd[i++] = "-g";
994         if(!loadimages)
995                 cmd[i++] = "-i";
996         if(kioskmode)
997                 cmd[i++] = "-k";
998         if(!enableplugins)
999                 cmd[i++] = "-p";
1000         if(!enablescripts)
1001                 cmd[i++] = "-s";
1002         if(showxid)
1003                 cmd[i++] = "-x";
1004         if(enablediskcache)
1005                 cmd[i++] = "-D";
1006         cmd[i++] = "-c";
1007         cmd[i++] = cookiefile;
1008         cmd[i++] = "--";
1009         uri = arg->v ? (char *)arg->v : c->linkhover;
1010         if(uri)
1011                 cmd[i++] = uri;
1012         cmd[i++] = NULL;
1013         spawn(NULL, &a);
1014 }
1015
1016 static gboolean
1017 contextmenu(WebKitWebView *view, GtkWidget *menu, WebKitHitTestResult *target,
1018                 gboolean keyboard, Client *c) {
1019         GList *items = gtk_container_get_children(GTK_CONTAINER(GTK_MENU(menu)));
1020
1021         for(GList *l = items; l; l = l->next) {
1022                 g_signal_connect(l->data, "activate", G_CALLBACK(menuactivate), c);
1023         }
1024
1025         g_list_free(items);
1026         return FALSE;
1027 }
1028
1029 static void
1030 menuactivate(GtkMenuItem *item, Client *c) {
1031         /*
1032          * context-menu-action-2000     open link
1033          * context-menu-action-1        open link in window
1034          * context-menu-action-2        download linked file
1035          * context-menu-action-3        copy link location
1036          * context-menu-action-7        copy image address
1037          * context-menu-action-13       reload
1038          * context-menu-action-10       back
1039          * context-menu-action-11       forward
1040          * context-menu-action-12       stop
1041          */
1042
1043         GtkAction *a = NULL;
1044         const char *name, *uri;
1045         GtkClipboard *prisel, *clpbrd;
1046
1047         a = gtk_activatable_get_related_action(GTK_ACTIVATABLE(item));
1048         if(a == NULL)
1049                 return;
1050
1051         name = gtk_action_get_name(a);
1052         if(!g_strcmp0(name, "context-menu-action-3")) {
1053                 prisel = gtk_clipboard_get(GDK_SELECTION_PRIMARY);
1054                 gtk_clipboard_set_text(prisel, c->linkhover, -1);
1055         } else if(!g_strcmp0(name, "context-menu-action-7")) {
1056                 prisel = gtk_clipboard_get(GDK_SELECTION_PRIMARY);
1057                 clpbrd = gtk_clipboard_get(GDK_SELECTION_CLIPBOARD);
1058                 uri = gtk_clipboard_wait_for_text(clpbrd);
1059                 if(uri)
1060                         gtk_clipboard_set_text(prisel, uri, -1);
1061         }
1062 }
1063
1064 static void
1065 pasteuri(GtkClipboard *clipboard, const char *text, gpointer d) {
1066         Arg arg = {.v = text };
1067         if(text != NULL)
1068                 loaduri((Client *) d, &arg);
1069 }
1070
1071 static void
1072 print(Client *c, const Arg *arg) {
1073         webkit_web_frame_print(webkit_web_view_get_main_frame(c->view));
1074 }
1075
1076 static GdkFilterReturn
1077 processx(GdkXEvent *e, GdkEvent *event, gpointer d) {
1078         Client *c = (Client *)d;
1079         XPropertyEvent *ev;
1080         Arg arg;
1081
1082         if(((XEvent *)e)->type == PropertyNotify) {
1083                 ev = &((XEvent *)e)->xproperty;
1084                 if(ev->state == PropertyNewValue) {
1085                         if(ev->atom == atoms[AtomFind]) {
1086                                 arg.b = TRUE;
1087                                 find(c, &arg);
1088
1089                                 return GDK_FILTER_REMOVE;
1090                         } else if(ev->atom == atoms[AtomGo]) {
1091                                 arg.v = getatom(c, AtomGo);
1092                                 loaduri(c, &arg);
1093
1094                                 return GDK_FILTER_REMOVE;
1095                         }
1096                 }
1097         }
1098         return GDK_FILTER_CONTINUE;
1099 }
1100
1101 static void
1102 progresschange(WebKitWebView *view, GParamSpec *pspec, Client *c) {
1103         c->progress = webkit_web_view_get_progress(c->view) * 100;
1104         updatetitle(c);
1105 }
1106
1107 static void
1108 reload(Client *c, const Arg *arg) {
1109         gboolean nocache = *(gboolean *)arg;
1110         if(nocache) {
1111                  webkit_web_view_reload_bypass_cache(c->view);
1112         } else {
1113                  webkit_web_view_reload(c->view);
1114         }
1115 }
1116
1117 static void
1118 scroll_h(Client *c, const Arg *arg) {
1119         scroll(gtk_scrolled_window_get_hadjustment(
1120                                 GTK_SCROLLED_WINDOW(c->scroll)), arg);
1121 }
1122
1123 static void
1124 scroll_v(Client *c, const Arg *arg) {
1125         scroll(gtk_scrolled_window_get_vadjustment(
1126                                 GTK_SCROLLED_WINDOW(c->scroll)), arg);
1127 }
1128
1129 static void
1130 scroll(GtkAdjustment *a, const Arg *arg) {
1131         gdouble v;
1132
1133         v = gtk_adjustment_get_value(a);
1134         switch(arg->i) {
1135         case +10000:
1136         case -10000:
1137                 v += gtk_adjustment_get_page_increment(a) *
1138                         (arg->i / 10000);
1139                 break;
1140         case +20000:
1141         case -20000:
1142         default:
1143                 v += gtk_adjustment_get_step_increment(a) * arg->i;
1144         }
1145
1146         v = MAX(v, 0.0);
1147         v = MIN(v, gtk_adjustment_get_upper(a) -
1148                         gtk_adjustment_get_page_size(a));
1149         gtk_adjustment_set_value(a, v);
1150 }
1151
1152 static void
1153 setatom(Client *c, int a, const char *v) {
1154         XSync(dpy, False);
1155         XChangeProperty(dpy, GDK_WINDOW_XID(GTK_WIDGET(c->win)->window),
1156                         atoms[a], XA_STRING, 8, PropModeReplace,
1157                         (unsigned char *)v, strlen(v) + 1);
1158 }
1159
1160 static void
1161 setup(void) {
1162         int i;
1163         char *proxy;
1164         char *new_proxy;
1165         SoupURI *puri;
1166         SoupSession *s;
1167         GError *error = NULL;
1168
1169         /* clean up any zombies immediately */
1170         sigchld(0);
1171         gtk_init(NULL, NULL);
1172
1173         dpy = GDK_DISPLAY();
1174
1175         /* atoms */
1176         atoms[AtomFind] = XInternAtom(dpy, "_SURF_FIND", False);
1177         atoms[AtomGo] = XInternAtom(dpy, "_SURF_GO", False);
1178         atoms[AtomUri] = XInternAtom(dpy, "_SURF_URI", False);
1179
1180         /* dirs and files */
1181         cookiefile = buildpath(cookiefile);
1182         scriptfile = buildpath(scriptfile);
1183         cachefolder = buildpath(cachefolder);
1184         styledir = buildpath(styledir);
1185         if(stylefile == NULL && enablestyles) {
1186                 for(i = 0; i < LENGTH(styles); i++) {
1187                         if(regcomp(&(styles[i].re), styles[i].regex,
1188                                                 REG_EXTENDED)) {
1189                                 fprintf(stderr,
1190                                         "Could not compile regex: %s\n",
1191                                         styles[i].regex);
1192                                 styles[i].regex = NULL;
1193                         }
1194                         styles[i].style = buildpath(
1195                                         g_strconcat(styledir,
1196                                                 styles[i].style, NULL));
1197                 }
1198         } else {
1199                 stylefile = buildpath(stylefile);
1200         }
1201
1202         /* request handler */
1203         s = webkit_get_default_session();
1204
1205         /* cookie jar */
1206         soup_session_add_feature(s,
1207                         SOUP_SESSION_FEATURE(cookiejar_new(cookiefile, FALSE,
1208                                         cookiepolicy_get())));
1209
1210         /* disk cache */
1211         if(enablediskcache) {
1212                 diskcache = soup_cache_new(cachefolder, SOUP_CACHE_SINGLE_USER);
1213                 soup_cache_set_max_size(diskcache, diskcachebytes);
1214                 soup_cache_load(diskcache);
1215                 soup_session_add_feature(s, SOUP_SESSION_FEATURE(diskcache));
1216         }
1217
1218         /* ssl */
1219         tlsdb = g_tls_file_database_new(cafile, &error);
1220
1221         if(error) {
1222                 g_warning("Error loading SSL database %s: %s", cafile, error->message);
1223                 g_error_free(error);
1224         }
1225         g_object_set(G_OBJECT(s), "tls-database", tlsdb, NULL);
1226         g_object_set(G_OBJECT(s), "ssl-strict", strictssl, NULL);
1227
1228         /* proxy */
1229         if((proxy = getenv("http_proxy")) && strcmp(proxy, "")) {
1230                 new_proxy = g_strrstr(proxy, "http://") ? g_strdup(proxy) :
1231                         g_strdup_printf("http://%s", proxy);
1232                 puri = soup_uri_new(new_proxy);
1233                 g_object_set(G_OBJECT(s), "proxy-uri", puri, NULL);
1234                 soup_uri_free(puri);
1235                 g_free(new_proxy);
1236                 usingproxy = 1;
1237         }
1238 }
1239
1240 static void
1241 sigchld(int unused) {
1242         if(signal(SIGCHLD, sigchld) == SIG_ERR)
1243                 die("Can't install SIGCHLD handler");
1244         while(0 < waitpid(-1, NULL, WNOHANG));
1245 }
1246
1247 static void
1248 source(Client *c, const Arg *arg) {
1249         Arg a = { .b = FALSE };
1250         gboolean s;
1251
1252         s = webkit_web_view_get_view_source_mode(c->view);
1253         webkit_web_view_set_view_source_mode(c->view, !s);
1254         reload(c, &a);
1255 }
1256
1257 static void
1258 spawn(Client *c, const Arg *arg) {
1259         if(fork() == 0) {
1260                 if(dpy)
1261                         close(ConnectionNumber(dpy));
1262                 setsid();
1263                 execvp(((char **)arg->v)[0], (char **)arg->v);
1264                 fprintf(stderr, "surf: execvp %s", ((char **)arg->v)[0]);
1265                 perror(" failed");
1266                 exit(0);
1267         }
1268 }
1269
1270 static void
1271 eval(Client *c, const Arg *arg) {
1272         WebKitWebFrame *frame = webkit_web_view_get_main_frame(c->view);
1273         evalscript(webkit_web_frame_get_global_context(frame),
1274                         ((char **)arg->v)[0], "");
1275 }
1276
1277 static void
1278 stop(Client *c, const Arg *arg) {
1279         webkit_web_view_stop_loading(c->view);
1280 }
1281
1282 static void
1283 titlechange(WebKitWebView *view, GParamSpec *pspec, Client *c) {
1284         const gchar *t = webkit_web_view_get_title(view);
1285         if (t) {
1286                 c->title = copystr(&c->title, t);
1287                 updatetitle(c);
1288         }
1289 }
1290
1291 static void
1292 toggle(Client *c, const Arg *arg) {
1293         WebKitWebSettings *settings;
1294         char *name = (char *)arg->v;
1295         gboolean value;
1296         Arg a = { .b = FALSE };
1297
1298         settings = webkit_web_view_get_settings(c->view);
1299         g_object_get(G_OBJECT(settings), name, &value, NULL);
1300         g_object_set(G_OBJECT(settings), name, !value, NULL);
1301
1302         reload(c, &a);
1303 }
1304
1305 static void
1306 togglecookiepolicy(Client *c, const Arg *arg) {
1307         SoupCookieJar *jar;
1308         SoupCookieJarAcceptPolicy policy;
1309
1310         jar = SOUP_COOKIE_JAR(
1311                         soup_session_get_feature(
1312                                 webkit_get_default_session(),
1313                                 SOUP_TYPE_COOKIE_JAR));
1314         g_object_get(G_OBJECT(jar), "accept-policy", &policy, NULL);
1315
1316         policysel++;
1317         if(policysel >= strlen(cookiepolicies))
1318                 policysel = 0;
1319
1320         g_object_set(G_OBJECT(jar), "accept-policy",
1321                         cookiepolicy_get(), NULL);
1322
1323         updatetitle(c);
1324         /* Do not reload. */
1325 }
1326
1327 static void
1328 togglegeolocation(Client *c, const Arg *arg) {
1329         Arg a = { .b = FALSE };
1330
1331         allowgeolocation ^= 1;
1332
1333         reload(c, &a);
1334 }
1335
1336 static void
1337 twitch(Client *c, const Arg *arg) {
1338         GtkAdjustment *a;
1339         gdouble v;
1340
1341         a = gtk_scrolled_window_get_vadjustment(
1342                         GTK_SCROLLED_WINDOW(c->scroll));
1343
1344         v = gtk_adjustment_get_value(a);
1345
1346         v += arg->i;
1347
1348         v = MAX(v, 0.0);
1349         v = MIN(v, gtk_adjustment_get_upper(a) -
1350                         gtk_adjustment_get_page_size(a));
1351         gtk_adjustment_set_value(a, v);
1352 }
1353
1354 static void
1355 togglescrollbars(Client *c, const Arg *arg) {
1356         GtkPolicyType vspolicy;
1357         Arg a;
1358
1359         gtk_scrolled_window_get_policy(GTK_SCROLLED_WINDOW(c->scroll), NULL, &vspolicy);
1360
1361         if(vspolicy == GTK_POLICY_AUTOMATIC) {
1362                 gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(c->scroll),
1363                                 GTK_POLICY_NEVER, GTK_POLICY_NEVER);
1364         } else {
1365                 gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(c->scroll),
1366                                 GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);
1367                 a.i = +1;
1368                 twitch(c, &a);
1369                 a.i = -1;
1370                 twitch(c, &a);
1371         }
1372 }
1373
1374 static void
1375 togglestyle(Client *c, const Arg *arg) {
1376         WebKitWebSettings *settings = webkit_web_view_get_settings(c->view);
1377         char *uri;
1378
1379         g_object_get(G_OBJECT(settings), "user-stylesheet-uri", &uri, NULL);
1380         if(stylefile == NULL && enablestyles) {
1381                 uri = (uri && uri[0])? g_strdup("") : getstyle(geturi(c));
1382         } else {
1383                 uri = uri[0]? g_strdup("") : g_strconcat("file://",
1384                                 stylefile, NULL);
1385         }
1386         g_object_set(G_OBJECT(settings), "user-stylesheet-uri", uri, NULL);
1387
1388         updatetitle(c);
1389 }
1390
1391 static void
1392 gettogglestat(Client *c){
1393         gboolean value;
1394         char *uri;
1395         int p = 0;
1396         WebKitWebSettings *settings = webkit_web_view_get_settings(c->view);
1397
1398         togglestat[p++] = cookiepolicy_set(cookiepolicy_get());
1399
1400         g_object_get(G_OBJECT(settings), "enable-caret-browsing",
1401                         &value, NULL);
1402         togglestat[p++] = value? 'C': 'c';
1403
1404         togglestat[p++] = allowgeolocation? 'G': 'g';
1405
1406         togglestat[p++] = enablediskcache? 'D': 'd';
1407
1408         g_object_get(G_OBJECT(settings), "auto-load-images", &value, NULL);
1409         togglestat[p++] = value? 'I': 'i';
1410
1411         g_object_get(G_OBJECT(settings), "enable-scripts", &value, NULL);
1412         togglestat[p++] = value? 'S': 's';
1413
1414         g_object_get(G_OBJECT(settings), "enable-plugins", &value, NULL);
1415         togglestat[p++] = value? 'V': 'v';
1416
1417         g_object_get(G_OBJECT(settings), "user-stylesheet-uri", &uri, NULL);
1418         togglestat[p++] = (uri && uri[0]) ? 'M': 'm';
1419
1420         togglestat[p] = '\0';
1421 }
1422
1423 static void
1424 getpagestat(Client *c) {
1425         const char *uri = geturi(c);
1426
1427         if(strstr(uri, "https://") == uri) {
1428                 pagestat[0] = c->sslfailed ? 'U' : 'T';
1429         } else {
1430                 pagestat[0] = '-';
1431         }
1432
1433         pagestat[1] = usingproxy ? 'P' : '-';
1434         pagestat[2] = '\0';
1435
1436 }
1437
1438 static void
1439 updatetitle(Client *c) {
1440         char *t;
1441
1442         if(showindicators) {
1443                 gettogglestat(c);
1444                 getpagestat(c);
1445
1446                 if(c->linkhover) {
1447                         t = g_strdup_printf("%s:%s | %s", togglestat,
1448                                         pagestat, c->linkhover);
1449                 } else if(c->progress != 100) {
1450                         t = g_strdup_printf("[%i%%] %s:%s | %s", c->progress,
1451                                         togglestat, pagestat,
1452                                         (c->title == NULL)? "" : c->title);
1453                 } else {
1454                         t = g_strdup_printf("%s:%s | %s", togglestat, pagestat,
1455                                         (c->title == NULL)? "" : c->title);
1456                 }
1457
1458                 gtk_window_set_title(GTK_WINDOW(c->win), t);
1459                 g_free(t);
1460         } else {
1461                 gtk_window_set_title(GTK_WINDOW(c->win),
1462                                 (c->title == NULL)? "" : c->title);
1463         }
1464 }
1465
1466 static void
1467 updatewinid(Client *c) {
1468         snprintf(winid, LENGTH(winid), "%u",
1469                         (int)GDK_WINDOW_XID(GTK_WIDGET(c->win)->window));
1470 }
1471
1472 static void
1473 usage(void) {
1474         die("usage: %s [-bBfFgGiIkKnNpPsSvx]"
1475                 " [-a cookiepolicies ] "
1476                 " [-c cookiefile] [-e xid] [-r scriptfile]"
1477                 " [-t stylefile] [-u useragent] [-z zoomlevel]"
1478                 " [uri]\n", basename(argv0));
1479 }
1480
1481 static void
1482 windowobjectcleared(GtkWidget *w, WebKitWebFrame *frame, JSContextRef js,
1483                 JSObjectRef win, Client *c) {
1484         runscript(frame);
1485 }
1486
1487 static void
1488 zoom(Client *c, const Arg *arg) {
1489         c->zoomed = TRUE;
1490         if(arg->i < 0) {
1491                 /* zoom out */
1492                 webkit_web_view_zoom_out(c->view);
1493         } else if(arg->i > 0) {
1494                 /* zoom in */
1495                 webkit_web_view_zoom_in(c->view);
1496         } else {
1497                 /* reset */
1498                 c->zoomed = FALSE;
1499                 webkit_web_view_set_zoom_level(c->view, 1.0);
1500         }
1501 }
1502
1503 int
1504 main(int argc, char *argv[]) {
1505         Arg arg;
1506         Client *c;
1507
1508         memset(&arg, 0, sizeof(arg));
1509
1510         /* command line args */
1511         ARGBEGIN {
1512         case 'a':
1513                 cookiepolicies = EARGF(usage());
1514                 break;
1515         case 'b':
1516                 enablescrollbars = 0;
1517                 break;
1518         case 'B':
1519                 enablescrollbars = 1;
1520                 break;
1521         case 'c':
1522                 cookiefile = EARGF(usage());
1523                 break;
1524         case 'd':
1525                 enablediskcache = 0;
1526                 break;
1527         case 'D':
1528                 enablediskcache = 1;
1529                 break;
1530         case 'e':
1531                 embed = strtol(EARGF(usage()), NULL, 0);
1532                 break;
1533         case 'f':
1534                 runinfullscreen = 1;
1535                 break;
1536         case 'F':
1537                 runinfullscreen = 0;
1538                 break;
1539         case 'g':
1540                 allowgeolocation = 0;
1541                 break;
1542         case 'G':
1543                 allowgeolocation = 1;
1544                 break;
1545         case 'i':
1546                 loadimages = 0;
1547                 break;
1548         case 'I':
1549                 loadimages = 1;
1550                 break;
1551         case 'k':
1552                 kioskmode = 0;
1553                 break;
1554         case 'K':
1555                 kioskmode = 1;
1556                 break;
1557         case 'm':
1558                 enablestyles = 0;
1559                 break;
1560         case 'M':
1561                 enablestyles = 1;
1562                 break;
1563         case 'n':
1564                 enableinspector = 0;
1565                 break;
1566         case 'N':
1567                 enableinspector = 1;
1568                 break;
1569         case 'p':
1570                 enableplugins = 0;
1571                 break;
1572         case 'P':
1573                 enableplugins = 1;
1574                 break;
1575         case 'r':
1576                 scriptfile = EARGF(usage());
1577                 break;
1578         case 's':
1579                 enablescripts = 0;
1580                 break;
1581         case 'S':
1582                 enablescripts = 1;
1583                 break;
1584         case 't':
1585                 stylefile = EARGF(usage());
1586                 break;
1587         case 'u':
1588                 useragent = EARGF(usage());
1589                 break;
1590         case 'v':
1591                 die("surf-"VERSION", ©2009-2014 surf engineers, "
1592                                 "see LICENSE for details\n");
1593         case 'x':
1594                 showxid = TRUE;
1595                 break;
1596         case 'z':
1597                 zoomlevel = strtof(EARGF(usage()), NULL);
1598                 break;
1599         default:
1600                 usage();
1601         } ARGEND;
1602         if(argc > 0)
1603                 arg.v = argv[0];
1604
1605         setup();
1606         c = newclient();
1607         if(arg.v) {
1608                 loaduri(clients, &arg);
1609         } else {
1610                 updatetitle(c);
1611         }
1612
1613         gtk_main();
1614         cleanup();
1615
1616         return EXIT_SUCCESS;
1617 }
1618