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