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