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])
25 enum { AtomFind, AtomGo, AtomUri, AtomLast };
27 typedef union Arg Arg;
34 typedef struct Client {
35 GtkWidget *win, *scroll, *vbox, *indicator;
37 char *title, *linkhover;
38 const char *uri, *needle;
46 void (*func)(Client *c, const Arg *arg);
53 void (*func)(Client *c, const Arg *arg);
58 static Atom atoms[AtomLast];
59 static Client *clients = NULL;
60 static GdkNativeWindow embed = 0;
61 static gboolean showxid = FALSE;
62 static char winid[64];
63 static char *progname;
64 static gboolean loadimage = 1, plugin = 1, script = 1;
66 static char *buildpath(const char *path);
67 static void cleanup(void);
68 static void clipboard(Client *c, const Arg *arg);
69 static char *copystr(char **str, const char *src);
70 static WebKitWebView *createwindow(WebKitWebView *v, WebKitWebFrame *f, Client *c);
71 static gboolean decidedownload(WebKitWebView *v, WebKitWebFrame *f, WebKitNetworkRequest *r, gchar *m, WebKitWebPolicyDecision *p, Client *c);
72 static gboolean decidewindow(WebKitWebView *v, WebKitWebFrame *f, WebKitNetworkRequest *r, WebKitWebNavigationAction *n, WebKitWebPolicyDecision *p, Client *c);
73 static void destroyclient(Client *c);
74 static void destroywin(GtkWidget* w, Client *c);
75 static void die(char *str);
76 static void drawindicator(Client *c);
77 static gboolean exposeindicator(GtkWidget *w, GdkEventExpose *e, Client *c);
78 static void find(Client *c, const Arg *arg);
79 static const char *getatom(Client *c, int a);
80 static const char *getcookies(SoupURI *uri);
81 static char *geturi(Client *c);
82 void gotheaders(SoupMessage *msg, gpointer user_data);
83 static gboolean initdownload(WebKitWebView *v, WebKitDownload *o, Client *c);
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 eval(Client *c, const Arg *arg);
106 static void stop(Client *c, const Arg *arg);
107 static void titlechange(WebKitWebView *v, WebKitWebFrame* frame, const char* title, Client *c);
108 static void update(Client *c);
109 static void updatewinid(Client *c);
110 static void usage(void);
111 static void windowobjectcleared(GtkWidget *w, WebKitWebFrame *frame, JSContextRef js, JSObjectRef win, Client *c);
112 static void zoom(Client *c, const Arg *arg);
114 /* configuration, allows nested code to access above variables */
118 buildpath(const char *path) {
122 /* creating directory */
124 apath = g_strdup(path);
126 apath = g_strconcat(g_get_home_dir(), "/", path, NULL);
127 if((p = strrchr(apath, '/'))) {
129 g_mkdir_with_parents(apath, 0755);
132 /* creating file (gives error when apath ends with "/") */
133 if((f = fopen(apath, "a")))
141 destroyclient(clients);
148 evalscript(WebKitWebFrame *frame, JSContextRef js, char *script, char* scriptname) {
149 JSStringRef jsscript, jsscriptname;
150 JSValueRef exception = NULL;
152 jsscript = JSStringCreateWithUTF8CString(script);
153 jsscriptname = JSStringCreateWithUTF8CString(scriptname);
154 JSEvaluateScript(js, jsscript, JSContextGetGlobalObject(js), jsscriptname, 0, &exception);
155 JSStringRelease(jsscript);
156 JSStringRelease(jsscriptname);
160 runscript(WebKitWebFrame *frame, JSContextRef js) {
164 if(g_file_get_contents(scriptfile, &script, NULL, &error)) {
165 evalscript(frame, webkit_web_frame_get_global_context(frame), script, scriptfile);
170 clipboard(Client *c, const Arg *arg) {
171 gboolean paste = *(gboolean *)arg;
174 gtk_clipboard_request_text(gtk_clipboard_get(GDK_SELECTION_PRIMARY), pasteuri, c);
176 gtk_clipboard_set_text(gtk_clipboard_get(GDK_SELECTION_PRIMARY), c->linkhover ? c->linkhover : geturi(c), -1);
180 copystr(char **str, const char *src) {
192 createwindow(WebKitWebView *v, WebKitWebFrame *f, Client *c) {
193 Client *n = newclient();
198 decidedownload(WebKitWebView *v, WebKitWebFrame *f, WebKitNetworkRequest *r, gchar *m, WebKitWebPolicyDecision *p, Client *c) {
199 if(!webkit_web_view_can_show_mime_type(v, m)) {
200 webkit_web_policy_decision_download(p);
207 decidewindow(WebKitWebView *view, WebKitWebFrame *f, WebKitNetworkRequest *r, WebKitWebNavigationAction *n, WebKitWebPolicyDecision *p, Client *c) {
210 if(webkit_web_navigation_action_get_reason(n) == WEBKIT_WEB_NAVIGATION_REASON_LINK_CLICKED) {
211 webkit_web_policy_decision_ignore(p);
212 arg.v = (void *)webkit_network_request_get_uri(r);
213 newwindow(NULL, &arg);
220 destroyclient(Client *c) {
223 webkit_web_view_stop_loading(c->view);
224 gtk_widget_destroy(c->indicator);
225 gtk_widget_destroy(GTK_WIDGET(c->view));
226 gtk_widget_destroy(c->scroll);
227 gtk_widget_destroy(c->vbox);
228 gtk_widget_destroy(c->win);
230 for(p = clients; p && p->next != c; p = p->next);
241 destroywin(GtkWidget* w, Client *c) {
252 drawindicator(Client *c) {
261 width = c->progress * w->allocation.width / 100;
262 gc = gdk_gc_new(w->window);
263 gdk_color_parse(strstr(uri, "https://") == uri ?
264 progress_trust : progress, &fg);
265 gdk_gc_set_rgb_fg_color(gc, &fg);
266 gdk_draw_rectangle(w->window,
267 w->style->bg_gc[GTK_WIDGET_STATE(w)],
268 TRUE, 0, 0, w->allocation.width, w->allocation.height);
269 gdk_draw_rectangle(w->window, gc, TRUE, 0, 0, width,
270 w->allocation.height);
275 exposeindicator(GtkWidget *w, GdkEventExpose *e, Client *c) {
281 find(Client *c, const Arg *arg) {
284 s = getatom(c, AtomFind);
285 gboolean forward = *(gboolean *)arg;
286 webkit_web_view_search_text(c->view, s, FALSE, forward, TRUE);
290 getcookies(SoupURI *uri) {
292 SoupCookieJar *j = soup_cookie_jar_text_new(cookiefile, TRUE);
293 c = soup_cookie_jar_get_cookies(j, uri, TRUE);
299 getatom(Client *c, int a) {
300 static char buf[BUFSIZ];
303 unsigned long ldummy;
304 unsigned char *p = NULL;
306 XGetWindowProperty(dpy, GDK_WINDOW_XID(GTK_WIDGET(c->win)->window),
307 atoms[a], 0L, BUFSIZ, False, XA_STRING,
308 &adummy, &idummy, &ldummy, &ldummy, &p);
310 strncpy(buf, (char *)p, LENGTH(buf)-1);
321 if(!(uri = (char *)webkit_web_view_get_uri(c->view)))
327 gotheaders(SoupMessage *msg, gpointer v) {
331 uri = soup_message_get_uri(msg);
332 for(p = l = soup_cookies_from_response(msg); p;
333 p = g_slist_next(p)) {
334 setcookie((SoupCookie *)p->data);
336 soup_cookies_free(l);
340 initdownload(WebKitWebView *view, WebKitDownload *o, Client *c) {
344 arg = (Arg)DOWNLOAD((char *)webkit_download_get_uri(o));
350 keypress(GtkWidget* w, GdkEventKey *ev, Client *c) {
352 gboolean processed = FALSE;
355 for(i = 0; i < LENGTH(keys); i++) {
356 if(gdk_keyval_to_lower(ev->keyval) == keys[i].keyval
357 && (ev->state & keys[i].mod) == keys[i].mod
359 keys[i].func(c, &(keys[i].arg));
367 linkhover(WebKitWebView *v, const char* t, const char* l, Client *c) {
369 c->linkhover = copystr(&c->linkhover, l);
371 else if(c->linkhover) {
379 loadstatuschange(WebKitWebView *view, GParamSpec *pspec, Client *c) {
380 switch(webkit_web_view_get_load_status (c->view)) {
381 case WEBKIT_LOAD_COMMITTED:
382 setatom(c, AtomUri, geturi(c));
384 case WEBKIT_LOAD_FINISHED:
394 loaduri(Client *c, const Arg *arg) {
396 const char *uri = (char *)arg->v;
397 Arg a = { .b = FALSE };
399 if(strcmp(uri, "") == 0)
401 u = g_strrstr(uri, "://") ? g_strdup(uri)
402 : g_strdup_printf("http://%s", uri);
403 /* prevents endless loop */
404 if(c->uri && strcmp(u, c->uri) == 0) {
408 webkit_web_view_load_uri(c->view, u);
410 c->title = copystr(&c->title, u);
417 navigate(Client *c, const Arg *arg) {
418 int steps = *(int *)arg;
419 webkit_web_view_go_back_or_forward(c->view, steps);
425 WebKitWebSettings *settings;
426 WebKitWebFrame *frame;
427 GdkGeometry hints = { 1, 1 };
430 if(!(c = calloc(1, sizeof(Client))))
431 die("Cannot malloc!\n");
434 c->win = gtk_plug_new(embed);
437 c->win = gtk_window_new(GTK_WINDOW_TOPLEVEL);
438 /* TA: 20091214: Despite what the GNOME docs say, the ICCCM
439 * is always correct, so we should still call this function.
440 * But when doing so, we *must* differentiate between a
441 * WM_CLASS and a resource on the window. By convention, the
442 * window class (WM_CLASS) is capped, while the resource is in
443 * lowercase. Both these values come as a pair.
445 gtk_window_set_wmclass(GTK_WINDOW(c->win), "surf", "surf");
447 /* TA: 20091214: And set the role here as well -- so that
448 * sessions can pick this up.
450 gtk_window_set_role(GTK_WINDOW(c->win), "Surf");
452 gtk_window_set_default_size(GTK_WINDOW(c->win), 800, 600);
453 g_signal_connect(G_OBJECT(c->win), "destroy", G_CALLBACK(destroywin), c);
454 g_signal_connect(G_OBJECT(c->win), "key-press-event", G_CALLBACK(keypress), c);
455 g_signal_connect(G_OBJECT(c->win), "size-allocate", G_CALLBACK(resize), c);
458 c->vbox = gtk_vbox_new(FALSE, 0);
460 /* Scrolled Window */
461 c->scroll = gtk_scrolled_window_new(NULL, NULL);
462 gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(c->scroll),
463 GTK_POLICY_NEVER, GTK_POLICY_NEVER);
466 c->view = WEBKIT_WEB_VIEW(webkit_web_view_new());
467 g_signal_connect(G_OBJECT(c->view), "title-changed", G_CALLBACK(titlechange), c);
468 g_signal_connect(G_OBJECT(c->view), "hovering-over-link", G_CALLBACK(linkhover), c);
469 g_signal_connect(G_OBJECT(c->view), "create-web-view", G_CALLBACK(createwindow), c);
470 g_signal_connect(G_OBJECT(c->view), "new-window-policy-decision-requested", G_CALLBACK(decidewindow), c);
471 g_signal_connect(G_OBJECT(c->view), "mime-type-policy-decision-requested", G_CALLBACK(decidedownload), c);
472 g_signal_connect(G_OBJECT(c->view), "window-object-cleared", G_CALLBACK(windowobjectcleared), c);
473 g_signal_connect(G_OBJECT(c->view), "notify::load-status", G_CALLBACK(loadstatuschange), c);
474 g_signal_connect(G_OBJECT(c->view), "notify::progress", G_CALLBACK(progresschange), c);
475 g_signal_connect(G_OBJECT(c->view), "download-requested", G_CALLBACK(initdownload), c);
478 c->indicator = gtk_drawing_area_new();
479 gtk_widget_set_size_request(c->indicator, 0, 2);
480 g_signal_connect (G_OBJECT (c->indicator), "expose_event",
481 G_CALLBACK (exposeindicator), c);
484 gtk_container_add(GTK_CONTAINER(c->scroll), GTK_WIDGET(c->view));
485 gtk_container_add(GTK_CONTAINER(c->win), c->vbox);
486 gtk_container_add(GTK_CONTAINER(c->vbox), c->scroll);
487 gtk_container_add(GTK_CONTAINER(c->vbox), c->indicator);
490 gtk_box_set_child_packing(GTK_BOX(c->vbox), c->indicator, FALSE, FALSE, 0, GTK_PACK_START);
491 gtk_box_set_child_packing(GTK_BOX(c->vbox), c->scroll, TRUE, TRUE, 0, GTK_PACK_START);
492 gtk_widget_grab_focus(GTK_WIDGET(c->view));
493 gtk_widget_show(c->vbox);
494 gtk_widget_show(c->indicator);
495 gtk_widget_show(c->scroll);
496 gtk_widget_show(GTK_WIDGET(c->view));
497 gtk_widget_show(c->win);
498 gtk_window_set_geometry_hints(GTK_WINDOW(c->win), NULL, &hints, GDK_HINT_MIN_SIZE);
499 gdk_window_set_events(GTK_WIDGET(c->win)->window, GDK_ALL_EVENTS_MASK);
500 gdk_window_add_filter(GTK_WIDGET(c->win)->window, processx, c);
501 webkit_web_view_set_full_content_zoom(c->view, TRUE);
502 frame = webkit_web_view_get_main_frame(c->view);
503 runscript(frame, webkit_web_frame_get_global_context(frame));
504 settings = webkit_web_view_get_settings(c->view);
505 if(!(ua = getenv("SURF_USERAGENT")))
507 g_object_set(G_OBJECT(settings), "user-agent", ua, NULL);
508 uri = g_strconcat("file://", stylefile, NULL);
509 g_object_set(G_OBJECT(settings), "user-stylesheet-uri", uri, NULL);
510 g_object_set(G_OBJECT(settings), "auto-load-images", loadimage, NULL);
511 g_object_set(G_OBJECT(settings), "enable-plugins", plugin, NULL);
512 g_object_set(G_OBJECT(settings), "enable-scripts", script, NULL);
513 g_object_set(G_OBJECT(settings), "enable-spatial-navigation", true, NULL);
517 setatom(c, AtomFind, "");
518 setatom(c, AtomUri, "about:blank");
520 webkit_web_view_set_transparent(c->view, TRUE);
526 gdk_display_sync(gtk_widget_get_display(c->win));
527 printf("%u\n", (guint)GDK_WINDOW_XID(GTK_WIDGET(c->win)->window));
534 newrequest(SoupSession *s, SoupMessage *msg, gpointer v) {
535 SoupMessageHeaders *h = msg->request_headers;
539 soup_message_headers_remove(h, "Cookie");
540 uri = soup_message_get_uri(msg);
541 if((c = getcookies(uri)))
542 soup_message_headers_append(h, "Cookie", c);
543 g_signal_connect_after(G_OBJECT(msg), "got-headers", G_CALLBACK(gotheaders), NULL);
547 newwindow(Client *c, const Arg *arg) {
549 const char *cmd[10], *uri;
550 const Arg a = { .v = (void *)cmd };
556 snprintf(tmp, LENGTH(tmp), "%u\n", (int)embed);
568 uri = arg->v ? (char *)arg->v : c->linkhover;
576 pasteuri(GtkClipboard *clipboard, const char *text, gpointer d) {
577 Arg arg = {.v = text };
579 loaduri((Client *) d, &arg);
583 print(Client *c, const Arg *arg) {
584 webkit_web_frame_print(webkit_web_view_get_main_frame(c->view));
588 processx(GdkXEvent *e, GdkEvent *event, gpointer d) {
589 Client *c = (Client *)d;
593 if(((XEvent *)e)->type == PropertyNotify) {
594 ev = &((XEvent *)e)->xproperty;
595 if(ev->state == PropertyNewValue) {
596 if(ev->atom == atoms[AtomFind]) {
599 return GDK_FILTER_REMOVE;
601 else if(ev->atom == atoms[AtomGo]) {
602 arg.v = getatom(c, AtomGo);
604 return GDK_FILTER_REMOVE;
608 return GDK_FILTER_CONTINUE;
612 progresschange(WebKitWebView *view, GParamSpec *pspec, Client *c) {
613 c->progress = webkit_web_view_get_progress(c->view) * 100;
618 reload(Client *c, const Arg *arg) {
619 gboolean nocache = *(gboolean *)arg;
621 webkit_web_view_reload_bypass_cache(c->view);
623 webkit_web_view_reload(c->view);
627 resize(GtkWidget *w, GtkAllocation *a, Client *c) {
632 zoom = webkit_web_view_get_zoom_level(c->view);
633 if(a->width * a->height < 300 * 400 && zoom != 0.2)
634 webkit_web_view_set_zoom_level(c->view, 0.2);
636 webkit_web_view_set_zoom_level(c->view, 1.0);
640 scroll(Client *c, const Arg *arg) {
644 a = gtk_scrolled_window_get_vadjustment(GTK_SCROLLED_WINDOW(c->scroll));
645 v = gtk_adjustment_get_value(a);
646 v += gtk_adjustment_get_step_increment(a) * arg->i;
648 v = MIN(v, gtk_adjustment_get_upper(a) - gtk_adjustment_get_page_size(a));
649 gtk_adjustment_set_value(a, v);
653 setcookie(SoupCookie *c) {
656 lock = open(cookiefile, 0);
657 flock(lock, LOCK_EX);
659 SoupCookieJar *j = soup_cookie_jar_text_new(cookiefile, FALSE);
660 c = soup_cookie_copy(c);
661 if(c->expires == NULL && sessiontime) {
662 e = soup_date_new_from_time_t(time(NULL) + sessiontime);
663 soup_cookie_set_expires(c, e);
665 soup_cookie_jar_add_cookie(j, c);
667 flock(lock, LOCK_UN);
672 setatom(Client *c, int a, const char *v) {
674 XChangeProperty(dpy, GDK_WINDOW_XID(GTK_WIDGET(c->win)->window), atoms[a],
675 XA_STRING, 8, PropModeReplace, (unsigned char *)v,
686 /* clean up any zombies immediately */
688 gtk_init(NULL, NULL);
689 if (!g_thread_supported())
693 s = webkit_get_default_session();
696 atoms[AtomFind] = XInternAtom(dpy, "_SURF_FIND", False);
697 atoms[AtomGo] = XInternAtom(dpy, "_SURF_GO", False);
698 atoms[AtomUri] = XInternAtom(dpy, "_SURF_URI", False);
701 cookiefile = buildpath(cookiefile);
702 scriptfile = buildpath(scriptfile);
703 stylefile = buildpath(stylefile);
705 /* request handler */
706 s = webkit_get_default_session();
707 soup_session_remove_feature_by_type(s, soup_cookie_get_type());
708 soup_session_remove_feature_by_type(s, soup_cookie_jar_get_type());
709 g_signal_connect_after(G_OBJECT(s), "request-started", G_CALLBACK(newrequest), NULL);
712 if((proxy = getenv("http_proxy")) && strcmp(proxy, "")) {
713 new_proxy = g_strrstr(proxy, "http://") ? g_strdup(proxy) :
714 g_strdup_printf("http://%s", proxy);
715 puri = soup_uri_new(new_proxy);
716 g_object_set(G_OBJECT(s), "proxy-uri", puri, NULL);
723 sigchld(int unused) {
724 if(signal(SIGCHLD, sigchld) == SIG_ERR)
725 die("Can't install SIGCHLD handler");
726 while(0 < waitpid(-1, NULL, WNOHANG));
730 source(Client *c, const Arg *arg) {
731 Arg a = { .b = FALSE };
734 s = webkit_web_view_get_view_source_mode(c->view);
735 webkit_web_view_set_view_source_mode(c->view, !s);
740 spawn(Client *c, const Arg *arg) {
743 close(ConnectionNumber(dpy));
745 execvp(((char **)arg->v)[0], (char **)arg->v);
746 fprintf(stderr, "surf: execvp %s", ((char **)arg->v)[0]);
753 eval(Client *c, const Arg *arg) {
754 WebKitWebFrame *frame = webkit_web_view_get_main_frame(c->view);
755 evalscript(frame, webkit_web_frame_get_global_context(frame), ((char **)arg->v)[0], "");
759 stop(Client *c, const Arg *arg) {
760 webkit_web_view_stop_loading(c->view);
764 titlechange(WebKitWebView *v, WebKitWebFrame *f, const char *t, Client *c) {
765 c->title = copystr(&c->title, t);
773 if(c->progress != 100)
774 t = g_strdup_printf("[%i%%] %s", c->progress, c->title);
775 else if(c->linkhover)
776 t = g_strdup(c->linkhover);
778 t = g_strdup(c->title);
780 gtk_window_set_title(GTK_WINDOW(c->win), t);
785 updatewinid(Client *c) {
786 snprintf(winid, LENGTH(winid), "%u",
787 (int)GDK_WINDOW_XID(GTK_WIDGET(c->win)->window));
792 fputs("surf - simple browser\n", stderr);
793 die("usage: surf [-e xid] [-i] [-p] [-s] [-v] [-x] [uri]\n");
797 windowobjectcleared(GtkWidget *w, WebKitWebFrame *frame, JSContextRef js, JSObjectRef win, Client *c) {
798 runscript(frame, js);
802 zoom(Client *c, const Arg *arg) {
804 if(arg->i < 0) /* zoom out */
805 webkit_web_view_zoom_out(c->view);
806 else if(arg->i > 0) /* zoom in */
807 webkit_web_view_zoom_in(c->view);
810 webkit_web_view_set_zoom_level(c->view, 1.0);
815 main(int argc, char *argv[]) {
820 /* command line args */
821 for(i = 1, arg.v = NULL; i < argc && argv[i][0] == '-' &&
822 argv[i][1] != '\0' && argv[i][2] == '\0'; i++) {
823 if(!strcmp(argv[i], "--")) {
830 embed = atoi(argv[i]);
847 die("surf-"VERSION", © 2009 surf engineers, see LICENSE for details\n");
857 loaduri(clients, &arg);