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