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