cebd469dcdaa235ff88b6f732643f61d6d1a9e96
[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, *pane;
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, isinspecting, 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->isinspecting) {
510                 webkit_web_inspector_close(c->inspector);
511         } else {
512                 webkit_web_inspector_show(c->inspector);
513         }
514 }
515
516 static WebKitWebView *
517 inspector_new(WebKitWebInspector *i, WebKitWebView *v, Client *c) {
518         return WEBKIT_WEB_VIEW(webkit_web_view_new());
519 }
520
521 static gboolean
522 inspector_show(WebKitWebInspector *i, Client *c) {
523         WebKitWebView *w;
524
525         if(c->isinspecting)
526                 return false;
527
528         w = webkit_web_inspector_get_web_view(i);
529         gtk_paned_pack2(GTK_PANED(c->pane), GTK_WIDGET(w), TRUE, TRUE);
530         gtk_widget_show(GTK_WIDGET(w));
531         c->isinspecting = true;
532
533         return true;
534 }
535
536 static gboolean
537 inspector_close(WebKitWebInspector *i, Client *c) {
538         GtkWidget *w;
539
540         if(!c->isinspecting)
541                 return false;
542
543         w = GTK_WIDGET(webkit_web_inspector_get_web_view(i));
544         gtk_widget_hide(w);
545         gtk_widget_destroy(w);
546         c->isinspecting = false;
547
548         return true;
549 }
550
551 static void
552 inspector_finished(WebKitWebInspector *i, Client *c) {
553         g_free(c->inspector);
554 }
555
556 static gboolean
557 keypress(GtkWidget* w, GdkEventKey *ev, Client *c) {
558         guint i;
559         gboolean processed = FALSE;
560
561         updatewinid(c);
562         for(i = 0; i < LENGTH(keys); i++) {
563                 if(gdk_keyval_to_lower(ev->keyval) == keys[i].keyval
564                                 && CLEANMASK(ev->state) == keys[i].mod
565                                 && keys[i].func) {
566                         keys[i].func(c, &(keys[i].arg));
567                         processed = TRUE;
568                 }
569         }
570
571         return processed;
572 }
573
574 static void
575 linkhover(WebKitWebView *v, const char* t, const char* l, Client *c) {
576         if(l) {
577                 c->linkhover = copystr(&c->linkhover, l);
578         } else if(c->linkhover) {
579                 free(c->linkhover);
580                 c->linkhover = NULL;
581         }
582         update(c);
583 }
584
585 static void
586 loadstatuschange(WebKitWebView *view, GParamSpec *pspec, Client *c) {
587         WebKitWebFrame *frame;
588         WebKitWebDataSource *src;
589         WebKitNetworkRequest *request;
590         SoupMessage *msg;
591         char *uri;
592
593         switch(webkit_web_view_get_load_status (c->view)) {
594         case WEBKIT_LOAD_COMMITTED:
595                 uri = geturi(c);
596                 if(strstr(uri, "https://") == uri) {
597                         frame = webkit_web_view_get_main_frame(c->view);
598                         src = webkit_web_frame_get_data_source(frame);
599                         request = webkit_web_data_source_get_request(src);
600                         msg = webkit_network_request_get_message(request);
601                         c->sslfailed = soup_message_get_flags(msg)
602                                        ^ SOUP_MESSAGE_CERTIFICATE_TRUSTED;
603                 }
604                 setatom(c, AtomUri, uri);
605                 break;
606         case WEBKIT_LOAD_FINISHED:
607                 c->progress = 100;
608                 update(c);
609                 break;
610         default:
611                 break;
612         }
613 }
614
615 static void
616 loaduri(Client *c, const Arg *arg) {
617         char *u, *rp;
618         const char *uri = (char *)arg->v;
619         Arg a = { .b = FALSE };
620
621         if(strcmp(uri, "") == 0)
622                 return;
623
624         /* In case it's a file path. */
625         if(uri[0] == '/') {
626                 rp = realpath(uri, NULL);
627                 u = g_strdup_printf("file://%s", rp);
628                 free(rp);
629         } else {
630                 u = g_strrstr(uri, "://") ? g_strdup(uri)
631                         : g_strdup_printf("http://%s", uri);
632         }
633
634         /* prevents endless loop */
635         if(c->uri && strcmp(u, c->uri) == 0) {
636                 reload(c, &a);
637         } else {
638                 webkit_web_view_load_uri(c->view, u);
639                 c->progress = 0;
640                 c->title = copystr(&c->title, u);
641                 g_free(u);
642                 update(c);
643         }
644 }
645
646 static void
647 navigate(Client *c, const Arg *arg) {
648         int steps = *(int *)arg;
649         webkit_web_view_go_back_or_forward(c->view, steps);
650 }
651
652 static Client *
653 newclient(void) {
654         Client *c;
655         WebKitWebSettings *settings;
656         WebKitWebFrame *frame;
657         GdkGeometry hints = { 1, 1 };
658         char *uri, *ua;
659
660         if(!(c = calloc(1, sizeof(Client))))
661                 die("Cannot malloc!\n");
662
663         /* Window */
664         if(embed) {
665                 c->win = gtk_plug_new(embed);
666         } else {
667                 c->win = gtk_window_new(GTK_WINDOW_TOPLEVEL);
668
669                 /* TA:  20091214:  Despite what the GNOME docs say, the ICCCM
670                  * is always correct, so we should still call this function.
671                  * But when doing so, we *must* differentiate between a
672                  * WM_CLASS and a resource on the window.  By convention, the
673                  * window class (WM_CLASS) is capped, while the resource is in
674                  * lowercase.   Both these values come as a pair.
675                  */
676                 gtk_window_set_wmclass(GTK_WINDOW(c->win), "surf", "Surf");
677
678                 /* TA:  20091214:  And set the role here as well -- so that
679                  * sessions can pick this up.
680                  */
681                 gtk_window_set_role(GTK_WINDOW(c->win), "Surf");
682         }
683         gtk_window_set_default_size(GTK_WINDOW(c->win), 800, 600);
684         g_signal_connect(G_OBJECT(c->win),
685                         "destroy",
686                         G_CALLBACK(destroywin), c);
687         g_signal_connect(G_OBJECT(c->win),
688                         "key-press-event",
689                         G_CALLBACK(keypress), c);
690
691         /* Pane */
692         c->pane = gtk_vpaned_new();
693
694         /* VBox */
695         c->vbox = gtk_vbox_new(FALSE, 0);
696         gtk_paned_pack1(GTK_PANED(c->pane), c->vbox, TRUE, TRUE);
697
698         /* Scrolled Window */
699         c->scroll = gtk_scrolled_window_new(NULL, NULL);
700         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(c->scroll),
701                         GTK_POLICY_NEVER, GTK_POLICY_NEVER);
702
703         /* Webview */
704         c->view = WEBKIT_WEB_VIEW(webkit_web_view_new());
705         g_signal_connect(G_OBJECT(c->view),
706                         "title-changed",
707                         G_CALLBACK(titlechange), c);
708         g_signal_connect(G_OBJECT(c->view),
709                         "hovering-over-link",
710                         G_CALLBACK(linkhover), c);
711         g_signal_connect(G_OBJECT(c->view),
712                         "create-web-view",
713                         G_CALLBACK(createwindow), c);
714         g_signal_connect(G_OBJECT(c->view),
715                         "new-window-policy-decision-requested",
716                         G_CALLBACK(decidewindow), c);
717         g_signal_connect(G_OBJECT(c->view),
718                         "mime-type-policy-decision-requested",
719                         G_CALLBACK(decidedownload), c);
720         g_signal_connect(G_OBJECT(c->view),
721                         "window-object-cleared",
722                         G_CALLBACK(windowobjectcleared), c);
723         g_signal_connect(G_OBJECT(c->view),
724                         "notify::load-status",
725                         G_CALLBACK(loadstatuschange), c);
726         g_signal_connect(G_OBJECT(c->view),
727                         "notify::progress",
728                         G_CALLBACK(progresschange), c);
729         g_signal_connect(G_OBJECT(c->view),
730                         "download-requested",
731                         G_CALLBACK(initdownload), c);
732         g_signal_connect(G_OBJECT(c->view),
733                         "button-release-event",
734                         G_CALLBACK(buttonrelease), c);
735         g_signal_connect(G_OBJECT(c->view),
736                         "populate-popup",
737                         G_CALLBACK(populatepopup), c);
738         g_signal_connect(G_OBJECT(c->view),
739                         "resource-request-starting",
740                         G_CALLBACK(beforerequest), c);
741
742         /* Indicator */
743         c->indicator = gtk_drawing_area_new();
744         gtk_widget_set_size_request(c->indicator, 0, indicator_thickness);
745         g_signal_connect (G_OBJECT (c->indicator), "expose_event",
746                         G_CALLBACK (exposeindicator), c);
747
748         /* Arranging */
749         gtk_container_add(GTK_CONTAINER(c->scroll), GTK_WIDGET(c->view));
750         gtk_container_add(GTK_CONTAINER(c->win), c->pane);
751         gtk_container_add(GTK_CONTAINER(c->vbox), c->scroll);
752         gtk_container_add(GTK_CONTAINER(c->vbox), c->indicator);
753
754         /* Setup */
755         gtk_box_set_child_packing(GTK_BOX(c->vbox), c->indicator, FALSE,
756                         FALSE, 0, GTK_PACK_START);
757         gtk_box_set_child_packing(GTK_BOX(c->vbox), c->scroll, TRUE,
758                         TRUE, 0, GTK_PACK_START);
759         gtk_widget_grab_focus(GTK_WIDGET(c->view));
760         gtk_widget_show(c->pane);
761         gtk_widget_show(c->vbox);
762         gtk_widget_show(c->scroll);
763         gtk_widget_show(GTK_WIDGET(c->view));
764         gtk_widget_show(c->win);
765         gtk_window_set_geometry_hints(GTK_WINDOW(c->win), NULL, &hints,
766                         GDK_HINT_MIN_SIZE);
767         gdk_window_set_events(GTK_WIDGET(c->win)->window, GDK_ALL_EVENTS_MASK);
768         gdk_window_add_filter(GTK_WIDGET(c->win)->window, processx, c);
769         webkit_web_view_set_full_content_zoom(c->view, TRUE);
770
771         frame = webkit_web_view_get_main_frame(c->view);
772         runscript(frame);
773         settings = webkit_web_view_get_settings(c->view);
774         if(!(ua = getenv("SURF_USERAGENT")))
775                 ua = useragent;
776         g_object_set(G_OBJECT(settings), "user-agent", ua, NULL);
777         uri = g_strconcat("file://", stylefile, NULL);
778         g_object_set(G_OBJECT(settings), "user-stylesheet-uri", uri, NULL);
779         g_object_set(G_OBJECT(settings), "auto-load-images", loadimages,
780                         NULL);
781         g_object_set(G_OBJECT(settings), "enable-plugins", enableplugins,
782                         NULL);
783         g_object_set(G_OBJECT(settings), "enable-scripts", enablescripts,
784                         NULL);
785         g_object_set(G_OBJECT(settings), "enable-spatial-navigation",
786                         enablespatialbrowsing, NULL);
787         g_object_set(G_OBJECT(settings), "enable-developer-extras",
788                         enableinspector, NULL);
789
790         if(enableinspector) {
791                 c->inspector = WEBKIT_WEB_INSPECTOR(
792                                 webkit_web_view_get_inspector(c->view));
793                 g_signal_connect(G_OBJECT(c->inspector), "inspect-web-view",
794                                 G_CALLBACK(inspector_new), c);
795                 g_signal_connect(G_OBJECT(c->inspector), "show-window",
796                                 G_CALLBACK(inspector_show), c);
797                 g_signal_connect(G_OBJECT(c->inspector), "close-window",
798                                 G_CALLBACK(inspector_close), c);
799                 g_signal_connect(G_OBJECT(c->inspector), "finished",
800                                 G_CALLBACK(inspector_finished), c);
801                 c->isinspecting = false;
802         }
803
804         g_free(uri);
805
806         setatom(c, AtomFind, "");
807         setatom(c, AtomUri, "about:blank");
808         if(hidebackground)
809                 webkit_web_view_set_transparent(c->view, TRUE);
810
811         c->title = NULL;
812         c->next = clients;
813         clients = c;
814
815         if(showxid) {
816                 gdk_display_sync(gtk_widget_get_display(c->win));
817                 printf("%u\n",
818                         (guint)GDK_WINDOW_XID(GTK_WIDGET(c->win)->window));
819                 fflush(NULL);
820                 if (fclose(stdout) != 0) {
821                         die("Error closing stdout");
822                 }
823         }
824
825         return c;
826 }
827
828 static void
829 newwindow(Client *c, const Arg *arg, gboolean noembed) {
830         guint i = 0;
831         const char *cmd[10], *uri;
832         const Arg a = { .v = (void *)cmd };
833         char tmp[64];
834
835         cmd[i++] = argv0;
836         if(embed && !noembed) {
837                 cmd[i++] = "-e";
838                 snprintf(tmp, LENGTH(tmp), "%u\n", (int)embed);
839                 cmd[i++] = tmp;
840         }
841         if(!enablescripts)
842                 cmd[i++] = "-s";
843         if(!enableplugins)
844                 cmd[i++] = "-p";
845         if(!loadimages)
846                 cmd[i++] = "-i";
847         if(showxid)
848                 cmd[i++] = "-x";
849         cmd[i++] = "--";
850         uri = arg->v ? (char *)arg->v : c->linkhover;
851         if(uri)
852                 cmd[i++] = uri;
853         cmd[i++] = NULL;
854         spawn(NULL, &a);
855 }
856
857 static void
858 populatepopup(WebKitWebView *web, GtkMenu *menu, Client *c) {
859         GList *items = gtk_container_get_children(GTK_CONTAINER(menu));
860
861         for(GList *l = items; l; l = l->next) {
862                 g_signal_connect(l->data, "activate", G_CALLBACK(popupactivate), c);
863         }
864
865         g_list_free(items);
866 }
867
868 static void
869 popupactivate(GtkMenuItem *menu, Client *c) {
870         /*
871          * context-menu-action-2000     open link
872          * context-menu-action-1        open link in window
873          * context-menu-action-2        download linked file
874          * context-menu-action-3        copy link location
875          * context-menu-action-13       reload
876          * context-menu-action-10       back
877          * context-menu-action-11       forward
878          * context-menu-action-12       stop
879          */
880
881         GtkAction *a = NULL;
882         const char *name;
883         GtkClipboard *prisel;
884
885         a = gtk_activatable_get_related_action(GTK_ACTIVATABLE(menu));
886         if(a == NULL)
887                 return;
888
889         name = gtk_action_get_name(a);
890         if(!g_strcmp0(name, "context-menu-action-3")) {
891                 prisel = gtk_clipboard_get(GDK_SELECTION_PRIMARY);
892                 gtk_clipboard_set_text(prisel, c->linkhover, -1);
893         }
894 }
895
896 static void
897 pasteuri(GtkClipboard *clipboard, const char *text, gpointer d) {
898         Arg arg = {.v = text };
899         if(text != NULL)
900                 loaduri((Client *) d, &arg);
901 }
902
903 static void
904 print(Client *c, const Arg *arg) {
905         webkit_web_frame_print(webkit_web_view_get_main_frame(c->view));
906 }
907
908 static GdkFilterReturn
909 processx(GdkXEvent *e, GdkEvent *event, gpointer d) {
910         Client *c = (Client *)d;
911         XPropertyEvent *ev;
912         Arg arg;
913
914         if(((XEvent *)e)->type == PropertyNotify) {
915                 ev = &((XEvent *)e)->xproperty;
916                 if(ev->state == PropertyNewValue) {
917                         if(ev->atom == atoms[AtomFind]) {
918                                 arg.b = TRUE;
919                                 find(c, &arg);
920                                 return GDK_FILTER_REMOVE;
921                         }
922                         else if(ev->atom == atoms[AtomGo]) {
923                                 arg.v = getatom(c, AtomGo);
924                                 loaduri(c, &arg);
925                                 return GDK_FILTER_REMOVE;
926                         }
927                 }
928         }
929         return GDK_FILTER_CONTINUE;
930 }
931
932 static void
933 progresschange(WebKitWebView *view, GParamSpec *pspec, Client *c) {
934         c->progress = webkit_web_view_get_progress(c->view) * 100;
935         update(c);
936 }
937
938 static void
939 reload(Client *c, const Arg *arg) {
940         gboolean nocache = *(gboolean *)arg;
941         if(nocache)
942                  webkit_web_view_reload_bypass_cache(c->view);
943         else
944                  webkit_web_view_reload(c->view);
945 }
946
947 static void
948 scroll_h(Client *c, const Arg *arg) {
949         scroll(gtk_scrolled_window_get_hadjustment(
950                                 GTK_SCROLLED_WINDOW(c->scroll)), arg);
951 }
952
953 static void
954 scroll_v(Client *c, const Arg *arg) {
955         scroll(gtk_scrolled_window_get_vadjustment(
956                                 GTK_SCROLLED_WINDOW(c->scroll)), arg);
957 }
958
959 static void
960 scroll(GtkAdjustment *a, const Arg *arg) {
961         gdouble v;
962
963         v = gtk_adjustment_get_value(a);
964         switch (arg->i){
965         case +10000:
966         case -10000:
967                 v += gtk_adjustment_get_page_increment(a) *
968                         (arg->i / 10000);
969                 break;
970         case +20000:
971         case -20000:
972         default:
973                 v += gtk_adjustment_get_step_increment(a) * arg->i;
974         }
975
976         v = MAX(v, 0.0);
977         v = MIN(v, gtk_adjustment_get_upper(a) -
978                         gtk_adjustment_get_page_size(a));
979         gtk_adjustment_set_value(a, v);
980 }
981
982 static void
983 setatom(Client *c, int a, const char *v) {
984         XSync(dpy, False);
985         XChangeProperty(dpy, GDK_WINDOW_XID(GTK_WIDGET(c->win)->window),
986                         atoms[a], XA_STRING, 8, PropModeReplace,
987                         (unsigned char *)v, strlen(v) + 1);
988 }
989
990 static void
991 setup(void) {
992         char *proxy;
993         char *new_proxy;
994         SoupURI *puri;
995         SoupSession *s;
996
997         /* clean up any zombies immediately */
998         sigchld(0);
999         gtk_init(NULL, NULL);
1000
1001         dpy = GDK_DISPLAY();
1002
1003         /* atoms */
1004         atoms[AtomFind] = XInternAtom(dpy, "_SURF_FIND", False);
1005         atoms[AtomGo] = XInternAtom(dpy, "_SURF_GO", False);
1006         atoms[AtomUri] = XInternAtom(dpy, "_SURF_URI", False);
1007
1008         /* dirs and files */
1009         cookiefile = buildpath(cookiefile);
1010         scriptfile = buildpath(scriptfile);
1011         stylefile = buildpath(stylefile);
1012
1013         /* request handler */
1014         s = webkit_get_default_session();
1015
1016         /* cookie jar */
1017         soup_session_add_feature(s,
1018                         SOUP_SESSION_FEATURE(cookiejar_new(cookiefile,
1019                                         FALSE)));
1020
1021         /* ssl */
1022         g_object_set(G_OBJECT(s), "ssl-ca-file", cafile, NULL);
1023         g_object_set(G_OBJECT(s), "ssl-strict", strictssl, NULL);
1024
1025         /* proxy */
1026         if((proxy = getenv("http_proxy")) && strcmp(proxy, "")) {
1027                 new_proxy = g_strrstr(proxy, "http://") ? g_strdup(proxy) :
1028                         g_strdup_printf("http://%s", proxy);
1029                 puri = soup_uri_new(new_proxy);
1030                 g_object_set(G_OBJECT(s), "proxy-uri", puri, NULL);
1031                 soup_uri_free(puri);
1032                 g_free(new_proxy);
1033                 usingproxy = 1;
1034         }
1035 }
1036
1037 static void
1038 sigchld(int unused) {
1039         if(signal(SIGCHLD, sigchld) == SIG_ERR)
1040                 die("Can't install SIGCHLD handler");
1041         while(0 < waitpid(-1, NULL, WNOHANG));
1042 }
1043
1044 static void
1045 source(Client *c, const Arg *arg) {
1046         Arg a = { .b = FALSE };
1047         gboolean s;
1048
1049         s = webkit_web_view_get_view_source_mode(c->view);
1050         webkit_web_view_set_view_source_mode(c->view, !s);
1051         reload(c, &a);
1052 }
1053
1054 static void
1055 spawn(Client *c, const Arg *arg) {
1056         if(fork() == 0) {
1057                 if(dpy)
1058                         close(ConnectionNumber(dpy));
1059                 setsid();
1060                 execvp(((char **)arg->v)[0], (char **)arg->v);
1061                 fprintf(stderr, "surf: execvp %s", ((char **)arg->v)[0]);
1062                 perror(" failed");
1063                 exit(0);
1064         }
1065 }
1066
1067 static void
1068 eval(Client *c, const Arg *arg) {
1069         WebKitWebFrame *frame = webkit_web_view_get_main_frame(c->view);
1070         evalscript(webkit_web_frame_get_global_context(frame),
1071                         ((char **)arg->v)[0], "");
1072 }
1073
1074 static void
1075 stop(Client *c, const Arg *arg) {
1076         webkit_web_view_stop_loading(c->view);
1077 }
1078
1079 static void
1080 titlechange(WebKitWebView *v, WebKitWebFrame *f, const char *t, Client *c) {
1081         c->title = copystr(&c->title, t);
1082         update(c);
1083 }
1084
1085 static void
1086 toggle(Client *c, const Arg *arg) {
1087         WebKitWebSettings *settings;
1088         char *name = (char *)arg->v;
1089         gboolean value;
1090         Arg a = { .b = FALSE };
1091
1092         settings = webkit_web_view_get_settings(c->view);
1093         g_object_get(G_OBJECT(settings), name, &value, NULL);
1094         g_object_set(G_OBJECT(settings), name, !value, NULL);
1095
1096         reload(c,&a);
1097 }
1098
1099 static void
1100 gettogglestat(Client *c){
1101         gboolean value;
1102         WebKitWebSettings *settings = webkit_web_view_get_settings(c->view);
1103
1104         g_object_get(G_OBJECT(settings), "enable-caret-browsing",
1105                         &value, NULL);
1106         togglestat[0] = value? 'C': 'c';
1107
1108         g_object_get(G_OBJECT(settings), "auto-load-images", &value, NULL);
1109         togglestat[1] = value? 'I': 'i';
1110
1111         g_object_get(G_OBJECT(settings), "enable-scripts", &value, NULL);
1112         togglestat[2] = value? 'S': 's';
1113
1114         g_object_get(G_OBJECT(settings), "enable-plugins", &value, NULL);
1115         togglestat[3] = value? 'V': 'v';
1116
1117         togglestat[4] = '\0';
1118 }
1119
1120
1121 static void
1122 update(Client *c) {
1123         char *t;
1124
1125         gettogglestat(c);
1126
1127         if(c->linkhover) {
1128                 t = g_strdup_printf("%s| %s", togglestat, c->linkhover);
1129         } else if(c->progress != 100) {
1130                 drawindicator(c);
1131                 gtk_widget_show(c->indicator);
1132                 t = g_strdup_printf("[%i%%] %s| %s", c->progress, togglestat,
1133                                 c->title);
1134         } else {
1135                 gtk_widget_hide_all(c->indicator);
1136                 t = g_strdup_printf("%s| %s", togglestat, c->title);
1137         }
1138
1139         gtk_window_set_title(GTK_WINDOW(c->win), t);
1140         g_free(t);
1141 }
1142
1143 static void
1144 updatewinid(Client *c) {
1145         snprintf(winid, LENGTH(winid), "%u",
1146                         (int)GDK_WINDOW_XID(GTK_WIDGET(c->win)->window));
1147 }
1148
1149 static void
1150 usage(void) {
1151         die("usage: %s [-inpsvx] [-c cookiefile] [-e xid] [-r scriptfile]"
1152                 " [-t stylefile] [-u useragent] [uri]\n", basename(argv0));
1153 }
1154
1155 static void
1156 windowobjectcleared(GtkWidget *w, WebKitWebFrame *frame, JSContextRef js,
1157                 JSObjectRef win, Client *c) {
1158         runscript(frame);
1159 }
1160
1161 static void
1162 zoom(Client *c, const Arg *arg) {
1163         c->zoomed = TRUE;
1164         if(arg->i < 0) {
1165                 /* zoom out */
1166                 webkit_web_view_zoom_out(c->view);
1167         } else if(arg->i > 0) {
1168                 /* zoom in */
1169                 webkit_web_view_zoom_in(c->view);
1170         } else {
1171                 /* reset */
1172                 c->zoomed = FALSE;
1173                 webkit_web_view_set_zoom_level(c->view, 1.0);
1174         }
1175 }
1176
1177 int
1178 main(int argc, char *argv[]) {
1179         Arg arg;
1180
1181         memset(&arg, 0, sizeof(arg));
1182
1183         /* command line args */
1184         ARGBEGIN {
1185         case 'c':
1186                 cookiefile = EARGF(usage());
1187                 break;
1188         case 'e':
1189                 embed = strtol(EARGF(usage()), NULL, 0);
1190                 break;
1191         case 'i':
1192                 loadimages = 0;
1193                 break;
1194         case 'n':
1195                 enableinspector = 0;
1196                 break;
1197         case 'p':
1198                 enableplugins = 0;
1199                 break;
1200         case 'r':
1201                 scriptfile = EARGF(usage());
1202                 break;
1203         case 's':
1204                 enablescripts = 0;
1205                 break;
1206         case 't':
1207                 stylefile = EARGF(usage());
1208                 break;
1209         case 'u':
1210                 useragent = EARGF(usage());
1211                 break;
1212         case 'v':
1213                 die("surf-"VERSION", ©2009-2012 surf engineers, "
1214                                 "see LICENSE for details\n");
1215         case 'x':
1216                 showxid = TRUE;
1217                 break;
1218         default:
1219                 usage();
1220         } ARGEND;
1221         if(argc > 0)
1222                 arg.v = argv[0];
1223
1224         setup();
1225         newclient();
1226         if(arg.v)
1227                 loaduri(clients, &arg);
1228
1229         gtk_main();
1230         cleanup();
1231
1232         return EXIT_SUCCESS;
1233 }
1234