Making more than one Modkey to work in keys.
[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
26 #include "arg.h"
27
28 char *argv0;
29
30 #define LENGTH(x)               (sizeof x / sizeof x[0])
31 #define CLEANMASK(mask)         (mask & (MODKEY|GDK_SHIFT_MASK))
32 #define COOKIEJAR_TYPE          (cookiejar_get_type ())
33 #define COOKIEJAR(obj)          (G_TYPE_CHECK_INSTANCE_CAST ((obj), COOKIEJAR_TYPE, CookieJar))
34
35 enum { AtomFind, AtomGo, AtomUri, AtomLast };
36
37 typedef union Arg Arg;
38 union Arg {
39         gboolean b;
40         gint i;
41         const void *v;
42 };
43
44 typedef struct Client {
45         GtkWidget *win, *scroll, *vbox, *indicator;
46         WebKitWebView *view;
47         WebKitWebInspector *inspector;
48         char *title, *linkhover;
49         const char *uri, *needle;
50         gint progress;
51         struct Client *next;
52         gboolean zoomed, fullscreen, isinspector, sslfailed;
53 } Client;
54
55 typedef struct {
56         char *label;
57         void (*func)(Client *c, const Arg *arg);
58         const Arg arg;
59 } Item;
60
61 typedef struct {
62         guint mod;
63         guint keyval;
64         void (*func)(Client *c, const Arg *arg);
65         const Arg arg;
66 } Key;
67
68 typedef struct {
69         SoupCookieJarText parent_instance;
70         int lock;
71 } CookieJar;
72
73 typedef struct {
74         SoupCookieJarTextClass parent_class;
75 } CookieJarClass;
76
77 G_DEFINE_TYPE(CookieJar, cookiejar, SOUP_TYPE_COOKIE_JAR_TEXT)
78
79 static Display *dpy;
80 static Atom atoms[AtomLast];
81 static Client *clients = NULL;
82 static GdkNativeWindow embed = 0;
83 static gboolean showxid = FALSE;
84 static char winid[64];
85 static gboolean usingproxy = 0;
86 static char togglestat[5];
87
88 static void beforerequest(WebKitWebView *w, WebKitWebFrame *f,
89                 WebKitWebResource *r, WebKitNetworkRequest *req,
90                 WebKitNetworkResponse *resp, gpointer d);
91 static char *buildpath(const char *path);
92 static gboolean buttonrelease(WebKitWebView *web, GdkEventButton *e,
93                 GList *gl);
94 static void cleanup(void);
95 static void clipboard(Client *c, const Arg *arg);
96
97 static void cookiejar_changed(SoupCookieJar *self, SoupCookie *old_cookie,
98                 SoupCookie *new_cookie);
99 static void cookiejar_finalize(GObject *self);
100 static SoupCookieJar *cookiejar_new(const char *filename, gboolean read_only);
101 static void cookiejar_set_property(GObject *self, guint prop_id,
102                 const GValue *value, GParamSpec *pspec);
103
104 static char *copystr(char **str, const char *src);
105 static WebKitWebView *createwindow(WebKitWebView *v, WebKitWebFrame *f,
106                 Client *c);
107 static gboolean decidedownload(WebKitWebView *v, WebKitWebFrame *f,
108                 WebKitNetworkRequest *r, gchar *m,  WebKitWebPolicyDecision *p,
109                 Client *c);
110 static gboolean decidewindow(WebKitWebView *v, WebKitWebFrame *f,
111                 WebKitNetworkRequest *r, WebKitWebNavigationAction *n,
112                 WebKitWebPolicyDecision *p, Client *c);
113 static void destroyclient(Client *c);
114 static void destroywin(GtkWidget* w, Client *c);
115 static void die(const char *errstr, ...);
116 static void drawindicator(Client *c);
117 static void eval(Client *c, const Arg *arg);
118 static gboolean exposeindicator(GtkWidget *w, GdkEventExpose *e, Client *c);
119 static void find(Client *c, const Arg *arg);
120 static void fullscreen(Client *c, const Arg *arg);
121 static const char *getatom(Client *c, int a);
122 static void gettogglestat(Client *c);
123 static char *geturi(Client *c);
124 static gboolean initdownload(WebKitWebView *v, WebKitDownload *o, Client *c);
125
126 static void inspector(Client *c, const Arg *arg);
127 static WebKitWebView *inspector_new(WebKitWebInspector *i, WebKitWebView *v,
128                 Client *c);
129 static gboolean inspector_show(WebKitWebInspector *i, Client *c);
130 static gboolean inspector_close(WebKitWebInspector *i, Client *c);
131 static void inspector_finished(WebKitWebInspector *i, Client *c);
132
133 static gboolean keypress(GtkWidget *w, GdkEventKey *ev, Client *c);
134 static void linkhover(WebKitWebView *v, const char* t, const char* l,
135                 Client *c);
136 static void loadstatuschange(WebKitWebView *view, GParamSpec *pspec,
137                 Client *c);
138 static void loaduri(Client *c, const Arg *arg);
139 static void navigate(Client *c, const Arg *arg);
140 static Client *newclient(void);
141 static void newwindow(Client *c, const Arg *arg, gboolean noembed);
142 static void pasteuri(GtkClipboard *clipboard, const char *text, gpointer d);
143 static void populatepopup(WebKitWebView *web, GtkMenu *menu, Client *c);
144 static void popupactivate(GtkMenuItem *menu, Client *);
145 static void print(Client *c, const Arg *arg);
146 static GdkFilterReturn processx(GdkXEvent *xevent, GdkEvent *event,
147                 gpointer d);
148 static void progresschange(WebKitWebView *view, GParamSpec *pspec, Client *c);
149 static void reload(Client *c, const Arg *arg);
150 static void scroll_h(Client *c, const Arg *arg);
151 static void scroll_v(Client *c, const Arg *arg);
152 static void scroll(GtkAdjustment *a, const Arg *arg);
153 static void setatom(Client *c, int a, const char *v);
154 static void setup(void);
155 static void sigchld(int unused);
156 static void source(Client *c, const Arg *arg);
157 static void spawn(Client *c, const Arg *arg);
158 static void stop(Client *c, const Arg *arg);
159 static void titlechange(WebKitWebView *v, WebKitWebFrame *frame,
160                 const char *title, Client *c);
161 static void toggle(Client *c, const Arg *arg);
162 static void update(Client *c);
163 static void updatewinid(Client *c);
164 static void usage(void);
165 static void windowobjectcleared(GtkWidget *w, WebKitWebFrame *frame,
166                 JSContextRef js, JSObjectRef win, Client *c);
167 static void zoom(Client *c, const Arg *arg);
168
169 /* configuration, allows nested code to access above variables */
170 #include "config.h"
171
172 static void
173 beforerequest(WebKitWebView *w, WebKitWebFrame *f, WebKitWebResource *r,
174                 WebKitNetworkRequest *req, WebKitNetworkResponse *resp,
175                 gpointer d) {
176         const gchar *uri = webkit_network_request_get_uri(req);
177         if(g_str_has_suffix(uri, "/favicon.ico"))
178                 webkit_network_request_set_uri(req, "about:blank");
179 }
180
181 static char *
182 buildpath(const char *path) {
183         char *apath, *p;
184         FILE *f;
185
186         /* creating directory */
187         if(path[0] == '/') {
188                 apath = g_strdup(path);
189         } else if(path[0] == '~') {
190                 if(path[1] == '/') {
191                         apath = g_strconcat(g_get_home_dir(), &path[1], NULL);
192                 } else {
193                         apath = g_strconcat(g_get_home_dir(), "/",
194                                         &path[1], NULL);
195                 }
196         } else {
197                 apath = g_strconcat(g_get_current_dir(), "/", path, NULL);
198         }
199
200         if((p = strrchr(apath, '/'))) {
201                 *p = '\0';
202                 g_mkdir_with_parents(apath, 0700);
203                 g_chmod(apath, 0700); /* in case it existed */
204                 *p = '/';
205         }
206         /* creating file (gives error when apath ends with "/") */
207         if((f = fopen(apath, "a"))) {
208                 g_chmod(apath, 0600); /* always */
209                 fclose(f);
210         }
211
212         return apath;
213 }
214
215 static gboolean
216 buttonrelease(WebKitWebView *web, GdkEventButton *e, GList *gl) {
217         WebKitHitTestResultContext context;
218         WebKitHitTestResult *result = webkit_web_view_get_hit_test_result(web,
219                         e);
220         Arg arg;
221
222         g_object_get(result, "context", &context, NULL);
223         if(context & WEBKIT_HIT_TEST_RESULT_CONTEXT_LINK) {
224                 if(e->button == 2) {
225                         g_object_get(result, "link-uri", &arg.v, NULL);
226                         newwindow(NULL, &arg, e->state & GDK_CONTROL_MASK);
227                         return true;
228                 }
229         }
230         return false;
231 }
232
233 static void
234 cleanup(void) {
235         while(clients)
236                 destroyclient(clients);
237         g_free(cookiefile);
238         g_free(scriptfile);
239         g_free(stylefile);
240 }
241
242 static void
243 cookiejar_changed(SoupCookieJar *self, SoupCookie *old_cookie,
244                 SoupCookie *new_cookie) {
245         flock(COOKIEJAR(self)->lock, LOCK_EX);
246         if(new_cookie && !new_cookie->expires && sessiontime) {
247                 soup_cookie_set_expires(new_cookie,
248                                 soup_date_new_from_now(sessiontime));
249         }
250         SOUP_COOKIE_JAR_CLASS(cookiejar_parent_class)->changed(self,
251                         old_cookie, new_cookie);
252         flock(COOKIEJAR(self)->lock, LOCK_UN);
253 }
254
255 static void
256 cookiejar_class_init(CookieJarClass *klass) {
257         SOUP_COOKIE_JAR_CLASS(klass)->changed = cookiejar_changed;
258         G_OBJECT_CLASS(klass)->get_property =
259                 G_OBJECT_CLASS(cookiejar_parent_class)->get_property;
260         G_OBJECT_CLASS(klass)->set_property = cookiejar_set_property;
261         G_OBJECT_CLASS(klass)->finalize = cookiejar_finalize;
262         g_object_class_override_property(G_OBJECT_CLASS(klass), 1, "filename");
263 }
264
265 static void
266 cookiejar_finalize(GObject *self) {
267         close(COOKIEJAR(self)->lock);
268         G_OBJECT_CLASS(cookiejar_parent_class)->finalize(self);
269 }
270
271 static void
272 cookiejar_init(CookieJar *self) {
273         self->lock = open(cookiefile, 0);
274 }
275
276 static SoupCookieJar *
277 cookiejar_new(const char *filename, gboolean read_only) {
278         return g_object_new(COOKIEJAR_TYPE,
279                             SOUP_COOKIE_JAR_TEXT_FILENAME, filename,
280                             SOUP_COOKIE_JAR_READ_ONLY, read_only, NULL);
281 }
282
283 static void
284 cookiejar_set_property(GObject *self, guint prop_id, const GValue *value,
285                 GParamSpec *pspec) {
286         flock(COOKIEJAR(self)->lock, LOCK_SH);
287         G_OBJECT_CLASS(cookiejar_parent_class)->set_property(self, prop_id,
288                         value, pspec);
289         flock(COOKIEJAR(self)->lock, LOCK_UN);
290 }
291
292 static void
293 evalscript(JSContextRef js, char *script, char* scriptname) {
294         JSStringRef jsscript, jsscriptname;
295         JSValueRef exception = NULL;
296
297         jsscript = JSStringCreateWithUTF8CString(script);
298         jsscriptname = JSStringCreateWithUTF8CString(scriptname);
299         JSEvaluateScript(js, jsscript, JSContextGetGlobalObject(js), jsscriptname, 0, &exception);
300         JSStringRelease(jsscript);
301         JSStringRelease(jsscriptname);
302 }
303
304 static void
305 runscript(WebKitWebFrame *frame) {
306         char *script;
307         GError *error;
308
309         if(g_file_get_contents(scriptfile, &script, NULL, &error)) {
310                 evalscript(webkit_web_frame_get_global_context(frame), script, scriptfile);
311         }
312 }
313
314 static void
315 clipboard(Client *c, const Arg *arg) {
316         gboolean paste = *(gboolean *)arg;
317
318         if(paste)
319                 gtk_clipboard_request_text(gtk_clipboard_get(GDK_SELECTION_PRIMARY), pasteuri, c);
320         else
321                 gtk_clipboard_set_text(gtk_clipboard_get(GDK_SELECTION_PRIMARY), c->linkhover ? c->linkhover : geturi(c), -1);
322 }
323
324 static char *
325 copystr(char **str, const char *src) {
326         char *tmp;
327         tmp = g_strdup(src);
328
329         if(str && *str) {
330                 g_free(*str);
331                 *str = tmp;
332         }
333         return tmp;
334 }
335
336 static WebKitWebView *
337 createwindow(WebKitWebView  *v, WebKitWebFrame *f, Client *c) {
338         Client *n = newclient();
339         return n->view;
340 }
341
342 static gboolean
343 decidedownload(WebKitWebView *v, WebKitWebFrame *f, WebKitNetworkRequest *r,
344                 gchar *m,  WebKitWebPolicyDecision *p, Client *c) {
345         if(!webkit_web_view_can_show_mime_type(v, m)) {
346                 webkit_web_policy_decision_download(p);
347                 return TRUE;
348         }
349         return FALSE;
350 }
351
352 static gboolean
353 decidewindow(WebKitWebView *view, WebKitWebFrame *f, WebKitNetworkRequest *r,
354                 WebKitWebNavigationAction *n, WebKitWebPolicyDecision *p,
355                 Client *c) {
356         Arg arg;
357
358         if(webkit_web_navigation_action_get_reason(n) ==
359                         WEBKIT_WEB_NAVIGATION_REASON_LINK_CLICKED) {
360                 webkit_web_policy_decision_ignore(p);
361                 arg.v = (void *)webkit_network_request_get_uri(r);
362                 newwindow(NULL, &arg, 0);
363                 return TRUE;
364         }
365         return FALSE;
366 }
367
368 static void
369 destroyclient(Client *c) {
370         Client *p;
371
372         webkit_web_view_stop_loading(c->view);
373         gtk_widget_destroy(c->indicator);
374         gtk_widget_destroy(GTK_WIDGET(c->view));
375         gtk_widget_destroy(c->scroll);
376         gtk_widget_destroy(c->vbox);
377         gtk_widget_destroy(c->win);
378
379         for(p = clients; p && p->next != c; p = p->next);
380         if(p) {
381                 p->next = c->next;
382         } else {
383                 clients = c->next;
384         }
385         free(c);
386         if(clients == NULL)
387                 gtk_main_quit();
388 }
389
390 static void
391 destroywin(GtkWidget* w, Client *c) {
392         destroyclient(c);
393 }
394
395 static void
396 die(const char *errstr, ...) {
397         va_list ap;
398
399         va_start(ap, errstr);
400         vfprintf(stderr, errstr, ap);
401         va_end(ap);
402         exit(EXIT_FAILURE);
403 }
404
405 static void
406 drawindicator(Client *c) {
407         gint width;
408         const char *uri;
409         char *colorname;
410         GtkWidget *w;
411         GdkGC *gc;
412         GdkColor fg;
413
414         uri = geturi(c);
415         w = c->indicator;
416         width = c->progress * w->allocation.width / 100;
417         gc = gdk_gc_new(w->window);
418         if(strstr(uri, "https://") == uri) {
419                 if(usingproxy) {
420                         colorname = c->sslfailed? progress_proxy_untrust :
421                                 progress_proxy_trust;
422                 } else {
423                         colorname = c->sslfailed? progress_untrust :
424                                 progress_trust;
425                 }
426         } else {
427                 if(usingproxy) {
428                         colorname = progress_proxy;
429                 } else {
430                         colorname = progress;
431                 }
432         }
433
434         gdk_color_parse(colorname, &fg);
435         gdk_gc_set_rgb_fg_color(gc, &fg);
436         gdk_draw_rectangle(w->window,
437                         w->style->bg_gc[GTK_WIDGET_STATE(w)],
438                         TRUE, 0, 0, w->allocation.width, w->allocation.height);
439         gdk_draw_rectangle(w->window, gc, TRUE, 0, 0, width,
440                         w->allocation.height);
441         g_object_unref(gc);
442 }
443
444 static gboolean
445 exposeindicator(GtkWidget *w, GdkEventExpose *e, Client *c) {
446         drawindicator(c);
447         return TRUE;
448 }
449
450 static void
451 find(Client *c, const Arg *arg) {
452         const char *s;
453
454         s = getatom(c, AtomFind);
455         gboolean forward = *(gboolean *)arg;
456         webkit_web_view_search_text(c->view, s, FALSE, forward, TRUE);
457 }
458
459 static void
460 fullscreen(Client *c, const Arg *arg) {
461         if(c->fullscreen) {
462                 gtk_window_unfullscreen(GTK_WINDOW(c->win));
463         } else {
464                 gtk_window_fullscreen(GTK_WINDOW(c->win));
465         }
466         c->fullscreen = !c->fullscreen;
467 }
468
469 static const char *
470 getatom(Client *c, int a) {
471         static char buf[BUFSIZ];
472         Atom adummy;
473         int idummy;
474         unsigned long ldummy;
475         unsigned char *p = NULL;
476
477         XGetWindowProperty(dpy, GDK_WINDOW_XID(GTK_WIDGET(c->win)->window),
478                         atoms[a], 0L, BUFSIZ, False, XA_STRING,
479                         &adummy, &idummy, &ldummy, &ldummy, &p);
480         if(p)
481                 strncpy(buf, (char *)p, LENGTH(buf)-1);
482         else
483                 buf[0] = '\0';
484         XFree(p);
485         return buf;
486 }
487
488 static char *
489 geturi(Client *c) {
490         char *uri;
491
492         if(!(uri = (char *)webkit_web_view_get_uri(c->view)))
493                 uri = "about:blank";
494         return uri;
495 }
496
497 static gboolean
498 initdownload(WebKitWebView *view, WebKitDownload *o, Client *c) {
499         Arg arg;
500
501         updatewinid(c);
502         arg = (Arg)DOWNLOAD((char *)webkit_download_get_uri(o), geturi(c));
503         spawn(c, &arg);
504         return FALSE;
505 }
506
507 static void
508 inspector(Client *c, const Arg *arg) {
509         if(c->isinspector)
510                 return;
511         webkit_web_inspector_show(c->inspector);
512 }
513
514 static WebKitWebView *
515 inspector_new(WebKitWebInspector *i, WebKitWebView *v, Client *c) {
516         Client *n = newclient();
517         n->isinspector = true;
518
519         return n->view;
520 }
521
522 static gboolean
523 inspector_show(WebKitWebInspector *i, Client *c) {
524         gtk_widget_show(GTK_WIDGET(webkit_web_inspector_get_web_view(i)));
525         return true;
526 }
527
528 static gboolean
529 inspector_close(WebKitWebInspector *i, Client *c) {
530         gtk_widget_hide(GTK_WIDGET(webkit_web_inspector_get_web_view(i)));
531         return true;
532 }
533
534 static void
535 inspector_finished(WebKitWebInspector *i, Client *c) {
536         g_free(c->inspector);
537 }
538
539 static gboolean
540 keypress(GtkWidget* w, GdkEventKey *ev, Client *c) {
541         guint i;
542         gboolean processed = FALSE;
543
544         updatewinid(c);
545         for(i = 0; i < LENGTH(keys); i++) {
546                 if(gdk_keyval_to_lower(ev->keyval) == keys[i].keyval
547                                 && CLEANMASK(ev->state) == keys[i].mod
548                                 && keys[i].func) {
549                         keys[i].func(c, &(keys[i].arg));
550                         processed = TRUE;
551                 }
552         }
553
554         return processed;
555 }
556
557 static void
558 linkhover(WebKitWebView *v, const char* t, const char* l, Client *c) {
559         if(l) {
560                 c->linkhover = copystr(&c->linkhover, l);
561         } else if(c->linkhover) {
562                 free(c->linkhover);
563                 c->linkhover = NULL;
564         }
565         update(c);
566 }
567
568 static void
569 loadstatuschange(WebKitWebView *view, GParamSpec *pspec, Client *c) {
570         WebKitWebFrame *frame;
571         WebKitWebDataSource *src;
572         WebKitNetworkRequest *request;
573         SoupMessage *msg;
574         char *uri;
575
576         switch(webkit_web_view_get_load_status (c->view)) {
577         case WEBKIT_LOAD_COMMITTED:
578                 uri = geturi(c);
579                 if(strstr(uri, "https://") == uri) {
580                         frame = webkit_web_view_get_main_frame(c->view);
581                         src = webkit_web_frame_get_data_source(frame);
582                         request = webkit_web_data_source_get_request(src);
583                         msg = webkit_network_request_get_message(request);
584                         c->sslfailed = soup_message_get_flags(msg)
585                                        ^ SOUP_MESSAGE_CERTIFICATE_TRUSTED;
586                 }
587                 setatom(c, AtomUri, uri);
588                 break;
589         case WEBKIT_LOAD_FINISHED:
590                 c->progress = 100;
591                 update(c);
592                 break;
593         default:
594                 break;
595         }
596 }
597
598 static void
599 loaduri(Client *c, const Arg *arg) {
600         char *u, *rp;
601         const char *uri = (char *)arg->v;
602         Arg a = { .b = FALSE };
603
604         if(strcmp(uri, "") == 0)
605                 return;
606
607         /* In case it's a file path. */
608         if(uri[0] == '/') {
609                 rp = realpath(uri, NULL);
610                 u = g_strdup_printf("file://%s", rp);
611                 free(rp);
612         } else {
613                 u = g_strrstr(uri, "://") ? g_strdup(uri)
614                         : g_strdup_printf("http://%s", uri);
615         }
616
617         /* prevents endless loop */
618         if(c->uri && strcmp(u, c->uri) == 0) {
619                 reload(c, &a);
620         } else {
621                 webkit_web_view_load_uri(c->view, u);
622                 c->progress = 0;
623                 c->title = copystr(&c->title, u);
624                 g_free(u);
625                 update(c);
626         }
627 }
628
629 static void
630 navigate(Client *c, const Arg *arg) {
631         int steps = *(int *)arg;
632         webkit_web_view_go_back_or_forward(c->view, steps);
633 }
634
635 static Client *
636 newclient(void) {
637         Client *c;
638         WebKitWebSettings *settings;
639         WebKitWebFrame *frame;
640         GdkGeometry hints = { 1, 1 };
641         char *uri, *ua;
642
643         if(!(c = calloc(1, sizeof(Client))))
644                 die("Cannot malloc!\n");
645
646         /* Window */
647         if(embed) {
648                 c->win = gtk_plug_new(embed);
649         } else {
650                 c->win = gtk_window_new(GTK_WINDOW_TOPLEVEL);
651
652                 /* TA:  20091214:  Despite what the GNOME docs say, the ICCCM
653                  * is always correct, so we should still call this function.
654                  * But when doing so, we *must* differentiate between a
655                  * WM_CLASS and a resource on the window.  By convention, the
656                  * window class (WM_CLASS) is capped, while the resource is in
657                  * lowercase.   Both these values come as a pair.
658                  */
659                 gtk_window_set_wmclass(GTK_WINDOW(c->win), "surf", "Surf");
660
661                 /* TA:  20091214:  And set the role here as well -- so that
662                  * sessions can pick this up.
663                  */
664                 gtk_window_set_role(GTK_WINDOW(c->win), "Surf");
665         }
666         gtk_window_set_default_size(GTK_WINDOW(c->win), 800, 600);
667         g_signal_connect(G_OBJECT(c->win),
668                         "destroy",
669                         G_CALLBACK(destroywin), c);
670         g_signal_connect(G_OBJECT(c->win),
671                         "key-press-event",
672                         G_CALLBACK(keypress), c);
673
674         /* VBox */
675         c->vbox = gtk_vbox_new(FALSE, 0);
676
677         /* Scrolled Window */
678         c->scroll = gtk_scrolled_window_new(NULL, NULL);
679         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(c->scroll),
680                         GTK_POLICY_NEVER, GTK_POLICY_NEVER);
681
682         /* Webview */
683         c->view = WEBKIT_WEB_VIEW(webkit_web_view_new());
684         g_signal_connect(G_OBJECT(c->view),
685                         "title-changed",
686                         G_CALLBACK(titlechange), c);
687         g_signal_connect(G_OBJECT(c->view),
688                         "hovering-over-link",
689                         G_CALLBACK(linkhover), c);
690         g_signal_connect(G_OBJECT(c->view),
691                         "create-web-view",
692                         G_CALLBACK(createwindow), c);
693         g_signal_connect(G_OBJECT(c->view),
694                         "new-window-policy-decision-requested",
695                         G_CALLBACK(decidewindow), c);
696         g_signal_connect(G_OBJECT(c->view),
697                         "mime-type-policy-decision-requested",
698                         G_CALLBACK(decidedownload), c);
699         g_signal_connect(G_OBJECT(c->view),
700                         "window-object-cleared",
701                         G_CALLBACK(windowobjectcleared), c);
702         g_signal_connect(G_OBJECT(c->view),
703                         "notify::load-status",
704                         G_CALLBACK(loadstatuschange), c);
705         g_signal_connect(G_OBJECT(c->view),
706                         "notify::progress",
707                         G_CALLBACK(progresschange), c);
708         g_signal_connect(G_OBJECT(c->view),
709                         "download-requested",
710                         G_CALLBACK(initdownload), c);
711         g_signal_connect(G_OBJECT(c->view),
712                         "button-release-event",
713                         G_CALLBACK(buttonrelease), c);
714         g_signal_connect(G_OBJECT(c->view),
715                         "populate-popup",
716                         G_CALLBACK(populatepopup), c);
717         g_signal_connect(G_OBJECT(c->view),
718                         "resource-request-starting",
719                         G_CALLBACK(beforerequest), c);
720
721         /* Indicator */
722         c->indicator = gtk_drawing_area_new();
723         gtk_widget_set_size_request(c->indicator, 0, indicator_thickness);
724         g_signal_connect (G_OBJECT (c->indicator), "expose_event",
725                         G_CALLBACK (exposeindicator), c);
726
727         /* Arranging */
728         gtk_container_add(GTK_CONTAINER(c->scroll), GTK_WIDGET(c->view));
729         gtk_container_add(GTK_CONTAINER(c->win), c->vbox);
730         gtk_container_add(GTK_CONTAINER(c->vbox), c->scroll);
731         gtk_container_add(GTK_CONTAINER(c->vbox), c->indicator);
732
733         /* Setup */
734         gtk_box_set_child_packing(GTK_BOX(c->vbox), c->indicator, FALSE,
735                         FALSE, 0, GTK_PACK_START);
736         gtk_box_set_child_packing(GTK_BOX(c->vbox), c->scroll, TRUE,
737                         TRUE, 0, GTK_PACK_START);
738         gtk_widget_grab_focus(GTK_WIDGET(c->view));
739         gtk_widget_show(c->vbox);
740         gtk_widget_show(c->scroll);
741         gtk_widget_show(GTK_WIDGET(c->view));
742         gtk_widget_show(c->win);
743         gtk_window_set_geometry_hints(GTK_WINDOW(c->win), NULL, &hints,
744                         GDK_HINT_MIN_SIZE);
745         gdk_window_set_events(GTK_WIDGET(c->win)->window, GDK_ALL_EVENTS_MASK);
746         gdk_window_add_filter(GTK_WIDGET(c->win)->window, processx, c);
747         webkit_web_view_set_full_content_zoom(c->view, TRUE);
748
749         frame = webkit_web_view_get_main_frame(c->view);
750         runscript(frame);
751         settings = webkit_web_view_get_settings(c->view);
752         if(!(ua = getenv("SURF_USERAGENT")))
753                 ua = useragent;
754         g_object_set(G_OBJECT(settings), "user-agent", ua, NULL);
755         uri = g_strconcat("file://", stylefile, NULL);
756         g_object_set(G_OBJECT(settings), "user-stylesheet-uri", uri, NULL);
757         g_object_set(G_OBJECT(settings), "auto-load-images", loadimages,
758                         NULL);
759         g_object_set(G_OBJECT(settings), "enable-plugins", enableplugins,
760                         NULL);
761         g_object_set(G_OBJECT(settings), "enable-scripts", enablescripts,
762                         NULL);
763         g_object_set(G_OBJECT(settings), "enable-spatial-navigation",
764                         enablespatialbrowsing, NULL);
765         g_object_set(G_OBJECT(settings), "enable-developer-extras",
766                         enableinspector, NULL);
767
768         if(enableinspector) {
769                 c->inspector = WEBKIT_WEB_INSPECTOR(
770                                 webkit_web_view_get_inspector(c->view));
771                 g_signal_connect(G_OBJECT(c->inspector), "inspect-web-view",
772                                 G_CALLBACK(inspector_new), c);
773                 g_signal_connect(G_OBJECT(c->inspector), "show-window",
774                                 G_CALLBACK(inspector_show), c);
775                 g_signal_connect(G_OBJECT(c->inspector), "close-window",
776                                 G_CALLBACK(inspector_close), c);
777                 g_signal_connect(G_OBJECT(c->inspector), "finished",
778                                 G_CALLBACK(inspector_finished), c);
779                 c->isinspector = false;
780         }
781
782         g_free(uri);
783
784         setatom(c, AtomFind, "");
785         setatom(c, AtomUri, "about:blank");
786         if(hidebackground)
787                 webkit_web_view_set_transparent(c->view, TRUE);
788
789         c->title = NULL;
790         c->next = clients;
791         clients = c;
792         if(showxid) {
793                 gdk_display_sync(gtk_widget_get_display(c->win));
794                 printf("%u\n",
795                         (guint)GDK_WINDOW_XID(GTK_WIDGET(c->win)->window));
796                 fflush(NULL);
797                 if (fclose(stdout) != 0) {
798                         die("Error closing stdout");
799                 }
800         }
801         return c;
802 }
803
804 static void
805 newwindow(Client *c, const Arg *arg, gboolean noembed) {
806         guint i = 0;
807         const char *cmd[10], *uri;
808         const Arg a = { .v = (void *)cmd };
809         char tmp[64];
810
811         cmd[i++] = argv0;
812         if(embed && !noembed) {
813                 cmd[i++] = "-e";
814                 snprintf(tmp, LENGTH(tmp), "%u\n", (int)embed);
815                 cmd[i++] = tmp;
816         }
817         if(!enablescripts)
818                 cmd[i++] = "-s";
819         if(!enableplugins)
820                 cmd[i++] = "-p";
821         if(!loadimages)
822                 cmd[i++] = "-i";
823         if(showxid)
824                 cmd[i++] = "-x";
825         cmd[i++] = "--";
826         uri = arg->v ? (char *)arg->v : c->linkhover;
827         if(uri)
828                 cmd[i++] = uri;
829         cmd[i++] = NULL;
830         spawn(NULL, &a);
831 }
832
833 static void
834 populatepopup(WebKitWebView *web, GtkMenu *menu, Client *c) {
835         GList *items = gtk_container_get_children(GTK_CONTAINER(menu));
836
837         for(GList *l = items; l; l = l->next) {
838                 g_signal_connect(l->data, "activate", G_CALLBACK(popupactivate), c);
839         }
840
841         g_list_free(items);
842 }
843
844 static void
845 popupactivate(GtkMenuItem *menu, Client *c) {
846         /*
847          * context-menu-action-2000     open link
848          * context-menu-action-1        open link in window
849          * context-menu-action-2        download linked file
850          * context-menu-action-3        copy link location
851          * context-menu-action-13       reload
852          * context-menu-action-10       back
853          * context-menu-action-11       forward
854          * context-menu-action-12       stop
855          */
856
857         GtkAction *a = NULL;
858         const char *name;
859         GtkClipboard *prisel;
860
861         a = gtk_activatable_get_related_action(GTK_ACTIVATABLE(menu));
862         if(a == NULL)
863                 return;
864
865         name = gtk_action_get_name(a);
866         if(!g_strcmp0(name, "context-menu-action-3")) {
867                 prisel = gtk_clipboard_get(GDK_SELECTION_PRIMARY);
868                 gtk_clipboard_set_text(prisel, c->linkhover, -1);
869         }
870 }
871
872 static void
873 pasteuri(GtkClipboard *clipboard, const char *text, gpointer d) {
874         Arg arg = {.v = text };
875         if(text != NULL)
876                 loaduri((Client *) d, &arg);
877 }
878
879 static void
880 print(Client *c, const Arg *arg) {
881         webkit_web_frame_print(webkit_web_view_get_main_frame(c->view));
882 }
883
884 static GdkFilterReturn
885 processx(GdkXEvent *e, GdkEvent *event, gpointer d) {
886         Client *c = (Client *)d;
887         XPropertyEvent *ev;
888         Arg arg;
889
890         if(((XEvent *)e)->type == PropertyNotify) {
891                 ev = &((XEvent *)e)->xproperty;
892                 if(ev->state == PropertyNewValue) {
893                         if(ev->atom == atoms[AtomFind]) {
894                                 arg.b = TRUE;
895                                 find(c, &arg);
896                                 return GDK_FILTER_REMOVE;
897                         }
898                         else if(ev->atom == atoms[AtomGo]) {
899                                 arg.v = getatom(c, AtomGo);
900                                 loaduri(c, &arg);
901                                 return GDK_FILTER_REMOVE;
902                         }
903                 }
904         }
905         return GDK_FILTER_CONTINUE;
906 }
907
908 static void
909 progresschange(WebKitWebView *view, GParamSpec *pspec, Client *c) {
910         c->progress = webkit_web_view_get_progress(c->view) * 100;
911         update(c);
912 }
913
914 static void
915 reload(Client *c, const Arg *arg) {
916         gboolean nocache = *(gboolean *)arg;
917         if(nocache)
918                  webkit_web_view_reload_bypass_cache(c->view);
919         else
920                  webkit_web_view_reload(c->view);
921 }
922
923 static void
924 scroll_h(Client *c, const Arg *arg) {
925         scroll(gtk_scrolled_window_get_hadjustment(
926                                 GTK_SCROLLED_WINDOW(c->scroll)), arg);
927 }
928
929 static void
930 scroll_v(Client *c, const Arg *arg) {
931         scroll(gtk_scrolled_window_get_vadjustment(
932                                 GTK_SCROLLED_WINDOW(c->scroll)), arg);
933 }
934
935 static void
936 scroll(GtkAdjustment *a, const Arg *arg) {
937         gdouble v;
938
939         v = gtk_adjustment_get_value(a);
940         switch (arg->i){
941         case +10000:
942         case -10000:
943                 v += gtk_adjustment_get_page_increment(a) *
944                         (arg->i / 10000);
945                 break;
946         case +20000:
947         case -20000:
948         default:
949                 v += gtk_adjustment_get_step_increment(a) * arg->i;
950         }
951
952         v = MAX(v, 0.0);
953         v = MIN(v, gtk_adjustment_get_upper(a) -
954                         gtk_adjustment_get_page_size(a));
955         gtk_adjustment_set_value(a, v);
956 }
957
958 static void
959 setatom(Client *c, int a, const char *v) {
960         XSync(dpy, False);
961         XChangeProperty(dpy, GDK_WINDOW_XID(GTK_WIDGET(c->win)->window),
962                         atoms[a], XA_STRING, 8, PropModeReplace,
963                         (unsigned char *)v, strlen(v) + 1);
964 }
965
966 static void
967 setup(void) {
968         char *proxy;
969         char *new_proxy;
970         SoupURI *puri;
971         SoupSession *s;
972
973         /* clean up any zombies immediately */
974         sigchld(0);
975         gtk_init(NULL, NULL);
976         if (!g_thread_supported())
977                 g_thread_init(NULL);
978
979         dpy = GDK_DISPLAY();
980
981         /* atoms */
982         atoms[AtomFind] = XInternAtom(dpy, "_SURF_FIND", False);
983         atoms[AtomGo] = XInternAtom(dpy, "_SURF_GO", False);
984         atoms[AtomUri] = XInternAtom(dpy, "_SURF_URI", False);
985
986         /* dirs and files */
987         cookiefile = buildpath(cookiefile);
988         scriptfile = buildpath(scriptfile);
989         stylefile = buildpath(stylefile);
990
991         /* request handler */
992         s = webkit_get_default_session();
993
994         /* cookie jar */
995         soup_session_add_feature(s,
996                         SOUP_SESSION_FEATURE(cookiejar_new(cookiefile,
997                                         FALSE)));
998
999         /* ssl */
1000         g_object_set(G_OBJECT(s), "ssl-ca-file", cafile, NULL);
1001         g_object_set(G_OBJECT(s), "ssl-strict", strictssl, NULL);
1002
1003         /* proxy */
1004         if((proxy = getenv("http_proxy")) && strcmp(proxy, "")) {
1005                 new_proxy = g_strrstr(proxy, "http://") ? g_strdup(proxy) :
1006                         g_strdup_printf("http://%s", proxy);
1007                 puri = soup_uri_new(new_proxy);
1008                 g_object_set(G_OBJECT(s), "proxy-uri", puri, NULL);
1009                 soup_uri_free(puri);
1010                 g_free(new_proxy);
1011                 usingproxy = 1;
1012         }
1013 }
1014
1015 static void
1016 sigchld(int unused) {
1017         if(signal(SIGCHLD, sigchld) == SIG_ERR)
1018                 die("Can't install SIGCHLD handler");
1019         while(0 < waitpid(-1, NULL, WNOHANG));
1020 }
1021
1022 static void
1023 source(Client *c, const Arg *arg) {
1024         Arg a = { .b = FALSE };
1025         gboolean s;
1026
1027         s = webkit_web_view_get_view_source_mode(c->view);
1028         webkit_web_view_set_view_source_mode(c->view, !s);
1029         reload(c, &a);
1030 }
1031
1032 static void
1033 spawn(Client *c, const Arg *arg) {
1034         if(fork() == 0) {
1035                 if(dpy)
1036                         close(ConnectionNumber(dpy));
1037                 setsid();
1038                 execvp(((char **)arg->v)[0], (char **)arg->v);
1039                 fprintf(stderr, "surf: execvp %s", ((char **)arg->v)[0]);
1040                 perror(" failed");
1041                 exit(0);
1042         }
1043 }
1044
1045 static void
1046 eval(Client *c, const Arg *arg) {
1047         WebKitWebFrame *frame = webkit_web_view_get_main_frame(c->view);
1048         evalscript(webkit_web_frame_get_global_context(frame),
1049                         ((char **)arg->v)[0], "");
1050 }
1051
1052 static void
1053 stop(Client *c, const Arg *arg) {
1054         webkit_web_view_stop_loading(c->view);
1055 }
1056
1057 static void
1058 titlechange(WebKitWebView *v, WebKitWebFrame *f, const char *t, Client *c) {
1059         c->title = copystr(&c->title, t);
1060         update(c);
1061 }
1062
1063 static void
1064 toggle(Client *c, const Arg *arg) {
1065         WebKitWebSettings *settings;
1066         char *name = (char *)arg->v;
1067         gboolean value;
1068         Arg a = { .b = FALSE };
1069
1070         settings = webkit_web_view_get_settings(c->view);
1071         g_object_get(G_OBJECT(settings), name, &value, NULL);
1072         g_object_set(G_OBJECT(settings), name, !value, NULL);
1073
1074         reload(c,&a);
1075 }
1076
1077 static void
1078 gettogglestat(Client *c){
1079         gboolean value;
1080         WebKitWebSettings *settings = webkit_web_view_get_settings(c->view);
1081
1082         g_object_get(G_OBJECT(settings), "enable-caret-browsing",
1083                         &value, NULL);
1084         togglestat[0] = value? 'C': 'c';
1085
1086         g_object_get(G_OBJECT(settings), "auto-load-images", &value, NULL);
1087         togglestat[1] = value? 'I': 'i';
1088
1089         g_object_get(G_OBJECT(settings), "enable-scripts", &value, NULL);
1090         togglestat[2] = value? 'S': 's';
1091
1092         g_object_get(G_OBJECT(settings), "enable-plugins", &value, NULL);
1093         togglestat[3] = value? 'V': 'v';
1094
1095         togglestat[4] = '\0';
1096 }
1097
1098
1099 static void
1100 update(Client *c) {
1101         char *t;
1102
1103         gettogglestat(c);
1104
1105         if(c->linkhover) {
1106                 t = g_strdup_printf("%s| %s", togglestat, c->linkhover);
1107         } else if(c->progress != 100) {
1108                 drawindicator(c);
1109                 gtk_widget_show(c->indicator);
1110                 t = g_strdup_printf("[%i%%] %s| %s", c->progress, togglestat,
1111                                 c->title);
1112         } else {
1113                 gtk_widget_hide_all(c->indicator);
1114                 t = g_strdup_printf("%s| %s", togglestat, c->title);
1115         }
1116
1117         gtk_window_set_title(GTK_WINDOW(c->win), t);
1118         g_free(t);
1119 }
1120
1121 static void
1122 updatewinid(Client *c) {
1123         snprintf(winid, LENGTH(winid), "%u",
1124                         (int)GDK_WINDOW_XID(GTK_WIDGET(c->win)->window));
1125 }
1126
1127 static void
1128 usage(void) {
1129         die("usage: %s [-inpsvx] [-c cookiefile] [-e xid] [-r scriptfile]"
1130                 " [-t stylefile] [-u useragent] [uri]\n", basename(argv0));
1131 }
1132
1133 static void
1134 windowobjectcleared(GtkWidget *w, WebKitWebFrame *frame, JSContextRef js,
1135                 JSObjectRef win, Client *c) {
1136         runscript(frame);
1137 }
1138
1139 static void
1140 zoom(Client *c, const Arg *arg) {
1141         c->zoomed = TRUE;
1142         if(arg->i < 0) {
1143                 /* zoom out */
1144                 webkit_web_view_zoom_out(c->view);
1145         } else if(arg->i > 0) {
1146                 /* zoom in */
1147                 webkit_web_view_zoom_in(c->view);
1148         } else {
1149                 /* reset */
1150                 c->zoomed = FALSE;
1151                 webkit_web_view_set_zoom_level(c->view, 1.0);
1152         }
1153 }
1154
1155 int
1156 main(int argc, char *argv[]) {
1157         Arg arg;
1158
1159         memset(&arg, 0, sizeof(arg));
1160
1161         /* command line args */
1162         ARGBEGIN {
1163         case 'c':
1164                 cookiefile = EARGF(usage());
1165                 break;
1166         case 'e':
1167                 embed = strtol(EARGF(usage()), NULL, 0);
1168                 break;
1169         case 'i':
1170                 loadimages = 0;
1171                 break;
1172         case 'n':
1173                 enableinspector = 0;
1174                 break;
1175         case 'p':
1176                 enableplugins = 0;
1177                 break;
1178         case 'r':
1179                 scriptfile = EARGF(usage());
1180                 break;
1181         case 's':
1182                 enablescripts = 0;
1183                 break;
1184         case 't':
1185                 stylefile = EARGF(usage());
1186                 break;
1187         case 'u':
1188                 useragent = EARGF(usage());
1189                 break;
1190         case 'v':
1191                 die("surf-"VERSION", ©2009-2012 surf engineers, "
1192                                 "see LICENSE for details\n");
1193         case 'x':
1194                 showxid = TRUE;
1195                 break;
1196         default:
1197                 usage();
1198         } ARGEND;
1199         if(argc > 0)
1200                 arg.v = argv[0];
1201
1202         setup();
1203         newclient();
1204         if(arg.v)
1205                 loaduri(clients, &arg);
1206
1207         gtk_main();
1208         cleanup();
1209
1210         return EXIT_SUCCESS;
1211 }
1212