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