Remove source(), it has been removed from webkit2gtk
[surf.git] / surf.c
1 /* See LICENSE file for copyright and license details.
2  *
3  * To understand surf, start reading main().
4  */
5 #include <signal.h>
6 #include <X11/X.h>
7 #include <X11/Xatom.h>
8 #include <gtk/gtkx.h>
9 #include <gtk/gtk.h>
10 #include <gdk/gdkx.h>
11 #include <gdk/gdk.h>
12 #include <gdk/gdkkeysyms.h>
13 #include <string.h>
14 #include <sys/types.h>
15 #include <sys/wait.h>
16 #include <unistd.h>
17 #include <limits.h>
18 #include <stdlib.h>
19 #include <stdio.h>
20 #include <webkit2/webkit2.h>
21 #include <glib/gstdio.h>
22 #include <JavaScriptCore/JavaScript.h>
23 #include <sys/file.h>
24 #include <libgen.h>
25 #include <stdarg.h>
26 #include <regex.h>
27 #include <pwd.h>
28 #include <string.h>
29
30 #include "arg.h"
31
32 char *argv0;
33
34 #define LENGTH(x)               (sizeof(x) / sizeof(x[0]))
35 #define CLEANMASK(mask)         (mask & (MODKEY|GDK_SHIFT_MASK))
36 #define COOKIEJAR_TYPE          (cookiejar_get_type ())
37 #define COOKIEJAR(obj)          (G_TYPE_CHECK_INSTANCE_CAST ((obj), COOKIEJAR_TYPE, CookieJar))
38
39 enum { AtomFind, AtomGo, AtomUri, AtomLast };
40 enum {
41         ClkDoc   = WEBKIT_HIT_TEST_RESULT_CONTEXT_DOCUMENT,
42         ClkLink  = WEBKIT_HIT_TEST_RESULT_CONTEXT_LINK,
43         ClkImg   = WEBKIT_HIT_TEST_RESULT_CONTEXT_IMAGE,
44         ClkMedia = WEBKIT_HIT_TEST_RESULT_CONTEXT_MEDIA,
45         ClkSel   = WEBKIT_HIT_TEST_RESULT_CONTEXT_SELECTION,
46         ClkEdit  = WEBKIT_HIT_TEST_RESULT_CONTEXT_EDITABLE,
47         ClkAny   = ClkDoc | ClkLink | ClkImg | ClkMedia | ClkSel | ClkEdit,
48 };
49
50 typedef union Arg Arg;
51 union Arg {
52         gboolean b;
53         gint i;
54         const void *v;
55 };
56
57 typedef struct Client {
58         GtkWidget *win, *scroll, *vbox, *pane;
59         Window xid;
60         WebKitWebView *view;
61         WebKitWebInspector *inspector;
62         char *title, *linkhover;
63         const char *needle;
64         gint progress;
65         struct Client *next;
66         gboolean zoomed, fullscreen, isinspecting, sslfailed;
67 } Client;
68
69 typedef struct {
70         guint mod;
71         guint keyval;
72         void (*func)(Client *c, const Arg *arg);
73         const Arg arg;
74 } Key;
75
76 typedef struct {
77         unsigned int click;
78         unsigned int mask;
79         guint button;
80         void (*func)(Client *c, const Arg *arg);
81         const Arg arg;
82 } Button;
83
84 typedef struct {
85         SoupCookieJarText parent_instance;
86         int lock;
87 } CookieJar;
88
89 typedef struct {
90         SoupCookieJarTextClass parent_class;
91 } CookieJarClass;
92
93 G_DEFINE_TYPE(CookieJar, cookiejar, SOUP_TYPE_COOKIE_JAR_TEXT)
94
95 typedef struct {
96         char *regex;
97         char *style;
98         regex_t re;
99 } SiteStyle;
100
101 static Display *dpy;
102 static Atom atoms[AtomLast];
103 static Client *clients = NULL;
104 static Window embed = 0;
105 static gboolean showxid = FALSE;
106 static char winid[64];
107 static char togglestat[9];
108 static char pagestat[3];
109 static GTlsDatabase *tlsdb;
110 static int policysel = 0;
111 static char *stylefile = NULL;
112 static SoupCache *diskcache = NULL;
113
114 static void addaccelgroup(Client *c);
115 static void beforerequest(WebKitWebView *w, WebKitWebFrame *f,
116                           WebKitWebResource *r, WebKitNetworkRequest *req,
117                           WebKitNetworkResponse *resp, Client *c);
118 static char *buildfile(const char *path);
119 static char *buildpath(const char *path);
120 static gboolean buttonrelease(WebKitWebView *web, GdkEventButton *e, Client *c);
121 static void cleanup(void);
122 static void clipboard(Client *c, const Arg *arg);
123
124 /* Cookiejar implementation */
125 static void cookiejar_changed(SoupCookieJar *self, SoupCookie *old_cookie,
126                               SoupCookie *new_cookie);
127 static void cookiejar_finalize(GObject *self);
128 static SoupCookieJarAcceptPolicy cookiepolicy_get(void);
129 static SoupCookieJar *cookiejar_new(const char *filename, gboolean read_only,
130                                     SoupCookieJarAcceptPolicy policy);
131 static void cookiejar_set_property(GObject *self, guint prop_id,
132     const GValue *value, GParamSpec *pspec);
133 static char cookiepolicy_set(const SoupCookieJarAcceptPolicy p);
134
135 static char *copystr(char **str, const char *src);
136 static WebKitWebView *createwindow(WebKitWebView *v, WebKitWebFrame *f,
137                                    Client *c);
138 static gboolean decidedownload(WebKitWebView *v, WebKitWebFrame *f,
139                                WebKitNetworkRequest *r, gchar *m,
140                                WebKitWebPolicyDecision *p, Client *c);
141 static gboolean decidewindow(WebKitWebView *v, WebKitWebFrame *f,
142                              WebKitNetworkRequest *r, WebKitWebNavigationAction
143                              *n, WebKitWebPolicyDecision *p, Client *c);
144 static gboolean deletion_interface(WebKitWebView *view,
145                                    WebKitDOMHTMLElement *arg1, Client *c);
146 static void destroyclient(Client *c);
147 static void destroywin(GtkWidget* w, Client *c);
148 static void die(const char *errstr, ...);
149 static void eval(Client *c, const Arg *arg);
150 static void find(Client *c, const Arg *arg);
151 static void fullscreen(Client *c, const Arg *arg);
152 static void geopolicyrequested(WebKitWebView *v, WebKitWebFrame *f,
153                                WebKitGeolocationPolicyDecision *d, Client *c);
154 static const char *getatom(Client *c, int a);
155 static void gettogglestat(Client *c);
156 static void getpagestat(Client *c);
157 static char *geturi(Client *c);
158 static const gchar *getstyle(const char *uri);
159 static void setstyle(Client *c, const char *style);
160
161 static void handleplumb(Client *c, WebKitWebView *w, const gchar *uri);
162
163 static gboolean initdownload(WebKitWebView *v, WebKitDownload *o, Client *c);
164
165 static void inspector(Client *c, const Arg *arg);
166 static WebKitWebView *inspector_new(WebKitWebInspector *i, WebKitWebView *v,
167                                     Client *c);
168 static gboolean inspector_show(WebKitWebInspector *i, Client *c);
169 static gboolean inspector_close(WebKitWebInspector *i, Client *c);
170 static void inspector_finished(WebKitWebInspector *i, Client *c);
171
172 static gboolean keypress(GtkAccelGroup *group, GObject *obj, guint key,
173                          GdkModifierType mods, Client *c);
174 static void linkhover(WebKitWebView *v, const char* t, const char* l,
175                       Client *c);
176 static void loadstatuschange(WebKitWebView *view, GParamSpec *pspec,
177                              Client *c);
178 static void loaduri(Client *c, const Arg *arg);
179 static void navigate(Client *c, const Arg *arg);
180 static Client *newclient(void);
181 static void newwindow(Client *c, const Arg *arg, gboolean noembed);
182 static void pasteuri(GtkClipboard *clipboard, const char *text, gpointer d);
183 static gboolean contextmenu(WebKitWebView *view, GtkWidget *menu,
184                             WebKitHitTestResult *target, gboolean keyboard,
185                             Client *c);
186 static void menuactivate(GtkMenuItem *item, Client *c);
187 static void print(Client *c, const Arg *arg);
188 static GdkFilterReturn processx(GdkXEvent *xevent, GdkEvent *event,
189                                 gpointer d);
190 static void progresschange(WebKitWebView *view, GParamSpec *pspec, Client *c);
191 static void linkopen(Client *c, const Arg *arg);
192 static void linkopenembed(Client *c, const Arg *arg);
193 static void reload(Client *c, const Arg *arg);
194 static void scroll_h(Client *c, const Arg *arg);
195 static void scroll_v(Client *c, const Arg *arg);
196 static void scroll(GtkAdjustment *a, const Arg *arg);
197 static void setatom(Client *c, int a, const char *v);
198 static void setup(void);
199 static void sigchld(int unused);
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, c->xid,
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         GdkWindow *gwin;
874         gdouble dpi;
875         char *ua;
876
877         if (!(c = calloc(1, sizeof(Client))))
878                 die("Cannot malloc!\n");
879
880         c->title = NULL;
881         c->progress = 100;
882
883         /* Window */
884         if (embed) {
885                 c->win = gtk_plug_new(embed);
886         } else {
887                 c->win = gtk_window_new(GTK_WINDOW_TOPLEVEL);
888
889                 /* TA:  20091214:  Despite what the GNOME docs say, the ICCCM
890                  * is always correct, so we should still call this function.
891                  * But when doing so, we *must* differentiate between a
892                  * WM_CLASS and a resource on the window.  By convention, the
893                  * window class (WM_CLASS) is capped, while the resource is in
894                  * lowercase.   Both these values come as a pair.
895                  */
896                 gtk_window_set_wmclass(GTK_WINDOW(c->win), "surf", "Surf");
897
898                 /* TA:  20091214:  And set the role here as well -- so that
899                  * sessions can pick this up.
900                  */
901                 gtk_window_set_role(GTK_WINDOW(c->win), "Surf");
902         }
903         gtk_window_set_default_size(GTK_WINDOW(c->win), 800, 600);
904         g_signal_connect(G_OBJECT(c->win),
905                          "destroy",
906                          G_CALLBACK(destroywin), c);
907         g_signal_connect(G_OBJECT(c->win),
908                          "leave_notify_event",
909                          G_CALLBACK(titlechangeleave), c);
910
911         if (!kioskmode)
912                 addaccelgroup(c);
913
914         /* Pane */
915         c->pane = gtk_paned_new(GTK_ORIENTATION_VERTICAL);
916
917         /* VBox */
918         c->vbox = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0);
919         gtk_paned_pack1(GTK_PANED(c->pane), c->vbox, TRUE, TRUE);
920
921         /* Webview */
922         c->view = WEBKIT_WEB_VIEW(webkit_web_view_new());
923
924         g_signal_connect(G_OBJECT(c->view),
925                          "notify::title",
926                          G_CALLBACK(titlechange), c);
927         g_signal_connect(G_OBJECT(c->view),
928                          "hovering-over-link",
929                          G_CALLBACK(linkhover), c);
930         g_signal_connect(G_OBJECT(c->view),
931                          "geolocation-policy-decision-requested",
932                          G_CALLBACK(geopolicyrequested), c);
933         g_signal_connect(G_OBJECT(c->view),
934                          "create-web-view",
935                          G_CALLBACK(createwindow), c);
936         g_signal_connect(G_OBJECT(c->view),
937                          "new-window-policy-decision-requested",
938                          G_CALLBACK(decidewindow), c);
939         g_signal_connect(G_OBJECT(c->view),
940                          "mime-type-policy-decision-requested",
941                          G_CALLBACK(decidedownload), c);
942         g_signal_connect(G_OBJECT(c->view),
943                          "window-object-cleared",
944                          G_CALLBACK(windowobjectcleared), c);
945         g_signal_connect(G_OBJECT(c->view),
946                          "notify::load-status",
947                          G_CALLBACK(loadstatuschange), c);
948         g_signal_connect(G_OBJECT(c->view),
949                          "notify::progress",
950                          G_CALLBACK(progresschange), c);
951         g_signal_connect(G_OBJECT(c->view),
952                          "download-requested",
953                          G_CALLBACK(initdownload), c);
954         g_signal_connect(G_OBJECT(c->view),
955                          "button-release-event",
956                          G_CALLBACK(buttonrelease), c);
957         g_signal_connect(G_OBJECT(c->view),
958                          "context-menu",
959                          G_CALLBACK(contextmenu), c);
960         g_signal_connect(G_OBJECT(c->view),
961                          "resource-request-starting",
962                          G_CALLBACK(beforerequest), c);
963         g_signal_connect(G_OBJECT(c->view),
964                          "should-show-delete-interface-for-element",
965                          G_CALLBACK(deletion_interface), c);
966
967         /* Scrolled Window */
968         c->scroll = gtk_scrolled_window_new(NULL, NULL);
969
970         frame = webkit_web_view_get_main_frame(WEBKIT_WEB_VIEW(c->view));
971         g_signal_connect(G_OBJECT(frame), "scrollbars-policy-changed",
972                          G_CALLBACK(gtk_true), NULL);
973
974         if (!enablescrollbars) {
975                 gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(c->scroll),
976                                                GTK_POLICY_NEVER,
977                                                GTK_POLICY_NEVER);
978         } else {
979                 gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(c->scroll),
980                                                GTK_POLICY_AUTOMATIC,
981                                                GTK_POLICY_AUTOMATIC);
982         }
983
984         /* Arranging */
985         gtk_container_add(GTK_CONTAINER(c->scroll), GTK_WIDGET(c->view));
986         gtk_container_add(GTK_CONTAINER(c->win), c->pane);
987         gtk_container_add(GTK_CONTAINER(c->vbox), c->scroll);
988
989         /* Setup */
990         gtk_box_set_child_packing(GTK_BOX(c->vbox), c->scroll, TRUE, TRUE, 0,
991                                   GTK_PACK_START);
992         gtk_widget_grab_focus(GTK_WIDGET(c->view));
993         gtk_widget_show(c->pane);
994         gtk_widget_show(c->vbox);
995         gtk_widget_show(c->scroll);
996         gtk_widget_show(GTK_WIDGET(c->view));
997         gtk_widget_show(c->win);
998         gwin = gtk_widget_get_window(GTK_WIDGET(c->win));
999         c->xid = gdk_x11_window_get_xid(gwin);
1000         gtk_window_set_geometry_hints(GTK_WINDOW(c->win), NULL, &hints,
1001                                       GDK_HINT_MIN_SIZE);
1002         gdk_window_set_events(gwin, GDK_ALL_EVENTS_MASK);
1003         gdk_window_add_filter(gwin, processx, c);
1004         webkit_web_view_set_full_content_zoom(c->view, TRUE);
1005
1006         runscript(frame);
1007
1008         settings = webkit_web_view_get_settings(c->view);
1009         if (!(ua = getenv("SURF_USERAGENT")))
1010                 ua = useragent;
1011         g_object_set(G_OBJECT(settings), "user-agent", ua, NULL);
1012         g_object_set(G_OBJECT(settings),
1013                      "auto-load-images", loadimages, NULL);
1014         g_object_set(G_OBJECT(settings),
1015                      "enable-plugins", enableplugins, NULL);
1016         g_object_set(G_OBJECT(settings),
1017                      "enable-scripts", enablescripts, NULL);
1018         g_object_set(G_OBJECT(settings),
1019                      "enable-spatial-navigation", enablespatialbrowsing, NULL);
1020         g_object_set(G_OBJECT(settings),
1021                      "enable-developer-extras", enableinspector, NULL);
1022         g_object_set(G_OBJECT(settings),
1023                      "enable-default-context-menu", kioskmode ^ 1, NULL);
1024         g_object_set(G_OBJECT(settings),
1025                      "default-font-size", defaultfontsize, NULL);
1026         g_object_set(G_OBJECT(settings),
1027                      "resizable-text-areas", 1, NULL);
1028         if (enablestyle)
1029                 setstyle(c, getstyle("about:blank"));
1030
1031         /*
1032          * While stupid, CSS specifies that a pixel represents 1/96 of an inch.
1033          * This ensures websites are not unusably small with a high DPI screen.
1034          * It is equivalent to firefox's "layout.css.devPixelsPerPx" setting.
1035          */
1036         if (zoomto96dpi) {
1037                 screen = gdk_window_get_screen(gwin);
1038                 dpi = gdk_screen_get_resolution(screen);
1039                 if (dpi != -1) {
1040                         g_object_set(G_OBJECT(settings),
1041                                      "enforce-96-dpi", true, NULL);
1042                         webkit_web_view_set_zoom_level(c->view, dpi/96);
1043                 }
1044         }
1045         /* This might conflict with _zoomto96dpi_. */
1046         if (zoomlevel != 1.0)
1047                 webkit_web_view_set_zoom_level(c->view, zoomlevel);
1048
1049         if (enableinspector) {
1050                 c->inspector = webkit_web_view_get_inspector(c->view);
1051                 g_signal_connect(G_OBJECT(c->inspector), "inspect-web-view",
1052                                  G_CALLBACK(inspector_new), c);
1053                 g_signal_connect(G_OBJECT(c->inspector), "show-window",
1054                                  G_CALLBACK(inspector_show), c);
1055                 g_signal_connect(G_OBJECT(c->inspector), "close-window",
1056                                  G_CALLBACK(inspector_close), c);
1057                 g_signal_connect(G_OBJECT(c->inspector), "finished",
1058                                  G_CALLBACK(inspector_finished), c);
1059                 c->isinspecting = false;
1060         }
1061
1062         if (runinfullscreen)
1063                 fullscreen(c, NULL);
1064
1065         setatom(c, AtomFind, "");
1066         setatom(c, AtomUri, "about:blank");
1067         if (hidebackground)
1068                 webkit_web_view_set_transparent(c->view, TRUE);
1069
1070         c->next = clients;
1071         clients = c;
1072
1073         if (showxid) {
1074                 gdk_display_sync(gtk_widget_get_display(c->win));
1075                 printf("%lu\n", c->xid);
1076                 fflush(NULL);
1077                 if (fclose(stdout) != 0) {
1078                         die("Error closing stdout");
1079                 }
1080         }
1081
1082         return c;
1083 }
1084
1085 void
1086 newwindow(Client *c, const Arg *arg, gboolean noembed)
1087 {
1088         guint i = 0;
1089         const char *cmd[18], *uri;
1090         const Arg a = { .v = (void *)cmd };
1091         char tmp[64];
1092
1093         cmd[i++] = argv0;
1094         cmd[i++] = "-a";
1095         cmd[i++] = cookiepolicies;
1096         if (!enablescrollbars)
1097                 cmd[i++] = "-b";
1098         if (embed && !noembed) {
1099                 cmd[i++] = "-e";
1100                 snprintf(tmp, LENGTH(tmp), "%u", (int)embed);
1101                 cmd[i++] = tmp;
1102         }
1103         if (!allowgeolocation)
1104                 cmd[i++] = "-g";
1105         if (!loadimages)
1106                 cmd[i++] = "-i";
1107         if (kioskmode)
1108                 cmd[i++] = "-k";
1109         if (!enableplugins)
1110                 cmd[i++] = "-p";
1111         if (!enablescripts)
1112                 cmd[i++] = "-s";
1113         if (showxid)
1114                 cmd[i++] = "-x";
1115         if (enablediskcache)
1116                 cmd[i++] = "-D";
1117         cmd[i++] = "-c";
1118         cmd[i++] = cookiefile;
1119         cmd[i++] = "--";
1120         uri = arg->v ? (char *)arg->v : c->linkhover;
1121         if (uri)
1122                 cmd[i++] = uri;
1123         cmd[i++] = NULL;
1124         spawn(NULL, &a);
1125 }
1126
1127 gboolean
1128 contextmenu(WebKitWebView *view, GtkWidget *menu, WebKitHitTestResult *target,
1129             gboolean keyboard, Client *c)
1130 {
1131         GList *items = gtk_container_get_children(GTK_CONTAINER(GTK_MENU(menu)));
1132
1133         for (GList *l = items; l; l = l->next)
1134                 g_signal_connect(l->data, "activate", G_CALLBACK(menuactivate), c);
1135
1136         g_list_free(items);
1137         return FALSE;
1138 }
1139
1140 void
1141 menuactivate(GtkMenuItem *item, Client *c)
1142 {
1143         /*
1144          * context-menu-action-2000 open link
1145          * context-menu-action-1    open link in window
1146          * context-menu-action-2    download linked file
1147          * context-menu-action-3    copy link location
1148          * context-menu-action-7    copy image address
1149          * context-menu-action-13   reload
1150          * context-menu-action-10   back
1151          * context-menu-action-11   forward
1152          * context-menu-action-12   stop
1153          */
1154
1155         const gchar *name, *uri;
1156         GtkClipboard *prisel, *clpbrd;
1157
1158         name = gtk_actionable_get_action_name(GTK_ACTIONABLE(item));
1159         if (name == NULL)
1160                 return;
1161
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, c->xid,
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 *styledirfile, *stylepath;
1294         SoupSession *s;
1295         GError *error = NULL;
1296
1297         /* clean up any zombies immediately */
1298         sigchld(0);
1299         gtk_init(NULL, NULL);
1300
1301         dpy = GDK_DISPLAY_XDISPLAY(gdk_display_get_default());
1302
1303         /* atoms */
1304         atoms[AtomFind] = XInternAtom(dpy, "_SURF_FIND", False);
1305         atoms[AtomGo] = XInternAtom(dpy, "_SURF_GO", False);
1306         atoms[AtomUri] = XInternAtom(dpy, "_SURF_URI", False);
1307
1308         /* dirs and files */
1309         cookiefile = buildfile(cookiefile);
1310         scriptfile = buildfile(scriptfile);
1311         cachefolder = buildpath(cachefolder);
1312         if (stylefile == NULL) {
1313                 styledir = buildpath(styledir);
1314                 for (i = 0; i < LENGTH(styles); i++) {
1315                         if (regcomp(&(styles[i].re), styles[i].regex,
1316                             REG_EXTENDED)) {
1317                                 fprintf(stderr,
1318                                         "Could not compile regex: %s\n",
1319                                         styles[i].regex);
1320                                 styles[i].regex = NULL;
1321                         }
1322                         styledirfile    = g_strconcat(styledir, "/",
1323                                                       styles[i].style, NULL);
1324                         stylepath       = buildfile(styledirfile);
1325                         styles[i].style = g_strconcat("file://", stylepath,
1326                                                       NULL);
1327                         g_free(styledirfile);
1328                         g_free(stylepath);
1329                 }
1330                 g_free(styledir);
1331         } else {
1332                 stylepath = buildfile(stylefile);
1333                 stylefile = g_strconcat("file://", stylepath, NULL);
1334                 g_free(stylepath);
1335         }
1336
1337         /* request handler */
1338         s = webkit_get_default_session();
1339
1340         /* cookie jar */
1341         soup_session_add_feature(s,
1342                                  SOUP_SESSION_FEATURE(cookiejar_new(cookiefile,
1343                                  FALSE, cookiepolicy_get())));
1344
1345         /* disk cache */
1346         if (enablediskcache) {
1347                 diskcache = soup_cache_new(cachefolder,
1348                                            SOUP_CACHE_SINGLE_USER);
1349                 soup_cache_set_max_size(diskcache, diskcachebytes);
1350                 soup_cache_load(diskcache);
1351                 soup_session_add_feature(s, SOUP_SESSION_FEATURE(diskcache));
1352         }
1353
1354         /* ssl */
1355         tlsdb = g_tls_file_database_new(cafile, &error);
1356
1357         if (error) {
1358                 g_warning("Error loading SSL database %s: %s", cafile,
1359                           error->message);
1360                 g_error_free(error);
1361         }
1362         g_object_set(G_OBJECT(s), "tls-database", tlsdb, NULL);
1363         g_object_set(G_OBJECT(s), "ssl-strict", strictssl, NULL);
1364 }
1365
1366 void
1367 sigchld(int unused)
1368 {
1369         if (signal(SIGCHLD, sigchld) == SIG_ERR)
1370                 die("Can't install SIGCHLD handler");
1371         while (0 < waitpid(-1, NULL, WNOHANG));
1372 }
1373
1374 void
1375 spawn(Client *c, const Arg *arg)
1376 {
1377         if (fork() == 0) {
1378                 if (dpy)
1379                         close(ConnectionNumber(dpy));
1380                 setsid();
1381                 execvp(((char **)arg->v)[0], (char **)arg->v);
1382                 fprintf(stderr, "surf: execvp %s", ((char **)arg->v)[0]);
1383                 perror(" failed");
1384                 exit(0);
1385         }
1386 }
1387
1388 void
1389 eval(Client *c, const Arg *arg)
1390 {
1391         WebKitWebFrame *frame = webkit_web_view_get_main_frame(c->view);
1392         evalscript(webkit_web_frame_get_global_context(frame),
1393                    ((char **)arg->v)[0], "");
1394 }
1395
1396 void
1397 stop(Client *c, const Arg *arg)
1398 {
1399         webkit_web_view_stop_loading(c->view);
1400 }
1401
1402 void
1403 titlechange(WebKitWebView *view, GParamSpec *pspec, Client *c)
1404 {
1405         const gchar *t = webkit_web_view_get_title(view);
1406         if (t) {
1407                 c->title = copystr(&c->title, t);
1408                 updatetitle(c);
1409         }
1410 }
1411
1412 void
1413 titlechangeleave(void *a, void *b, Client *c)
1414 {
1415         c->linkhover = NULL;
1416         updatetitle(c);
1417 }
1418
1419 void
1420 toggle(Client *c, const Arg *arg)
1421 {
1422         WebKitWebSettings *settings;
1423         char *name = (char *)arg->v;
1424         gboolean value;
1425         Arg a = { .b = FALSE };
1426
1427         settings = webkit_web_view_get_settings(c->view);
1428         g_object_get(G_OBJECT(settings), name, &value, NULL);
1429         g_object_set(G_OBJECT(settings), name, !value, NULL);
1430
1431         reload(c, &a);
1432 }
1433
1434 void
1435 togglecookiepolicy(Client *c, const Arg *arg)
1436 {
1437         SoupCookieJar *jar;
1438         SoupCookieJarAcceptPolicy policy;
1439
1440         jar = SOUP_COOKIE_JAR(soup_session_get_feature(
1441                               webkit_get_default_session(),
1442                               SOUP_TYPE_COOKIE_JAR));
1443         g_object_get(G_OBJECT(jar), "accept-policy", &policy, NULL);
1444
1445         policysel++;
1446         if (policysel >= strlen(cookiepolicies))
1447                 policysel = 0;
1448
1449         g_object_set(G_OBJECT(jar), "accept-policy", cookiepolicy_get(), NULL);
1450
1451         updatetitle(c);
1452         /* Do not reload. */
1453 }
1454
1455 void
1456 togglegeolocation(Client *c, const Arg *arg)
1457 {
1458         Arg a = { .b = FALSE };
1459
1460         allowgeolocation ^= 1;
1461         reload(c, &a);
1462 }
1463
1464 void
1465 twitch(Client *c, const Arg *arg)
1466 {
1467         GtkAdjustment *a;
1468         gdouble v;
1469
1470         a = gtk_scrolled_window_get_vadjustment(GTK_SCROLLED_WINDOW(
1471                                                 c->scroll));
1472
1473         v = gtk_adjustment_get_value(a);
1474
1475         v += arg->i;
1476
1477         v = MAX(v, 0.0);
1478         v = MIN(v, gtk_adjustment_get_upper(a) -
1479                 gtk_adjustment_get_page_size(a));
1480         gtk_adjustment_set_value(a, v);
1481 }
1482
1483 void
1484 togglescrollbars(Client *c, const Arg *arg)
1485 {
1486         GtkPolicyType vspolicy;
1487         Arg a;
1488
1489         gtk_scrolled_window_get_policy(GTK_SCROLLED_WINDOW(c->scroll), NULL,
1490                                        &vspolicy);
1491
1492         if (vspolicy == GTK_POLICY_AUTOMATIC) {
1493                 gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(c->scroll),
1494                                                GTK_POLICY_NEVER,
1495                                                GTK_POLICY_NEVER);
1496         } else {
1497                 gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(c->scroll),
1498                                                GTK_POLICY_AUTOMATIC,
1499                                                GTK_POLICY_AUTOMATIC);
1500                 a.i = +1;
1501                 twitch(c, &a);
1502                 a.i = -1;
1503                 twitch(c, &a);
1504         }
1505 }
1506
1507 void
1508 togglestyle(Client *c, const Arg *arg)
1509 {
1510         enablestyle = !enablestyle;
1511         setstyle(c, enablestyle ? getstyle(geturi(c)) : "");
1512
1513         updatetitle(c);
1514 }
1515
1516 void
1517 gettogglestat(Client *c)
1518 {
1519         gboolean value;
1520         int p = 0;
1521         WebKitWebSettings *settings = webkit_web_view_get_settings(c->view);
1522
1523         togglestat[p++] = cookiepolicy_set(cookiepolicy_get());
1524
1525         g_object_get(G_OBJECT(settings), "enable-caret-browsing", &value,
1526                      NULL);
1527         togglestat[p++] = value? 'C': 'c';
1528
1529         togglestat[p++] = allowgeolocation? 'G': 'g';
1530
1531         togglestat[p++] = enablediskcache? 'D': 'd';
1532
1533         g_object_get(G_OBJECT(settings), "auto-load-images", &value, NULL);
1534         togglestat[p++] = value? 'I': 'i';
1535
1536         g_object_get(G_OBJECT(settings), "enable-scripts", &value, NULL);
1537         togglestat[p++] = value? 'S': 's';
1538
1539         g_object_get(G_OBJECT(settings), "enable-plugins", &value, NULL);
1540         togglestat[p++] = value? 'V': 'v';
1541
1542         togglestat[p++] = enablestyle ? 'M': 'm';
1543
1544         togglestat[p] = '\0';
1545 }
1546
1547 void
1548 getpagestat(Client *c)
1549 {
1550         const char *uri = geturi(c);
1551
1552         if (strstr(uri, "https://") == uri)
1553                 pagestat[0] = c->sslfailed ? 'U' : 'T';
1554         else
1555                 pagestat[0] = '-';
1556
1557         pagestat[1] = '\0';
1558 }
1559
1560 void
1561 updatetitle(Client *c)
1562 {
1563         char *t;
1564
1565         if (showindicators) {
1566                 gettogglestat(c);
1567                 getpagestat(c);
1568
1569                 if (c->linkhover) {
1570                         t = g_strdup_printf("%s:%s | %s", togglestat, pagestat,
1571                                             c->linkhover);
1572                 } else if (c->progress != 100) {
1573                         t = g_strdup_printf("[%i%%] %s:%s | %s", c->progress,
1574                                             togglestat, pagestat,
1575                                             c->title == NULL ? "" : c->title);
1576                 } else {
1577                         t = g_strdup_printf("%s:%s | %s", togglestat, pagestat,
1578                                             c->title == NULL ? "" : c->title);
1579                 }
1580
1581                 gtk_window_set_title(GTK_WINDOW(c->win), t);
1582                 g_free(t);
1583         } else {
1584                 gtk_window_set_title(GTK_WINDOW(c->win), (c->title == NULL) ?
1585                                      "" : c->title);
1586         }
1587 }
1588
1589 void
1590 updatewinid(Client *c)
1591 {
1592         snprintf(winid, LENGTH(winid), "%lu", c->xid);
1593 }
1594
1595 void
1596 usage(void)
1597 {
1598         die("usage: %s [-bBdDfFgGiIkKmMnNpPsSvx] [-a cookiepolicies ] "
1599             "[-c cookiefile] [-e xid] [-r scriptfile] [-t stylefile] "
1600             "[-u useragent] [-z zoomlevel] [uri]\n", basename(argv0));
1601 }
1602
1603 void
1604 windowobjectcleared(GtkWidget *w, WebKitWebFrame *frame, JSContextRef js,
1605                     JSObjectRef win, Client *c)
1606 {
1607         runscript(frame);
1608 }
1609
1610 void
1611 zoom(Client *c, const Arg *arg)
1612 {
1613         c->zoomed = TRUE;
1614         if (arg->i < 0) {
1615                 /* zoom out */
1616                 webkit_web_view_zoom_out(c->view);
1617         } else if (arg->i > 0) {
1618                 /* zoom in */
1619                 webkit_web_view_zoom_in(c->view);
1620         } else {
1621                 /* reset */
1622                 c->zoomed = FALSE;
1623                 webkit_web_view_set_zoom_level(c->view, 1.0);
1624         }
1625 }
1626
1627 int
1628 main(int argc, char *argv[])
1629 {
1630         Arg arg;
1631         Client *c;
1632
1633         memset(&arg, 0, sizeof(arg));
1634
1635         /* command line args */
1636         ARGBEGIN {
1637         case 'a':
1638                 cookiepolicies = EARGF(usage());
1639                 break;
1640         case 'b':
1641                 enablescrollbars = 0;
1642                 break;
1643         case 'B':
1644                 enablescrollbars = 1;
1645                 break;
1646         case 'c':
1647                 cookiefile = EARGF(usage());
1648                 break;
1649         case 'd':
1650                 enablediskcache = 0;
1651                 break;
1652         case 'D':
1653                 enablediskcache = 1;
1654                 break;
1655         case 'e':
1656                 embed = strtol(EARGF(usage()), NULL, 0);
1657                 break;
1658         case 'f':
1659                 runinfullscreen = 0;
1660                 break;
1661         case 'F':
1662                 runinfullscreen = 1;
1663                 break;
1664         case 'g':
1665                 allowgeolocation = 0;
1666                 break;
1667         case 'G':
1668                 allowgeolocation = 1;
1669                 break;
1670         case 'i':
1671                 loadimages = 0;
1672                 break;
1673         case 'I':
1674                 loadimages = 1;
1675                 break;
1676         case 'k':
1677                 kioskmode = 0;
1678                 break;
1679         case 'K':
1680                 kioskmode = 1;
1681                 break;
1682         case 'm':
1683                 enablestyle = 0;
1684                 break;
1685         case 'M':
1686                 enablestyle = 1;
1687                 break;
1688         case 'n':
1689                 enableinspector = 0;
1690                 break;
1691         case 'N':
1692                 enableinspector = 1;
1693                 break;
1694         case 'p':
1695                 enableplugins = 0;
1696                 break;
1697         case 'P':
1698                 enableplugins = 1;
1699                 break;
1700         case 'r':
1701                 scriptfile = EARGF(usage());
1702                 break;
1703         case 's':
1704                 enablescripts = 0;
1705                 break;
1706         case 'S':
1707                 enablescripts = 1;
1708                 break;
1709         case 't':
1710                 stylefile = EARGF(usage());
1711                 break;
1712         case 'u':
1713                 useragent = EARGF(usage());
1714                 break;
1715         case 'v':
1716                 die("surf-"VERSION", ©2009-2015 surf engineers, "
1717                     "see LICENSE for details\n");
1718         case 'x':
1719                 showxid = TRUE;
1720                 break;
1721         case 'z':
1722                 zoomlevel = strtof(EARGF(usage()), NULL);
1723                 break;
1724         default:
1725                 usage();
1726         } ARGEND;
1727         if (argc > 0)
1728                 arg.v = argv[0];
1729
1730         setup();
1731         c = newclient();
1732         if (arg.v)
1733                 loaduri(clients, &arg);
1734         else
1735                 updatetitle(c);
1736
1737         gtk_main();
1738         cleanup();
1739
1740         return EXIT_SUCCESS;
1741 }
1742