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