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