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