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