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