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