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