1 /* See LICENSE file for copyright and license details.
3 * To understand surf, start reading main().
11 #include <gdk/gdkkeysyms.h>
13 #include <sys/types.h>
18 #include <webkit/webkit.h>
19 #include <glib/gstdio.h>
20 #include <JavaScriptCore/JavaScript.h>
23 #define LENGTH(x) (sizeof x / sizeof x[0])
24 #define CLEANMASK(mask) (mask & ~(GDK_MOD2_MASK))
26 enum { AtomFind, AtomGo, AtomUri, AtomHiLight, AtomLast };
28 typedef union Arg Arg;
35 typedef struct Client {
36 GtkWidget *win, *scroll, *vbox, *indicator;
38 char *title, *linkhover;
39 const char *uri, *needle;
47 void (*func)(Client *c, const Arg *arg);
54 void (*func)(Client *c, const Arg *arg);
59 static Atom atoms[AtomLast];
60 static Client *clients = NULL;
61 static GdkNativeWindow embed = 0;
62 static gboolean showxid = FALSE;
63 static char winid[64];
64 static char *progname;
65 static gboolean loadimage = 1, plugin = 1, script = 1;
67 static char *buildpath(const char *path);
68 static void cleanup(void);
69 static void clipboard(Client *c, const Arg *arg);
70 static char *copystr(char **str, const char *src);
71 static WebKitWebView *createwindow(WebKitWebView *v, WebKitWebFrame *f, Client *c);
72 static gboolean decidedownload(WebKitWebView *v, WebKitWebFrame *f, WebKitNetworkRequest *r, gchar *m, WebKitWebPolicyDecision *p, Client *c);
73 static gboolean decidewindow(WebKitWebView *v, WebKitWebFrame *f, WebKitNetworkRequest *r, WebKitWebNavigationAction *n, WebKitWebPolicyDecision *p, Client *c);
74 static void destroyclient(Client *c);
75 static void destroywin(GtkWidget* w, Client *c);
76 static void die(char *str);
77 static void drawindicator(Client *c);
78 static gboolean exposeindicator(GtkWidget *w, GdkEventExpose *e, Client *c);
79 static void find(Client *c, const Arg *arg);
80 static const char *getatom(Client *c, int a);
81 static const char *getcookies(SoupURI *uri);
82 static char *geturi(Client *c);
83 void gotheaders(SoupMessage *msg, gpointer user_data);
84 static gboolean keypress(GtkWidget *w, GdkEventKey *ev, Client *c);
85 static void linkhover(WebKitWebView *v, const char* t, const char* l, Client *c);
86 static void loadstatuschange(WebKitWebView *view, GParamSpec *pspec, Client *c);
87 static void loaduri(Client *c, const Arg *arg);
88 static void navigate(Client *c, const Arg *arg);
89 static Client *newclient(void);
90 static void newwindow(Client *c, const Arg *arg);
91 static void newrequest(SoupSession *s, SoupMessage *msg, gpointer v);
92 static void pasteuri(GtkClipboard *clipboard, const char *text, gpointer d);
93 static void print(Client *c, const Arg *arg);
94 static GdkFilterReturn processx(GdkXEvent *xevent, GdkEvent *event, gpointer d);
95 static void progresschange(WebKitWebView *view, GParamSpec *pspec, Client *c);
96 static void reload(Client *c, const Arg *arg);
97 static void resize(GtkWidget *w, GtkAllocation *a, Client *c);
98 static void scroll(Client *c, const Arg *arg);
99 static void setatom(Client *c, int a, const char *v);
100 static void setcookie(SoupCookie *c);
101 static void setup(void);
102 static void sigchld(int unused);
103 static void source(Client *c, const Arg *arg);
104 static void spawn(Client *c, const Arg *arg);
105 static void stop(Client *c, const Arg *arg);
106 static void titlechange(WebKitWebView *v, WebKitWebFrame* frame, const char* title, Client *c);
107 static void update(Client *c);
108 static void updatewinid(Client *c);
109 static void usage(void);
110 static void windowobjectcleared(GtkWidget *w, WebKitWebFrame *frame, JSContextRef js, JSObjectRef win, Client *c);
111 static void zoom(Client *c, const Arg *arg);
113 /* configuration, allows nested code to access above variables */
117 buildpath(const char *path) {
121 /* creating directory */
123 apath = g_strdup(path);
125 apath = g_strconcat(g_get_home_dir(), "/", path, NULL);
126 if((p = strrchr(apath, '/'))) {
128 g_mkdir_with_parents(apath, 0755);
131 /* creating file (gives error when apath ends with "/") */
132 if((f = fopen(apath, "a")))
140 destroyclient(clients);
147 runscript(WebKitWebFrame *frame, JSContextRef js) {
148 JSStringRef jsscript;
150 JSValueRef exception = NULL;
153 if(g_file_get_contents(scriptfile, &script, NULL, &error)) {
154 jsscript = JSStringCreateWithUTF8CString(script);
155 JSEvaluateScript(js, jsscript, JSContextGetGlobalObject(js), NULL, 0, &exception);
160 clipboard(Client *c, const Arg *arg) {
161 gboolean paste = *(gboolean *)arg;
164 gtk_clipboard_request_text(gtk_clipboard_get(GDK_SELECTION_PRIMARY), pasteuri, c);
166 gtk_clipboard_set_text(gtk_clipboard_get(GDK_SELECTION_PRIMARY), c->linkhover ? c->linkhover : geturi(c), -1);
170 copystr(char **str, const char *src) {
182 createwindow(WebKitWebView *v, WebKitWebFrame *f, Client *c) {
183 Client *n = newclient();
188 decidedownload(WebKitWebView *v, WebKitWebFrame *f, WebKitNetworkRequest *r, gchar *m, WebKitWebPolicyDecision *p, Client *c) {
189 if(!webkit_web_view_can_show_mime_type(v, m)) {
190 webkit_web_policy_decision_ignore(p);
191 webkit_web_view_load_html_string(c->view,
192 "Can't display content.",
193 webkit_network_request_get_uri(r));
200 decidewindow(WebKitWebView *view, WebKitWebFrame *f, WebKitNetworkRequest *r, WebKitWebNavigationAction *n, WebKitWebPolicyDecision *p, Client *c) {
203 if(webkit_web_navigation_action_get_reason(n) == WEBKIT_WEB_NAVIGATION_REASON_LINK_CLICKED) {
204 webkit_web_policy_decision_ignore(p);
205 arg.v = (void *)webkit_network_request_get_uri(r);
206 newwindow(NULL, &arg);
213 destroyclient(Client *c) {
216 gtk_widget_destroy(c->indicator);
217 gtk_widget_destroy(GTK_WIDGET(c->view));
218 gtk_widget_destroy(c->scroll);
219 gtk_widget_destroy(c->vbox);
220 gtk_widget_destroy(c->win);
222 for(p = clients; p && p->next != c; p = p->next);
233 destroywin(GtkWidget* w, Client *c) {
244 drawindicator(Client *c) {
253 width = c->progress * w->allocation.width / 100;
254 gc = gdk_gc_new(w->window);
255 gdk_color_parse(strstr(uri, "https://") == uri ?
256 progress_trust : progress, &fg);
257 gdk_gc_set_rgb_fg_color(gc, &fg);
258 gdk_draw_rectangle(w->window,
259 w->style->bg_gc[GTK_WIDGET_STATE(w)],
260 TRUE, 0, 0, w->allocation.width, w->allocation.height);
261 gdk_draw_rectangle(w->window, gc, TRUE, 0, 0, width,
262 w->allocation.height);
267 exposeindicator(GtkWidget *w, GdkEventExpose *e, Client *c) {
273 find(Client *c, const Arg *arg) {
276 s = getatom(c, AtomFind);
277 gboolean forward = *(gboolean *)arg;
278 webkit_web_view_search_text(c->view, s, FALSE, forward, TRUE);
282 getcookies(SoupURI *uri) {
284 SoupCookieJar *j = soup_cookie_jar_text_new(cookiefile, TRUE);
285 c = soup_cookie_jar_get_cookies(j, uri, TRUE);
291 getatom(Client *c, int a) {
292 static char buf[BUFSIZ];
295 unsigned long ldummy;
296 unsigned char *p = NULL;
298 XGetWindowProperty(dpy, GDK_WINDOW_XID(GTK_WIDGET(c->win)->window),
299 atoms[a], 0L, BUFSIZ, False, XA_STRING,
300 &adummy, &idummy, &ldummy, &ldummy, &p);
302 strncpy(buf, (char *)p, LENGTH(buf)-1);
313 if(!(uri = (char *)webkit_web_view_get_uri(c->view)))
319 gotheaders(SoupMessage *msg, gpointer v) {
323 uri = soup_message_get_uri(msg);
324 for(p = l = soup_cookies_from_response(msg); p;
325 p = g_slist_next(p)) {
326 setcookie((SoupCookie *)p->data);
328 soup_cookies_free(l);
332 keypress(GtkWidget* w, GdkEventKey *ev, Client *c) {
334 gboolean processed = FALSE;
337 for(i = 0; i < LENGTH(keys); i++) {
338 if(gdk_keyval_to_lower(ev->keyval) == keys[i].keyval
339 && CLEANMASK(ev->state) == keys[i].mod
341 keys[i].func(c, &(keys[i].arg));
349 linkhover(WebKitWebView *v, const char* t, const char* l, Client *c) {
351 c->linkhover = copystr(&c->linkhover, l);
353 else if(c->linkhover) {
361 loadstatuschange(WebKitWebView *view, GParamSpec *pspec, Client *c) {
362 switch(webkit_web_view_get_load_status (c->view)) {
363 case WEBKIT_LOAD_COMMITTED:
364 setatom(c, AtomUri, geturi(c));
366 case WEBKIT_LOAD_FINISHED:
376 loaduri(Client *c, const Arg *arg) {
378 const char *uri = (char *)arg->v;
379 Arg a = { .b = FALSE };
381 if(strcmp(uri, "") == 0)
383 u = g_strrstr(uri, "://") ? g_strdup(uri)
384 : g_strdup_printf("http://%s", uri);
385 /* prevents endless loop */
386 if(c->uri && strcmp(u, c->uri) == 0) {
390 webkit_web_view_load_uri(c->view, u);
392 c->title = copystr(&c->title, u);
399 navigate(Client *c, const Arg *arg) {
400 int steps = *(int *)arg;
401 webkit_web_view_go_back_or_forward(c->view, steps);
407 WebKitWebSettings *settings;
408 WebKitWebFrame *frame;
409 GdkGeometry hints = { 1, 1 };
412 if(!(c = calloc(1, sizeof(Client))))
413 die("Cannot malloc!\n");
416 c->win = gtk_plug_new(embed);
419 c->win = gtk_window_new(GTK_WINDOW_TOPLEVEL);
420 /* TA: 20091214: Despite what the GNOME docs say, the ICCCM
421 * is always correct, so we should still call this function.
422 * But when doing so, we *must* differentiate between a
423 * WM_CLASS and a resource on the window. By convention, the
424 * window class (WM_CLASS) is capped, while the resource is in
425 * lowercase. Both these values come as a pair.
427 gtk_window_set_wmclass(GTK_WINDOW(c->win), "surf", "surf");
429 /* TA: 20091214: And set the role here as well -- so that
430 * sessions can pick this up.
432 gtk_window_set_role(GTK_WINDOW(c->win), "Surf");
434 gtk_window_set_default_size(GTK_WINDOW(c->win), 800, 600);
435 g_signal_connect(G_OBJECT(c->win), "destroy", G_CALLBACK(destroywin), c);
436 g_signal_connect(G_OBJECT(c->win), "key-press-event", G_CALLBACK(keypress), c);
437 g_signal_connect(G_OBJECT(c->win), "size-allocate", G_CALLBACK(resize), c);
440 c->vbox = gtk_vbox_new(FALSE, 0);
442 /* Scrolled Window */
443 c->scroll = gtk_scrolled_window_new(NULL, NULL);
444 gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(c->scroll),
445 GTK_POLICY_NEVER, GTK_POLICY_NEVER);
448 c->view = WEBKIT_WEB_VIEW(webkit_web_view_new());
449 g_signal_connect(G_OBJECT(c->view), "title-changed", G_CALLBACK(titlechange), c);
450 g_signal_connect(G_OBJECT(c->view), "hovering-over-link", G_CALLBACK(linkhover), c);
451 g_signal_connect(G_OBJECT(c->view), "create-web-view", G_CALLBACK(createwindow), c);
452 g_signal_connect(G_OBJECT(c->view), "new-window-policy-decision-requested", G_CALLBACK(decidewindow), c);
453 g_signal_connect(G_OBJECT(c->view), "mime-type-policy-decision-requested", G_CALLBACK(decidedownload), c);
454 g_signal_connect(G_OBJECT(c->view), "window-object-cleared", G_CALLBACK(windowobjectcleared), c);
455 g_signal_connect(G_OBJECT(c->view), "notify::load-status", G_CALLBACK(loadstatuschange), c);
456 g_signal_connect(G_OBJECT(c->view), "notify::progress", G_CALLBACK(progresschange), c);
459 c->indicator = gtk_drawing_area_new();
460 gtk_widget_set_size_request(c->indicator, 0, 2);
461 g_signal_connect (G_OBJECT (c->indicator), "expose_event",
462 G_CALLBACK (exposeindicator), c);
465 gtk_container_add(GTK_CONTAINER(c->scroll), GTK_WIDGET(c->view));
466 gtk_container_add(GTK_CONTAINER(c->win), c->vbox);
467 gtk_container_add(GTK_CONTAINER(c->vbox), c->scroll);
468 gtk_container_add(GTK_CONTAINER(c->vbox), c->indicator);
471 gtk_box_set_child_packing(GTK_BOX(c->vbox), c->indicator, FALSE, FALSE, 0, GTK_PACK_START);
472 gtk_box_set_child_packing(GTK_BOX(c->vbox), c->scroll, TRUE, TRUE, 0, GTK_PACK_START);
473 gtk_widget_grab_focus(GTK_WIDGET(c->view));
474 gtk_widget_show(c->vbox);
475 gtk_widget_show(c->indicator);
476 gtk_widget_show(c->scroll);
477 gtk_widget_show(GTK_WIDGET(c->view));
478 gtk_widget_show(c->win);
479 gtk_window_set_geometry_hints(GTK_WINDOW(c->win), NULL, &hints, GDK_HINT_MIN_SIZE);
480 gdk_window_set_events(GTK_WIDGET(c->win)->window, GDK_ALL_EVENTS_MASK);
481 gdk_window_add_filter(GTK_WIDGET(c->win)->window, processx, c);
482 webkit_web_view_set_full_content_zoom(c->view, TRUE);
483 frame = webkit_web_view_get_main_frame(c->view);
484 runscript(frame, webkit_web_frame_get_global_context(frame));
485 settings = webkit_web_view_get_settings(c->view);
486 if(!(ua = getenv("SURF_USERAGENT")))
488 g_object_set(G_OBJECT(settings), "user-agent", ua, NULL);
489 uri = g_strconcat("file://", stylefile, NULL);
490 g_object_set(G_OBJECT(settings), "user-stylesheet-uri", uri, NULL);
491 g_object_set(G_OBJECT(settings), "auto-load-images", loadimage, NULL);
492 g_object_set(G_OBJECT(settings), "enable-plugins", plugin, NULL);
493 g_object_set(G_OBJECT(settings), "enable-scripts", script, NULL);
496 setatom(c, AtomFind, "");
497 setatom(c, AtomUri, "about:blank");
499 webkit_web_view_set_transparent(c->view, TRUE);
505 gdk_display_sync(gtk_widget_get_display(c->win));
506 printf("%u\n", (guint)GDK_WINDOW_XID(GTK_WIDGET(c->win)->window));
513 newrequest(SoupSession *s, SoupMessage *msg, gpointer v) {
514 SoupMessageHeaders *h = msg->request_headers;
518 soup_message_headers_remove(h, "Cookie");
519 uri = soup_message_get_uri(msg);
520 if((c = getcookies(uri)))
521 soup_message_headers_append(h, "Cookie", c);
522 g_signal_connect_after(G_OBJECT(msg), "got-headers", G_CALLBACK(gotheaders), NULL);
526 newwindow(Client *c, const Arg *arg) {
528 const char *cmd[10], *uri;
529 const Arg a = { .v = (void *)cmd };
535 snprintf(tmp, LENGTH(tmp), "%u\n", (int)embed);
547 uri = arg->v ? (char *)arg->v : c->linkhover;
555 pasteuri(GtkClipboard *clipboard, const char *text, gpointer d) {
556 Arg arg = {.v = text };
558 loaduri((Client *) d, &arg);
562 print(Client *c, const Arg *arg) {
563 webkit_web_frame_print(webkit_web_view_get_main_frame(c->view));
567 processx(GdkXEvent *e, GdkEvent *event, gpointer d) {
568 Client *c = (Client *)d;
572 if(((XEvent *)e)->type == PropertyNotify) {
573 ev = &((XEvent *)e)->xproperty;
574 if(ev->state == PropertyNewValue) {
575 if(ev->atom == atoms[AtomFind]) {
578 return GDK_FILTER_REMOVE;
580 else if(ev->atom == atoms[AtomGo]) {
581 arg.v = getatom(c, AtomGo);
583 return GDK_FILTER_REMOVE;
587 return GDK_FILTER_CONTINUE;
591 progresschange(WebKitWebView *view, GParamSpec *pspec, Client *c) {
592 c->progress = webkit_web_view_get_progress(c->view) * 100;
597 reload(Client *c, const Arg *arg) {
598 gboolean nocache = *(gboolean *)arg;
600 webkit_web_view_reload_bypass_cache(c->view);
602 webkit_web_view_reload(c->view);
606 resize(GtkWidget *w, GtkAllocation *a, Client *c) {
611 zoom = webkit_web_view_get_zoom_level(c->view);
612 if(a->width * a->height < 300 * 400 && zoom != 0.2)
613 webkit_web_view_set_zoom_level(c->view, 0.2);
615 webkit_web_view_set_zoom_level(c->view, 1.0);
619 scroll(Client *c, const Arg *arg) {
623 a = gtk_scrolled_window_get_vadjustment(GTK_SCROLLED_WINDOW(c->scroll));
624 v = gtk_adjustment_get_value(a);
625 v += gtk_adjustment_get_step_increment(a) * arg->i;
627 v = MIN(v, gtk_adjustment_get_upper(a) - gtk_adjustment_get_page_size(a));
628 gtk_adjustment_set_value(a, v);
632 setcookie(SoupCookie *c) {
635 lock = open(cookiefile, 0);
636 flock(lock, LOCK_EX);
638 SoupCookieJar *j = soup_cookie_jar_text_new(cookiefile, FALSE);
639 c = soup_cookie_copy(c);
640 if(c->expires == NULL && sessiontime) {
641 e = soup_date_new_from_time_t(time(NULL) + sessiontime);
642 soup_cookie_set_expires(c, e);
644 soup_cookie_jar_add_cookie(j, c);
646 flock(lock, LOCK_UN);
651 setatom(Client *c, int a, const char *v) {
653 XChangeProperty(dpy, GDK_WINDOW_XID(GTK_WIDGET(c->win)->window), atoms[a],
654 XA_STRING, 8, PropModeReplace, (unsigned char *)v,
665 /* clean up any zombies immediately */
667 gtk_init(NULL, NULL);
668 if (!g_thread_supported())
672 s = webkit_get_default_session();
675 atoms[AtomFind] = XInternAtom(dpy, "_SURF_FIND", False);
676 atoms[AtomGo] = XInternAtom(dpy, "_SURF_GO", False);
677 atoms[AtomUri] = XInternAtom(dpy, "_SURF_URI", False);
678 atoms[AtomHiLight] = XInternAtom(dpy, "_SURF_HILIGHT", False);
681 cookiefile = buildpath(cookiefile);
682 scriptfile = buildpath(scriptfile);
683 stylefile = buildpath(stylefile);
685 /* request handler */
686 s = webkit_get_default_session();
687 soup_session_remove_feature_by_type(s, soup_cookie_get_type());
688 soup_session_remove_feature_by_type(s, soup_cookie_jar_get_type());
689 g_signal_connect_after(G_OBJECT(s), "request-started", G_CALLBACK(newrequest), NULL);
692 if((proxy = getenv("http_proxy")) && strcmp(proxy, "")) {
693 new_proxy = g_strrstr(proxy, "http://") ? g_strdup(proxy) :
694 g_strdup_printf("http://%s", proxy);
695 puri = soup_uri_new(new_proxy);
696 g_object_set(G_OBJECT(s), "proxy-uri", puri, NULL);
703 sigchld(int unused) {
704 if(signal(SIGCHLD, sigchld) == SIG_ERR)
705 die("Can't install SIGCHLD handler");
706 while(0 < waitpid(-1, NULL, WNOHANG));
710 source(Client *c, const Arg *arg) {
711 Arg a = { .b = FALSE };
714 s = webkit_web_view_get_view_source_mode(c->view);
715 webkit_web_view_set_view_source_mode(c->view, !s);
720 spawn(Client *c, const Arg *arg) {
723 close(ConnectionNumber(dpy));
725 execvp(((char **)arg->v)[0], (char **)arg->v);
726 fprintf(stderr, "surf: execvp %s", ((char **)arg->v)[0]);
733 stop(Client *c, const Arg *arg) {
734 webkit_web_view_stop_loading(c->view);
738 titlechange(WebKitWebView *v, WebKitWebFrame *f, const char *t, Client *c) {
739 c->title = copystr(&c->title, t);
747 if(c->progress != 100)
748 t = g_strdup_printf("[%i%%] %s", c->progress, c->title);
749 else if(c->linkhover)
750 t = g_strdup(c->linkhover);
752 t = g_strdup(c->title);
754 gtk_window_set_title(GTK_WINDOW(c->win), t);
759 updatewinid(Client *c) {
760 snprintf(winid, LENGTH(winid), "%u",
761 (int)GDK_WINDOW_XID(GTK_WIDGET(c->win)->window));
766 fputs("surf - simple browser\n", stderr);
767 die("usage: surf [-e xid] [-i] [-p] [-s] [-v] [-x] [uri]\n");
771 windowobjectcleared(GtkWidget *w, WebKitWebFrame *frame, JSContextRef js, JSObjectRef win, Client *c) {
772 runscript(frame, js);
776 zoom(Client *c, const Arg *arg) {
778 if(arg->i < 0) /* zoom out */
779 webkit_web_view_zoom_out(c->view);
780 else if(arg->i > 0) /* zoom in */
781 webkit_web_view_zoom_in(c->view);
784 webkit_web_view_set_zoom_level(c->view, 1.0);
789 main(int argc, char *argv[]) {
794 /* command line args */
795 for(i = 1, arg.v = NULL; i < argc && argv[i][0] == '-' &&
796 argv[i][1] != '\0' && argv[i][2] == '\0'; i++) {
797 if(!strcmp(argv[i], "--")) {
804 embed = atoi(argv[i]);
821 die("surf-"VERSION", © 2009 surf engineers, see LICENSE for details\n");
831 loaduri(clients, &arg);