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;
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 initdownload(WebKitWebView *v, WebKitDownload *o, 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(SoupSession *s, SoupMessage *msg, gpointer v);
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 scroll_h(Client *c, const Arg *arg);
99 static void scroll_v(Client *c, const Arg *arg);
100 static void scroll(GtkAdjustment *a, const Arg *arg);
101 static void setatom(Client *c, int a, const char *v);
102 static void setcookie(SoupCookie *c);
103 static void setup(void);
104 static void sigchld(int unused);
105 static void source(Client *c, const Arg *arg);
106 static void spawn(Client *c, const Arg *arg);
107 static void eval(Client *c, const Arg *arg);
108 static void stop(Client *c, const Arg *arg);
109 static void titlechange(WebKitWebView *v, WebKitWebFrame* frame, const char* title, Client *c);
110 static void update(Client *c);
111 static void updatewinid(Client *c);
112 static void usage(void);
113 static void windowobjectcleared(GtkWidget *w, WebKitWebFrame *frame, JSContextRef js, JSObjectRef win, Client *c);
114 static void zoom(Client *c, const Arg *arg);
116 /* configuration, allows nested code to access above variables */
120 buildpath(const char *path) {
124 /* creating directory */
126 apath = g_strdup(path);
128 apath = g_strconcat(g_get_home_dir(), "/", path, NULL);
129 if((p = strrchr(apath, '/'))) {
131 g_mkdir_with_parents(apath, 0700);
132 g_chmod(apath, 0700); /* in case it existed */
135 /* creating file (gives error when apath ends with "/") */
136 if((f = fopen(apath, "a"))) {
137 g_chmod(apath, 0600); /* always */
146 destroyclient(clients);
153 evalscript(WebKitWebFrame *frame, JSContextRef js, char *script, char* scriptname) {
154 JSStringRef jsscript, jsscriptname;
155 JSValueRef exception = NULL;
157 jsscript = JSStringCreateWithUTF8CString(script);
158 jsscriptname = JSStringCreateWithUTF8CString(scriptname);
159 JSEvaluateScript(js, jsscript, JSContextGetGlobalObject(js), jsscriptname, 0, &exception);
160 JSStringRelease(jsscript);
161 JSStringRelease(jsscriptname);
165 runscript(WebKitWebFrame *frame, JSContextRef js) {
169 if(g_file_get_contents(scriptfile, &script, NULL, &error)) {
170 evalscript(frame, webkit_web_frame_get_global_context(frame), script, scriptfile);
175 clipboard(Client *c, const Arg *arg) {
176 gboolean paste = *(gboolean *)arg;
179 gtk_clipboard_request_text(gtk_clipboard_get(GDK_SELECTION_PRIMARY), pasteuri, c);
181 gtk_clipboard_set_text(gtk_clipboard_get(GDK_SELECTION_PRIMARY), c->linkhover ? c->linkhover : geturi(c), -1);
185 copystr(char **str, const char *src) {
197 createwindow(WebKitWebView *v, WebKitWebFrame *f, Client *c) {
198 Client *n = newclient();
203 decidedownload(WebKitWebView *v, WebKitWebFrame *f, WebKitNetworkRequest *r, gchar *m, WebKitWebPolicyDecision *p, Client *c) {
204 if(!webkit_web_view_can_show_mime_type(v, m)) {
205 webkit_web_policy_decision_download(p);
212 decidewindow(WebKitWebView *view, WebKitWebFrame *f, WebKitNetworkRequest *r, WebKitWebNavigationAction *n, WebKitWebPolicyDecision *p, Client *c) {
215 if(webkit_web_navigation_action_get_reason(n) == WEBKIT_WEB_NAVIGATION_REASON_LINK_CLICKED) {
216 webkit_web_policy_decision_ignore(p);
217 arg.v = (void *)webkit_network_request_get_uri(r);
218 newwindow(NULL, &arg);
225 destroyclient(Client *c) {
228 webkit_web_view_stop_loading(c->view);
229 gtk_widget_destroy(c->indicator);
230 gtk_widget_destroy(GTK_WIDGET(c->view));
231 gtk_widget_destroy(c->scroll);
232 gtk_widget_destroy(c->vbox);
233 gtk_widget_destroy(c->win);
235 for(p = clients; p && p->next != c; p = p->next);
246 destroywin(GtkWidget* w, Client *c) {
257 drawindicator(Client *c) {
266 width = c->progress * w->allocation.width / 100;
267 gc = gdk_gc_new(w->window);
268 if(strstr(uri, "https://") == uri)
269 gdk_color_parse(c->sslfailed ?
270 progress_untrust : progress_trust, &fg);
272 gdk_color_parse(progress, &fg);
273 gdk_gc_set_rgb_fg_color(gc, &fg);
274 gdk_draw_rectangle(w->window,
275 w->style->bg_gc[GTK_WIDGET_STATE(w)],
276 TRUE, 0, 0, w->allocation.width, w->allocation.height);
277 gdk_draw_rectangle(w->window, gc, TRUE, 0, 0, width,
278 w->allocation.height);
283 exposeindicator(GtkWidget *w, GdkEventExpose *e, Client *c) {
289 find(Client *c, const Arg *arg) {
292 s = getatom(c, AtomFind);
293 gboolean forward = *(gboolean *)arg;
294 webkit_web_view_search_text(c->view, s, FALSE, forward, TRUE);
298 getcookies(SoupURI *uri) {
300 SoupCookieJar *j = soup_cookie_jar_text_new(cookiefile, TRUE);
301 c = soup_cookie_jar_get_cookies(j, uri, TRUE);
307 getatom(Client *c, int a) {
308 static char buf[BUFSIZ];
311 unsigned long ldummy;
312 unsigned char *p = NULL;
314 XGetWindowProperty(dpy, GDK_WINDOW_XID(GTK_WIDGET(c->win)->window),
315 atoms[a], 0L, BUFSIZ, False, XA_STRING,
316 &adummy, &idummy, &ldummy, &ldummy, &p);
318 strncpy(buf, (char *)p, LENGTH(buf)-1);
329 if(!(uri = (char *)webkit_web_view_get_uri(c->view)))
335 gotheaders(SoupMessage *msg, gpointer v) {
339 uri = soup_message_get_uri(msg);
340 for(p = l = soup_cookies_from_response(msg); p;
341 p = g_slist_next(p)) {
342 setcookie((SoupCookie *)p->data);
344 soup_cookies_free(l);
348 initdownload(WebKitWebView *view, WebKitDownload *o, Client *c) {
352 arg = (Arg)DOWNLOAD((char *)webkit_download_get_uri(o));
358 keypress(GtkWidget* w, GdkEventKey *ev, Client *c) {
360 gboolean processed = FALSE;
363 for(i = 0; i < LENGTH(keys); i++) {
364 if(gdk_keyval_to_lower(ev->keyval) == keys[i].keyval
365 && (ev->state & keys[i].mod) == keys[i].mod
367 keys[i].func(c, &(keys[i].arg));
375 linkhover(WebKitWebView *v, const char* t, const char* l, Client *c) {
377 c->linkhover = copystr(&c->linkhover, l);
379 else if(c->linkhover) {
387 loadstatuschange(WebKitWebView *view, GParamSpec *pspec, Client *c) {
388 WebKitWebFrame *frame;
389 WebKitWebDataSource *src;
390 WebKitNetworkRequest *request;
394 switch(webkit_web_view_get_load_status (c->view)) {
395 case WEBKIT_LOAD_COMMITTED:
397 if(strstr(uri, "https://") == uri) {
398 frame = webkit_web_view_get_main_frame(c->view);
399 src = webkit_web_frame_get_data_source(frame);
400 request = webkit_web_data_source_get_request(src);
401 msg = webkit_network_request_get_message(request);
402 c->sslfailed = soup_message_get_flags(msg)
403 ^ SOUP_MESSAGE_CERTIFICATE_TRUSTED;
405 setatom(c, AtomUri, uri);
407 case WEBKIT_LOAD_FINISHED:
417 loaduri(Client *c, const Arg *arg) {
419 const char *uri = (char *)arg->v;
420 Arg a = { .b = FALSE };
422 if(strcmp(uri, "") == 0)
424 u = g_strrstr(uri, "://") ? g_strdup(uri)
425 : g_strdup_printf("http://%s", uri);
426 /* prevents endless loop */
427 if(c->uri && strcmp(u, c->uri) == 0) {
431 webkit_web_view_load_uri(c->view, u);
433 c->title = copystr(&c->title, u);
440 navigate(Client *c, const Arg *arg) {
441 int steps = *(int *)arg;
442 webkit_web_view_go_back_or_forward(c->view, steps);
448 WebKitWebSettings *settings;
449 WebKitWebFrame *frame;
450 GdkGeometry hints = { 1, 1 };
453 if(!(c = calloc(1, sizeof(Client))))
454 die("Cannot malloc!\n");
457 c->win = gtk_plug_new(embed);
460 c->win = gtk_window_new(GTK_WINDOW_TOPLEVEL);
461 /* TA: 20091214: Despite what the GNOME docs say, the ICCCM
462 * is always correct, so we should still call this function.
463 * But when doing so, we *must* differentiate between a
464 * WM_CLASS and a resource on the window. By convention, the
465 * window class (WM_CLASS) is capped, while the resource is in
466 * lowercase. Both these values come as a pair.
468 gtk_window_set_wmclass(GTK_WINDOW(c->win), "surf", "Surf");
470 /* TA: 20091214: And set the role here as well -- so that
471 * sessions can pick this up.
473 gtk_window_set_role(GTK_WINDOW(c->win), "Surf");
475 gtk_window_set_default_size(GTK_WINDOW(c->win), 800, 600);
476 g_signal_connect(G_OBJECT(c->win), "destroy", G_CALLBACK(destroywin), c);
477 g_signal_connect(G_OBJECT(c->win), "key-press-event", G_CALLBACK(keypress), c);
480 c->vbox = gtk_vbox_new(FALSE, 0);
482 /* Scrolled Window */
483 c->scroll = gtk_scrolled_window_new(NULL, NULL);
484 gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(c->scroll),
485 GTK_POLICY_NEVER, GTK_POLICY_NEVER);
488 c->view = WEBKIT_WEB_VIEW(webkit_web_view_new());
489 g_signal_connect(G_OBJECT(c->view), "title-changed", G_CALLBACK(titlechange), c);
490 g_signal_connect(G_OBJECT(c->view), "hovering-over-link", G_CALLBACK(linkhover), c);
491 g_signal_connect(G_OBJECT(c->view), "create-web-view", G_CALLBACK(createwindow), c);
492 g_signal_connect(G_OBJECT(c->view), "new-window-policy-decision-requested", G_CALLBACK(decidewindow), c);
493 g_signal_connect(G_OBJECT(c->view), "mime-type-policy-decision-requested", G_CALLBACK(decidedownload), c);
494 g_signal_connect(G_OBJECT(c->view), "window-object-cleared", G_CALLBACK(windowobjectcleared), c);
495 g_signal_connect(G_OBJECT(c->view), "notify::load-status", G_CALLBACK(loadstatuschange), c);
496 g_signal_connect(G_OBJECT(c->view), "notify::progress", G_CALLBACK(progresschange), c);
497 g_signal_connect(G_OBJECT(c->view), "download-requested", G_CALLBACK(initdownload), c);
500 c->indicator = gtk_drawing_area_new();
501 gtk_widget_set_size_request(c->indicator, 0, 2);
502 g_signal_connect (G_OBJECT (c->indicator), "expose_event",
503 G_CALLBACK (exposeindicator), c);
506 gtk_container_add(GTK_CONTAINER(c->scroll), GTK_WIDGET(c->view));
507 gtk_container_add(GTK_CONTAINER(c->win), c->vbox);
508 gtk_container_add(GTK_CONTAINER(c->vbox), c->scroll);
509 gtk_container_add(GTK_CONTAINER(c->vbox), c->indicator);
512 gtk_box_set_child_packing(GTK_BOX(c->vbox), c->indicator, FALSE, FALSE, 0, GTK_PACK_START);
513 gtk_box_set_child_packing(GTK_BOX(c->vbox), c->scroll, TRUE, TRUE, 0, GTK_PACK_START);
514 gtk_widget_grab_focus(GTK_WIDGET(c->view));
515 gtk_widget_show(c->vbox);
516 gtk_widget_show(c->indicator);
517 gtk_widget_show(c->scroll);
518 gtk_widget_show(GTK_WIDGET(c->view));
519 gtk_widget_show(c->win);
520 gtk_window_set_geometry_hints(GTK_WINDOW(c->win), NULL, &hints, GDK_HINT_MIN_SIZE);
521 gdk_window_set_events(GTK_WIDGET(c->win)->window, GDK_ALL_EVENTS_MASK);
522 gdk_window_add_filter(GTK_WIDGET(c->win)->window, processx, c);
523 webkit_web_view_set_full_content_zoom(c->view, TRUE);
524 frame = webkit_web_view_get_main_frame(c->view);
525 runscript(frame, webkit_web_frame_get_global_context(frame));
526 settings = webkit_web_view_get_settings(c->view);
527 if(!(ua = getenv("SURF_USERAGENT")))
529 g_object_set(G_OBJECT(settings), "user-agent", ua, NULL);
530 uri = g_strconcat("file://", stylefile, NULL);
531 g_object_set(G_OBJECT(settings), "user-stylesheet-uri", uri, NULL);
532 g_object_set(G_OBJECT(settings), "auto-load-images", loadimage, NULL);
533 g_object_set(G_OBJECT(settings), "enable-plugins", plugin, NULL);
534 g_object_set(G_OBJECT(settings), "enable-scripts", script, NULL);
535 g_object_set(G_OBJECT(settings), "enable-spatial-navigation", SPATIAL_BROWSING, NULL);
539 setatom(c, AtomFind, "");
540 setatom(c, AtomUri, "about:blank");
542 webkit_web_view_set_transparent(c->view, TRUE);
548 gdk_display_sync(gtk_widget_get_display(c->win));
549 printf("%u\n", (guint)GDK_WINDOW_XID(GTK_WIDGET(c->win)->window));
551 if (fclose(stdout) != 0) {
552 die("Error closing stdout");
559 newrequest(SoupSession *s, SoupMessage *msg, gpointer v) {
560 SoupMessageHeaders *h = msg->request_headers;
564 soup_message_headers_remove(h, "Cookie");
565 uri = soup_message_get_uri(msg);
566 if((c = getcookies(uri)))
567 soup_message_headers_append(h, "Cookie", c);
568 g_signal_connect_after(G_OBJECT(msg), "got-headers", G_CALLBACK(gotheaders), NULL);
572 newwindow(Client *c, const Arg *arg) {
574 const char *cmd[10], *uri;
575 const Arg a = { .v = (void *)cmd };
581 snprintf(tmp, LENGTH(tmp), "%u\n", (int)embed);
593 uri = arg->v ? (char *)arg->v : c->linkhover;
601 pasteuri(GtkClipboard *clipboard, const char *text, gpointer d) {
602 Arg arg = {.v = text };
604 loaduri((Client *) d, &arg);
608 print(Client *c, const Arg *arg) {
609 webkit_web_frame_print(webkit_web_view_get_main_frame(c->view));
613 processx(GdkXEvent *e, GdkEvent *event, gpointer d) {
614 Client *c = (Client *)d;
618 if(((XEvent *)e)->type == PropertyNotify) {
619 ev = &((XEvent *)e)->xproperty;
620 if(ev->state == PropertyNewValue) {
621 if(ev->atom == atoms[AtomFind]) {
624 return GDK_FILTER_REMOVE;
626 else if(ev->atom == atoms[AtomGo]) {
627 arg.v = getatom(c, AtomGo);
629 return GDK_FILTER_REMOVE;
633 return GDK_FILTER_CONTINUE;
637 progresschange(WebKitWebView *view, GParamSpec *pspec, Client *c) {
638 c->progress = webkit_web_view_get_progress(c->view) * 100;
643 reload(Client *c, const Arg *arg) {
644 gboolean nocache = *(gboolean *)arg;
646 webkit_web_view_reload_bypass_cache(c->view);
648 webkit_web_view_reload(c->view);
652 scroll_h(Client *c, const Arg *arg) {
653 scroll(gtk_scrolled_window_get_hadjustment(GTK_SCROLLED_WINDOW(c->scroll)), arg);
657 scroll_v(Client *c, const Arg *arg) {
658 scroll(gtk_scrolled_window_get_vadjustment(GTK_SCROLLED_WINDOW(c->scroll)), arg);
662 scroll(GtkAdjustment *a, const Arg *arg) {
665 v = gtk_adjustment_get_value(a);
669 v += gtk_adjustment_get_page_increment(a) * (arg->i / 10000); break;
673 v += gtk_adjustment_get_step_increment(a) * arg->i;
676 v = MIN(v, gtk_adjustment_get_upper(a) - gtk_adjustment_get_page_size(a));
677 gtk_adjustment_set_value(a, v);
681 setcookie(SoupCookie *c) {
684 lock = open(cookiefile, 0);
685 flock(lock, LOCK_EX);
687 SoupCookieJar *j = soup_cookie_jar_text_new(cookiefile, FALSE);
688 c = soup_cookie_copy(c);
689 if(c->expires == NULL && sessiontime) {
690 e = soup_date_new_from_time_t(time(NULL) + sessiontime);
691 soup_cookie_set_expires(c, e);
693 soup_cookie_jar_add_cookie(j, c);
695 flock(lock, LOCK_UN);
700 setatom(Client *c, int a, const char *v) {
702 XChangeProperty(dpy, GDK_WINDOW_XID(GTK_WIDGET(c->win)->window), atoms[a],
703 XA_STRING, 8, PropModeReplace, (unsigned char *)v,
714 /* clean up any zombies immediately */
716 gtk_init(NULL, NULL);
717 if (!g_thread_supported())
721 s = webkit_get_default_session();
724 atoms[AtomFind] = XInternAtom(dpy, "_SURF_FIND", False);
725 atoms[AtomGo] = XInternAtom(dpy, "_SURF_GO", False);
726 atoms[AtomUri] = XInternAtom(dpy, "_SURF_URI", False);
729 cookiefile = buildpath(cookiefile);
730 scriptfile = buildpath(scriptfile);
731 stylefile = buildpath(stylefile);
733 /* request handler */
734 s = webkit_get_default_session();
735 soup_session_remove_feature_by_type(s, soup_cookie_get_type());
736 soup_session_remove_feature_by_type(s, soup_cookie_jar_get_type());
737 g_signal_connect_after(G_OBJECT(s), "request-started", G_CALLBACK(newrequest), NULL);
740 g_object_set(G_OBJECT(s), "ssl-ca-file", cafile, NULL);
741 g_object_set(G_OBJECT(s), "ssl-strict", strictssl, NULL);
744 if((proxy = getenv("http_proxy")) && strcmp(proxy, "")) {
745 new_proxy = g_strrstr(proxy, "http://") ? g_strdup(proxy) :
746 g_strdup_printf("http://%s", proxy);
747 puri = soup_uri_new(new_proxy);
748 g_object_set(G_OBJECT(s), "proxy-uri", puri, NULL);
755 sigchld(int unused) {
756 if(signal(SIGCHLD, sigchld) == SIG_ERR)
757 die("Can't install SIGCHLD handler");
758 while(0 < waitpid(-1, NULL, WNOHANG));
762 source(Client *c, const Arg *arg) {
763 Arg a = { .b = FALSE };
766 s = webkit_web_view_get_view_source_mode(c->view);
767 webkit_web_view_set_view_source_mode(c->view, !s);
772 spawn(Client *c, const Arg *arg) {
775 close(ConnectionNumber(dpy));
777 execvp(((char **)arg->v)[0], (char **)arg->v);
778 fprintf(stderr, "surf: execvp %s", ((char **)arg->v)[0]);
785 eval(Client *c, const Arg *arg) {
786 WebKitWebFrame *frame = webkit_web_view_get_main_frame(c->view);
787 evalscript(frame, webkit_web_frame_get_global_context(frame), ((char **)arg->v)[0], "");
791 stop(Client *c, const Arg *arg) {
792 webkit_web_view_stop_loading(c->view);
796 titlechange(WebKitWebView *v, WebKitWebFrame *f, const char *t, Client *c) {
797 c->title = copystr(&c->title, t);
806 t = g_strdup(c->linkhover);
807 else if(c->progress != 100)
808 t = g_strdup_printf("[%i%%] %s", c->progress, c->title);
810 t = g_strdup(c->title);
812 gtk_window_set_title(GTK_WINDOW(c->win), t);
817 updatewinid(Client *c) {
818 snprintf(winid, LENGTH(winid), "%u",
819 (int)GDK_WINDOW_XID(GTK_WIDGET(c->win)->window));
824 fputs("surf - simple browser\n", stderr);
825 die("usage: surf [-e xid] [-i] [-p] [-s] [-v] [-x] [uri]\n");
829 windowobjectcleared(GtkWidget *w, WebKitWebFrame *frame, JSContextRef js, JSObjectRef win, Client *c) {
830 runscript(frame, js);
834 zoom(Client *c, const Arg *arg) {
836 if(arg->i < 0) /* zoom out */
837 webkit_web_view_zoom_out(c->view);
838 else if(arg->i > 0) /* zoom in */
839 webkit_web_view_zoom_in(c->view);
842 webkit_web_view_set_zoom_level(c->view, 1.0);
847 main(int argc, char *argv[]) {
852 /* command line args */
853 for(i = 1, arg.v = NULL; i < argc && argv[i][0] == '-' &&
854 argv[i][1] != '\0' && argv[i][2] == '\0'; i++) {
855 if(!strcmp(argv[i], "--")) {
862 embed = atoi(argv[i]);
879 die("surf-"VERSION", ©2009-2012 surf engineers, see LICENSE for details\n");
889 loaduri(clients, &arg);