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