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>
22 #define LENGTH(x) (sizeof x / sizeof x[0])
23 #define CLEANMASK(mask) (mask & ~(GDK_MOD2_MASK))
25 typedef union Arg Arg;
32 typedef struct Client {
33 GtkWidget *win, *scroll, *vbox, *indicator;
36 WebKitDownload *download;
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 uriprop, findprop;
59 static Client *clients = NULL;
60 static GdkNativeWindow embed = 0;
61 static gboolean showxid = FALSE;
62 static int ignorexprop = 0;
63 static char winid[64];
64 static char *progname;
66 static char *buildpath(const char *path);
67 static void cleanup(void);
68 static void clipboard(Client *c, const Arg *arg);
69 static void context(WebKitWebView *v, GtkMenu *m, Client *c);
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 download(Client *c, const Arg *arg);
78 static void drawindicator(Client *c);
79 static gboolean exposeindicator(GtkWidget *w, GdkEventExpose *e, Client *c);
80 static void find(Client *c, const Arg *arg);
81 static const char *getatom(Client *c, Atom a);
82 static char *geturi(Client *c);
83 static gboolean initdownload(WebKitWebView *v, WebKitDownload *o, Client *c);
84 static void itemclick(GtkMenuItem *mi, Client *c);
85 static gboolean keypress(GtkWidget *w, GdkEventKey *ev, Client *c);
86 static void linkhover(WebKitWebView *v, const char* t, const char* l, Client *c);
87 static void loadstatuschange(WebKitWebView *view, GParamSpec *pspec, Client *c);
88 static void loaduri(Client *c, const Arg *arg);
89 static void navigate(Client *c, const Arg *arg);
90 static Client *newclient(void);
91 static void newwindow(Client *c, const Arg *arg);
92 static void newrequest(WebKitWebView *v, WebKitWebFrame *f, WebKitWebResource *r, WebKitNetworkRequest *req, WebKitNetworkResponse *res, Client *c);
93 static void pasteuri(GtkClipboard *clipboard, const char *text, gpointer d);
94 static void print(Client *c, const Arg *arg);
95 static GdkFilterReturn processx(GdkXEvent *xevent, GdkEvent *event, gpointer d);
96 static void progresschange(WebKitWebView *view, GParamSpec *pspec, Client *c);
97 static void reload(Client *c, const Arg *arg);
98 static void resize(GtkWidget *w, GtkAllocation *a, Client *c);
99 static void scroll(Client *c, const Arg *arg);
100 static void setatom(Client *c, Atom a, const char *v);
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 updatedownload(WebKitDownload *o, GParamSpec *pspec, 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 = g_fopen(apath, "a")))
141 destroyclient(clients);
149 clipboard(Client *c, const Arg *arg) {
150 gboolean paste = *(gboolean *)arg;
153 gtk_clipboard_request_text(gtk_clipboard_get(GDK_SELECTION_PRIMARY), pasteuri, c);
155 gtk_clipboard_set_text(gtk_clipboard_get(GDK_SELECTION_PRIMARY), c->linkhover ? c->linkhover : geturi(c), -1);
159 context(WebKitWebView *v, GtkMenu *m, Client *c) {
161 GtkContainer *parent;
163 gtk_widget_hide_all(GTK_WIDGET(m));
164 gtk_widget_show(GTK_WIDGET(m));
165 for(i = 0; i < LENGTH(items); i++) {
166 parent = GTK_CONTAINER(gtk_widget_get_parent(c->items[i]));
168 gtk_container_remove(parent, c->items[i]);
169 gtk_menu_shell_append(GTK_MENU_SHELL(m), c->items[i]);
170 gtk_widget_show(c->items[i]);
175 copystr(char **str, const char *src) {
187 createwindow(WebKitWebView *v, WebKitWebFrame *f, Client *c) {
188 Client *n = newclient();
193 decidedownload(WebKitWebView *v, WebKitWebFrame *f, WebKitNetworkRequest *r, gchar *m, WebKitWebPolicyDecision *p, Client *c) {
194 if(!webkit_web_view_can_show_mime_type(v, m)) {
195 webkit_web_policy_decision_download(p);
202 decidewindow(WebKitWebView *view, WebKitWebFrame *f, WebKitNetworkRequest *r, WebKitWebNavigationAction *n, WebKitWebPolicyDecision *p, Client *c) {
205 if(webkit_web_navigation_action_get_reason(n) == WEBKIT_WEB_NAVIGATION_REASON_LINK_CLICKED) {
206 webkit_web_policy_decision_ignore(p);
207 arg.v = (void *)webkit_network_request_get_uri(r);
208 newwindow(NULL, &arg);
215 destroyclient(Client *c) {
219 gtk_widget_destroy(c->indicator);
220 gtk_widget_destroy(GTK_WIDGET(c->view));
221 gtk_widget_destroy(c->scroll);
222 gtk_widget_destroy(c->vbox);
223 gtk_widget_destroy(c->win);
224 for(i = 0; i < LENGTH(items); i++)
225 gtk_widget_destroy(c->items[i]);
228 for(p = clients; p && p->next != c; p = p->next);
239 destroywin(GtkWidget* w, Client *c) {
250 download(Client *c, const Arg *arg) {
252 WebKitNetworkRequest *r;
256 uri = (char *)arg->v;
258 uri = c->linkhover ? c->linkhover : geturi(c);
259 r = webkit_network_request_new(uri);
260 dl = webkit_download_new(r);
261 initdownload(c->view, dl, c);
265 drawindicator(Client *c) {
272 uri = getatom(c, uriprop);
274 width = c->progress * w->allocation.width / 100;
275 gc = gdk_gc_new(w->window);
276 gdk_color_parse(strstr(uri, "https://") == uri ?
277 progress_trust : progress, &fg);
278 gdk_gc_set_rgb_fg_color(gc, &fg);
279 gdk_draw_rectangle(w->window,
280 w->style->bg_gc[GTK_WIDGET_STATE(w)],
281 TRUE, 0, 0, w->allocation.width, w->allocation.height);
282 gdk_draw_rectangle(w->window, gc, TRUE, 0, 0, width,
283 w->allocation.height);
288 exposeindicator(GtkWidget *w, GdkEventExpose *e, Client *c) {
294 find(Client *c, const Arg *arg) {
297 s = getatom(c, findprop);
298 gboolean forward = *(gboolean *)arg;
299 webkit_web_view_search_text(c->view, s, FALSE, forward, TRUE);
303 getatom(Client *c, Atom a) {
304 static char buf[BUFSIZ];
307 unsigned long ldummy;
308 unsigned char *p = NULL;
310 XGetWindowProperty(dpy, GDK_WINDOW_XID(GTK_WIDGET(c->win)->window),
311 a, 0L, BUFSIZ, False, XA_STRING,
312 &adummy, &idummy, &ldummy, &ldummy, &p);
314 strncpy(buf, (char *)p, LENGTH(buf)-1);
325 if(!(uri = (char *)webkit_web_view_get_uri(c->view)))
331 initdownload(WebKitWebView *view, WebKitDownload *o, Client *c) {
332 const char *filename;
337 filename = webkit_download_get_suggested_filename(o);
338 if(!strcmp("", filename))
339 filename = "index.html";
340 uri = g_strconcat("file://", dldir, "/", filename, NULL);
341 webkit_download_set_destination_uri(c->download, uri);
344 html = g_strdup_printf("Download <b>%s</b>...", filename);
345 webkit_web_view_load_html_string(c->view, html,
346 webkit_download_get_uri(c->download));
347 g_signal_connect(c->download, "notify::progress", G_CALLBACK(updatedownload), c);
348 g_signal_connect(c->download, "notify::status", G_CALLBACK(updatedownload), c);
349 webkit_download_start(c->download);
351 c->title = copystr(&c->title, filename);
358 itemclick(GtkMenuItem *mi, Client *c) {
362 label = gtk_menu_item_get_label(mi);
363 for(i = 0; i < LENGTH(items); i++)
364 if(!strcmp(items[i].label, label))
365 items[i].func(c, &(items[i].arg));
369 keypress(GtkWidget* w, GdkEventKey *ev, Client *c) {
371 gboolean processed = FALSE;
374 for(i = 0; i < LENGTH(keys); i++) {
375 if(gdk_keyval_to_lower(ev->keyval) == keys[i].keyval
376 && CLEANMASK(ev->state) == keys[i].mod
378 keys[i].func(c, &(keys[i].arg));
386 linkhover(WebKitWebView *v, const char* t, const char* l, Client *c) {
388 c->linkhover = copystr(&c->linkhover, l);
389 else if(c->linkhover) {
397 loadstatuschange(WebKitWebView *view, GParamSpec *pspec, Client *c) {
398 switch(webkit_web_view_get_load_status (c->view)) {
399 case WEBKIT_LOAD_COMMITTED:
400 setatom(c, uriprop, geturi(c));
402 case WEBKIT_LOAD_FINISHED:
406 case WEBKIT_LOAD_PROVISIONAL:
407 case WEBKIT_LOAD_FIRST_VISUALLY_NON_EMPTY_LAYOUT:
413 loaduri(Client *c, const Arg *arg) {
415 const char *uri = (char *)arg->v;
416 Arg a = { .b = FALSE };
418 if(strcmp(uri, "") == 0)
420 u = g_strrstr(uri, "://") ? g_strdup(uri)
421 : g_strdup_printf("http://%s", uri);
422 /* prevents endless loop */
423 if(c->uri && strcmp(u, c->uri) == 0) {
427 webkit_web_view_load_uri(c->view, u);
429 c->title = copystr(&c->title, u);
436 navigate(Client *c, const Arg *arg) {
437 int steps = *(int *)arg;
438 webkit_web_view_go_back_or_forward(c->view, steps);
445 WebKitWebSettings *settings;
446 GdkGeometry hints = { 1, 1 };
449 if(!(c = calloc(1, sizeof(Client))))
450 die("Cannot malloc!\n");
453 c->win = gtk_plug_new(embed);
456 c->win = gtk_window_new(GTK_WINDOW_TOPLEVEL);
457 /* TA: 20091214: Despite what the GNOME docs say, the ICCCM
458 * is always correct, so we should still call this function.
459 * But when doing so, we *must* differentiate between a
460 * WM_CLASS and a resource on the window. By convention, the
461 * window class (WM_CLASS) is capped, while the resource is in
462 * lowercase. Both these values come as a pair.
464 gtk_window_set_wmclass(GTK_WINDOW(c->win), "surf", "surf");
466 /* TA: 20091214: And set the role here as well -- so that
467 * sessions can pick this up.
469 gtk_window_set_role(GTK_WINDOW(c->win), "Surf");
471 gtk_window_set_default_size(GTK_WINDOW(c->win), 800, 600);
472 g_signal_connect(G_OBJECT(c->win), "destroy", G_CALLBACK(destroywin), c);
473 g_signal_connect(G_OBJECT(c->win), "key-press-event", G_CALLBACK(keypress), c);
474 g_signal_connect(G_OBJECT(c->win), "size-allocate", G_CALLBACK(resize), c);
476 if(!(c->items = calloc(1, sizeof(GtkWidget *) * LENGTH(items))))
477 die("Cannot malloc!\n");
480 for(i = 0; i < LENGTH(items); i++) {
481 c->items[i] = gtk_menu_item_new_with_label(items[i].label);
482 g_signal_connect(G_OBJECT(c->items[i]), "activate",
483 G_CALLBACK(itemclick), c);
487 c->vbox = gtk_vbox_new(FALSE, 0);
489 /* Scrolled Window */
490 c->scroll = gtk_scrolled_window_new(NULL, NULL);
491 gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(c->scroll),
492 GTK_POLICY_NEVER, GTK_POLICY_NEVER);
495 c->view = WEBKIT_WEB_VIEW(webkit_web_view_new());
496 g_signal_connect(G_OBJECT(c->view), "title-changed", G_CALLBACK(titlechange), c);
497 g_signal_connect(G_OBJECT(c->view), "hovering-over-link", G_CALLBACK(linkhover), c);
498 g_signal_connect(G_OBJECT(c->view), "create-web-view", G_CALLBACK(createwindow), c);
499 g_signal_connect(G_OBJECT(c->view), "new-window-policy-decision-requested", G_CALLBACK(decidewindow), c);
500 g_signal_connect(G_OBJECT(c->view), "mime-type-policy-decision-requested", G_CALLBACK(decidedownload), c);
501 g_signal_connect(G_OBJECT(c->view), "download-requested", G_CALLBACK(initdownload), c);
502 g_signal_connect(G_OBJECT(c->view), "window-object-cleared", G_CALLBACK(windowobjectcleared), c);
503 g_signal_connect(G_OBJECT(c->view), "populate-popup", G_CALLBACK(context), c);
504 g_signal_connect(G_OBJECT(c->view), "notify::load-status", G_CALLBACK(loadstatuschange), c);
505 g_signal_connect(G_OBJECT(c->view), "notify::progress", G_CALLBACK(progresschange), c);
506 g_signal_connect(G_OBJECT(c->view), "resource-request-starting", G_CALLBACK(newrequest), c);
509 c->indicator = gtk_drawing_area_new();
510 gtk_widget_set_size_request(c->indicator, 0, 2);
511 g_signal_connect (G_OBJECT (c->indicator), "expose_event",
512 G_CALLBACK (exposeindicator), c);
515 gtk_container_add(GTK_CONTAINER(c->scroll), GTK_WIDGET(c->view));
516 gtk_container_add(GTK_CONTAINER(c->win), c->vbox);
517 gtk_container_add(GTK_CONTAINER(c->vbox), c->scroll);
518 gtk_container_add(GTK_CONTAINER(c->vbox), c->indicator);
521 gtk_box_set_child_packing(GTK_BOX(c->vbox), c->indicator, FALSE, FALSE, 0, GTK_PACK_START);
522 gtk_box_set_child_packing(GTK_BOX(c->vbox), c->scroll, TRUE, TRUE, 0, GTK_PACK_START);
523 gtk_widget_grab_focus(GTK_WIDGET(c->view));
524 gtk_widget_show(c->vbox);
525 gtk_widget_show(c->indicator);
526 gtk_widget_show(c->scroll);
527 gtk_widget_show(GTK_WIDGET(c->view));
528 gtk_widget_show(c->win);
529 gtk_window_set_geometry_hints(GTK_WINDOW(c->win), NULL, &hints, GDK_HINT_MIN_SIZE);
530 gdk_window_set_events(GTK_WIDGET(c->win)->window, GDK_ALL_EVENTS_MASK);
531 gdk_window_add_filter(GTK_WIDGET(c->win)->window, processx, c);
532 webkit_web_view_set_full_content_zoom(c->view, TRUE);
533 settings = webkit_web_view_get_settings(c->view);
534 if(!(ua = getenv("SURF_USERAGENT")))
536 g_object_set(G_OBJECT(settings), "user-agent", ua, NULL);
537 uri = g_strconcat("file://", stylefile, NULL);
538 g_object_set(G_OBJECT(settings), "user-stylesheet-uri", uri, NULL);
540 setatom(c, findprop, "");
541 setatom(c, uriprop, "");
548 gdk_display_sync(gtk_widget_get_display(c->win));
549 printf("%u\n", (guint)GDK_WINDOW_XID(GTK_WIDGET(c->win)->window));
555 void func(const char *name, const char *value, void *dummy) {
556 printf("%s = %s\n", name, value);
560 static void newrequest(WebKitWebView *v, WebKitWebFrame *f, WebKitWebResource *r, WebKitNetworkRequest *req, WebKitNetworkResponse *res, Client *c) {
561 SoupMessage *msg = webkit_network_request_get_message(req);
562 SoupMessageHeaders *h;
565 h = msg->request_headers;
566 soup_message_headers_foreach(h, func, NULL);
570 newwindow(Client *c, const Arg *arg) {
572 const char *cmd[7], *uri;
573 const Arg a = { .v = (void *)cmd };
579 snprintf(tmp, LENGTH(tmp), "%u\n", (int)embed);
586 uri = arg->v ? (char *)arg->v : c->linkhover;
594 pasteuri(GtkClipboard *clipboard, const char *text, gpointer d) {
595 Arg arg = {.v = text };
597 loaduri((Client *) d, &arg);
601 print(Client *c, const Arg *arg) {
602 webkit_web_frame_print(webkit_web_view_get_main_frame(c->view));
606 processx(GdkXEvent *e, GdkEvent *event, gpointer d) {
607 Client *c = (Client *)d;
611 if(((XEvent *)e)->type == PropertyNotify) {
612 ev = &((XEvent *)e)->xproperty;
615 else if(ev->state == PropertyNewValue) {
616 if(ev->atom == uriprop) {
617 arg.v = getatom(c, uriprop);
620 else if(ev->atom == findprop) {
624 return GDK_FILTER_REMOVE;
627 return GDK_FILTER_CONTINUE;
631 progresschange(WebKitWebView *view, GParamSpec *pspec, Client *c) {
632 c->progress = webkit_web_view_get_progress(c->view) * 100;
637 reload(Client *c, const Arg *arg) {
638 gboolean nocache = *(gboolean *)arg;
640 webkit_web_view_reload_bypass_cache(c->view);
642 webkit_web_view_reload(c->view);
646 resize(GtkWidget *w, GtkAllocation *a, Client *c) {
651 zoom = webkit_web_view_get_zoom_level(c->view);
652 if(a->width * a->height < 300 * 400 && zoom != 0.2)
653 webkit_web_view_set_zoom_level(c->view, 0.2);
655 webkit_web_view_set_zoom_level(c->view, 1.0);
659 scroll(Client *c, const Arg *arg) {
663 a = gtk_scrolled_window_get_vadjustment(GTK_SCROLLED_WINDOW(c->scroll));
664 v = gtk_adjustment_get_value(a);
665 v += gtk_adjustment_get_step_increment(a) * arg->i;
667 v = MIN(v, gtk_adjustment_get_upper(a) - gtk_adjustment_get_page_size(a));
668 gtk_adjustment_set_value(a, v);
672 setatom(Client *c, Atom a, const char *v) {
675 XChangeProperty(dpy, GDK_WINDOW_XID(GTK_WIDGET(c->win)->window), a,
676 XA_STRING, 8, PropModeReplace, (unsigned char *)v,
687 /* clean up any zombies immediately */
689 gtk_init(NULL, NULL);
690 if (!g_thread_supported())
694 s = webkit_get_default_session();
695 uriprop = XInternAtom(dpy, "_SURF_URI", False);
696 findprop = XInternAtom(dpy, "_SURF_FIND", False);
698 /* create dirs and files */
699 cookiefile = buildpath(cookiefile);
700 dldir = buildpath(dldir);
701 scriptfile = buildpath(scriptfile);
702 stylefile = buildpath(stylefile);
704 s = webkit_get_default_session();
706 soup_session_remove_feature_by_type(s, soup_cookie_get_type());
709 if((proxy = getenv("http_proxy")) && strcmp(proxy, "")) {
710 new_proxy = g_strrstr(proxy, "http://") ? g_strdup(proxy) :
711 g_strdup_printf("http://%s", proxy);
713 puri = soup_uri_new(new_proxy);
714 g_object_set(G_OBJECT(s), "proxy-uri", puri, NULL);
721 sigchld(int unused) {
722 if(signal(SIGCHLD, sigchld) == SIG_ERR)
723 die("Can't install SIGCHLD handler");
724 while(0 < waitpid(-1, NULL, WNOHANG));
728 source(Client *c, const Arg *arg) {
729 Arg a = { .b = FALSE };
732 s = webkit_web_view_get_view_source_mode(c->view);
733 webkit_web_view_set_view_source_mode(c->view, !s);
738 spawn(Client *c, const Arg *arg) {
741 close(ConnectionNumber(dpy));
743 execvp(((char **)arg->v)[0], (char **)arg->v);
744 fprintf(stderr, "surf: execvp %s", ((char **)arg->v)[0]);
751 stop(Client *c, const Arg *arg) {
753 webkit_download_cancel(c->download);
755 webkit_web_view_stop_loading(c->view);
760 titlechange(WebKitWebView *v, WebKitWebFrame *f, const char *t, Client *c) {
761 c->title = copystr(&c->title, t);
769 if(c->progress != 100)
770 t = g_strdup_printf("[%i%%] %s", c->progress, c->title);
771 else if(c->linkhover)
772 t = g_strdup(c->linkhover);
774 t = g_strdup(c->title);
776 gtk_window_set_title(GTK_WINDOW(c->win), t);
781 updatedownload(WebKitDownload *o, GParamSpec *pspec, Client *c) {
782 WebKitDownloadStatus status;
784 status = webkit_download_get_status(c->download);
785 if(status == WEBKIT_DOWNLOAD_STATUS_STARTED || status == WEBKIT_DOWNLOAD_STATUS_CREATED) {
786 c->progress = (gint)(webkit_download_get_progress(c->download)*100);
792 updatewinid(Client *c) {
793 snprintf(winid, LENGTH(winid), "%u",
794 (int)GDK_WINDOW_XID(GTK_WIDGET(c->win)->window));
799 fputs("surf - simple browser\n", stderr);
800 die("usage: surf [-e Window] [-x] [uri]\n");
804 windowobjectcleared(GtkWidget *w, WebKitWebFrame *frame, JSContextRef js, JSObjectRef win, Client *c) {
805 JSStringRef jsscript;
807 JSValueRef exception = NULL;
810 if(g_file_get_contents(scriptfile, &script, NULL, &error)) {
811 jsscript = JSStringCreateWithUTF8CString(script);
812 JSEvaluateScript(js, jsscript, JSContextGetGlobalObject(js), NULL, 0, &exception);
817 zoom(Client *c, const Arg *arg) {
819 if(arg->i < 0) /* zoom out */
820 webkit_web_view_zoom_out(c->view);
821 else if(arg->i > 0) /* zoom in */
822 webkit_web_view_zoom_in(c->view);
825 webkit_web_view_set_zoom_level(c->view, 1.0);
829 int main(int argc, char *argv[]) {
834 /* command line args */
835 for(i = 1, arg.v = NULL; i < argc && argv[i][0] == '-'; i++) {
836 if(!strcmp(argv[i], "-x"))
838 else if(!strcmp(argv[i], "-e")) {
840 embed = atoi(argv[i]);
844 else if(!strcmp(argv[i], "--")) {
848 else if(!strcmp(argv[i], "-v"))
849 die("surf-"VERSION", © 2009 surf engineers, see LICENSE for details\n");
858 loaduri(clients, &arg);