using gint instead of int (insane API, but ok.)
[surf.git] / surf.c
1 /* See LICENSE file for copyright and license details.
2  *
3  * To understand surf, start reading main().
4  */
5 #include <X11/X.h>
6 #include <X11/Xatom.h>
7 #include <gtk/gtk.h>
8 #include <gdk/gdkx.h>
9 #include <gdk/gdk.h>
10 #include <gdk/gdkkeysyms.h>
11 #include <string.h>
12 #include <unistd.h>
13 #include <getopt.h>
14 #include <stdlib.h>
15 #include <stdio.h>
16 #include <webkit/webkit.h>
17 #include <glib/gstdio.h>
18
19 #define LENGTH(x) (sizeof x / sizeof x[0])
20
21 Display *dpy;
22 Atom urlprop;
23 typedef union Arg Arg;
24 union Arg {
25         const gboolean b;
26         const gint i;
27         const void *v;
28 } ;
29
30 typedef struct Client {
31         GtkWidget *win, *scroll, *vbox, *urlbar, *searchbar, *indicator;
32         WebKitWebView *view;
33         WebKitDownload *download;
34         gchar *title;
35         gint progress;
36         struct Client *next;
37 } Client;
38
39 typedef struct Cookie {
40         char *name;
41         char *value;
42         char *domain;
43         char *path;
44         struct Cookie *next;
45 } Cookie;
46
47 typedef enum {
48     BROWSER = 0x0001,
49     SEARCHBAR = 0x0010,
50     URLBAR = 0x0100,
51     ALWAYS = ~0,
52 } KeyFocus;
53
54 typedef struct {
55         guint mod;
56         guint keyval;
57         void (*func)(Client *c, const Arg *arg);
58         const Arg arg;
59         KeyFocus focus;
60 } Key;
61
62 SoupCookieJar *cookiejar;
63 SoupSession *session;
64 Client *clients = NULL;
65 Cookie *cookies = NULL;
66 gboolean embed = FALSE;
67 gboolean showxid = FALSE;
68 gboolean ignore_once = FALSE;
69 extern char *optarg;
70 extern gint optind;
71
72 static void cleanup(void);
73 static void proccookies(SoupMessage *m, Client *c);
74 static void clipboard(Client *c, const Arg *arg);
75 static void destroyclient(Client *c);
76 static void destroywin(GtkWidget* w, Client *c);
77 static void die(char *str);
78 static void download(WebKitDownload *o, GParamSpec *pspec, Client *c);
79 static void drawindicator(Client *c);
80 static gboolean exposeindicator(GtkWidget *w, GdkEventExpose *e, Client *c);
81 static gboolean initdownload(WebKitWebView *view, WebKitDownload *o, Client *c);
82 static gchar *geturi(Client *c);
83 static void hidesearch(Client *c, const Arg *arg);
84 static void hideurl(Client *c, const Arg *arg);
85 static gboolean keypress(GtkWidget* w, GdkEventKey *ev, Client *c);
86 static void linkhover(WebKitWebView* page, const gchar* t, const gchar* l, Client *c);
87 static void loadcommit(WebKitWebView *view, WebKitWebFrame *f, Client *c);
88 static void loadstart(WebKitWebView *view, WebKitWebFrame *f, Client *c);
89 static void loadfile(Client *c, const gchar *f);
90 static void loaduri(Client *c, const Arg *arg);
91 static void navigate(Client *c, const Arg *arg);
92 static Client *newclient();
93 static WebKitWebView *newwindow(WebKitWebView  *v, WebKitWebFrame *f, Client *c);
94 static void pasteurl(GtkClipboard *clipboard, const gchar *text, gpointer d);
95 static GdkFilterReturn processx(GdkXEvent *xevent, GdkEvent *event, gpointer d);
96 static void print(Client *c, const Arg *arg);
97 static void progresschange(WebKitWebView *view, gint p, Client *c);
98 static void request(SoupSession *s, SoupMessage *m, Client *c);
99 static void reload(Client *c, const Arg *arg);
100 static void rereadcookies();
101 static void setcookie(char *name, char *val, char *dom, char *path, long exp);
102 static void setup();
103 static void titlechange(WebKitWebView* view, WebKitWebFrame* frame,
104                 const gchar* title, Client *c);
105 static void searchtext(Client *c, const Arg *arg);
106 static void showsearch(Client *c, const Arg *arg);
107 static void showurl(Client *c, const Arg *arg);
108 static void stop(Client *c, const Arg *arg);
109 static void titlechange(WebKitWebView* view, WebKitWebFrame* frame, const gchar* title, Client *c);
110 static void usage();
111 static void update(Client *c, const gchar *title);
112 static void zoom(Client *c, const Arg *arg);
113
114 #include "config.h"
115
116 void
117 cleanup(void) {
118         while(clients)
119                 destroyclient(clients);
120 }
121
122 void
123 proccookies(SoupMessage *m, Client *c) {
124         GSList *l;
125         SoupCookie *co;
126         long t;
127
128         rereadcookies();
129         for (l = soup_cookies_from_response(m); l; l = l->next){
130                 co = (SoupCookie *)l->data;
131                 t = co->expires ?  soup_date_to_time_t(co->expires) : 0;
132                 setcookie(co->name, co->value, co->domain, co->value, t);
133         }
134         g_slist_free(l);
135 }
136
137 void
138 clipboard(Client *c, const Arg *arg) {
139         gboolean paste = *(gboolean *)arg;
140         if(paste)
141                 gtk_clipboard_request_text(gtk_clipboard_get(GDK_SELECTION_PRIMARY), pasteurl, c);
142         else
143                 gtk_clipboard_set_text(gtk_clipboard_get(GDK_SELECTION_PRIMARY), webkit_web_view_get_uri(c->view), -1);
144 }
145
146 void
147 destroyclient(Client *c) {
148         Client *p;
149
150         gtk_widget_destroy(GTK_WIDGET(webkit_web_view_new()));
151         gtk_widget_destroy(c->scroll);
152         gtk_widget_destroy(c->urlbar);
153         gtk_widget_destroy(c->searchbar);
154         gtk_widget_destroy(c->vbox);
155         gtk_widget_destroy(c->win);
156         for(p = clients; p && p->next != c; p = p->next);
157         if(p)
158                 p->next = c->next;
159         else
160                 clients = c->next;
161         free(c);
162         if(clients == NULL)
163                 gtk_main_quit();
164 }
165
166 void
167 destroywin(GtkWidget* w, Client *c) {
168         destroyclient(c);
169 }
170
171 void
172 die(char *str) {
173         fputs(str, stderr);
174         exit(EXIT_FAILURE);
175 }
176
177 void
178 drawindicator(Client *c) {
179         gint width;
180         gchar *uri;
181         GtkWidget *w;
182         GdkGC *gc;
183         GdkColor fg;
184
185         uri = geturi(c);
186         w = c->indicator;
187         width = c->progress * w->allocation.width / 100;
188         gc = gdk_gc_new(w->window);
189         gdk_color_parse(strstr(uri, "https://") == uri ?
190                         progress_trust : progress, &fg);
191         gdk_gc_set_rgb_fg_color(gc, &fg);
192         gdk_draw_rectangle(w->window,
193                         w->style->bg_gc[GTK_WIDGET_STATE(w)],
194                         TRUE, 0, 0, w->allocation.width, w->allocation.height);
195         gdk_draw_rectangle(w->window, gc, TRUE, 0, 0, width,
196                         w->allocation.height);
197         g_object_unref(gc);/*g_free(gc);*/
198 }
199
200 gboolean
201 exposeindicator(GtkWidget *w, GdkEventExpose *e, Client *c) {
202         drawindicator(c);
203         return TRUE;
204 }
205
206 void
207 download(WebKitDownload *o, GParamSpec *pspec, Client *c) {
208         WebKitDownloadStatus status;
209
210         status = webkit_download_get_status(c->download);
211         if(status == WEBKIT_DOWNLOAD_STATUS_STARTED || status == WEBKIT_DOWNLOAD_STATUS_CREATED) {
212                 c->progress = (gint)(webkit_download_get_progress(c->download)*100);
213         }
214         update(c, NULL);
215 }
216
217 gboolean
218 initdownload(WebKitWebView *view, WebKitDownload *o, Client *c) {
219         const gchar *home, *filename;
220         gchar *uri, *path, *html;
221
222         stop(c, NULL);
223         c->download = o;
224         home = g_get_home_dir();
225         filename = webkit_download_get_suggested_filename(o);
226         path = g_build_filename(home, ".surf", "dl", 
227                         filename, NULL);
228         uri = g_strconcat("file://", path, NULL);
229         webkit_download_set_destination_uri(c->download, uri);
230         c->progress = 0;
231         g_free(uri);
232         html = g_strdup_printf("Download <b>%s</b>...", filename);
233         webkit_web_view_load_html_string(c->view, html,
234                         webkit_download_get_uri(c->download));
235         g_signal_connect(c->download, "notify::progress", G_CALLBACK(download), c);
236         g_signal_connect(c->download, "notify::status", G_CALLBACK(download), c);
237         webkit_download_start(c->download);
238         update(c, filename);
239         g_free(html);
240         return TRUE;
241 }
242
243 gchar *
244 geturi(Client *c) {
245         gchar *uri;
246
247         if(!(uri = (gchar *)webkit_web_view_get_uri(c->view)))
248                 uri = g_strdup("about:blank");
249         return uri;
250 }
251
252 void
253 hidesearch(Client *c, const Arg *arg) {
254         gtk_widget_hide(c->searchbar);
255         gtk_widget_grab_focus(GTK_WIDGET(c->view));
256 }
257
258 void
259 hideurl(Client *c, const Arg *arg) {
260         gtk_widget_hide(c->urlbar);
261         gtk_widget_grab_focus(GTK_WIDGET(c->view));
262 }
263
264 gboolean
265 keypress(GtkWidget* w, GdkEventKey *ev, Client *c) {
266         guint i, focus;
267         gboolean processed = FALSE;
268
269         if(ev->type != GDK_KEY_PRESS)
270                 return FALSE;
271         if(GTK_WIDGET_HAS_FOCUS(c->searchbar))
272                 focus = SEARCHBAR;
273         else if(GTK_WIDGET_HAS_FOCUS(c->urlbar))
274                 focus = URLBAR;
275         else
276                 focus = BROWSER;
277         for(i = 0; i < LENGTH(keys); i++) {
278                 if(focus & keys[i].focus && ev->keyval == keys[i].keyval &&
279                                 (ev->state == keys[i].mod || ev->state & keys[i].mod)
280                                 && keys[i].func) {
281                         keys[i].func(c, &(keys[i].arg));
282                         processed = TRUE;
283                 }
284         }
285         return processed;
286 }
287
288 void
289 linkhover(WebKitWebView* page, const gchar* t, const gchar* l, Client *c) {
290         if(l)
291                 gtk_window_set_title(GTK_WINDOW(c->win), l);
292         else
293                 update(c, NULL);
294 }
295
296 void
297 loadcommit(WebKitWebView *view, WebKitWebFrame *f, Client *c) {
298         gchar *uri;
299
300         ignore_once = TRUE;
301         uri = geturi(c);
302         XChangeProperty(dpy, GDK_WINDOW_XID(GTK_WIDGET(c->win)->window), urlprop,
303                         XA_STRING, 8, PropModeReplace, (unsigned char *)uri,
304                         strlen(uri) + 1);
305 }
306
307 void
308 loadstart(WebKitWebView *view, WebKitWebFrame *f, Client *c) {
309         c->progress = 0;
310         update(c, NULL);
311 }
312
313 void
314 loadfile(Client *c, const gchar *f) {
315         GIOChannel *chan = NULL;
316         GError *e = NULL;
317         GString *code;
318         gchar *line, *uri;
319         Arg arg;
320
321         if(strcmp(f, "-") == 0) {
322                 chan = g_io_channel_unix_new(STDIN_FILENO);
323                 if (chan) {
324                         code = g_string_new("");
325                         while(g_io_channel_read_line(chan, &line, NULL, NULL,
326                                                 &e) == G_IO_STATUS_NORMAL) {
327                                 g_string_append(code, line);
328                                 g_free(line);
329                         }
330                         webkit_web_view_load_html_string(c->view, code->str,
331                                         "file://.");
332                         g_io_channel_shutdown(chan, FALSE, NULL);
333                         g_string_free(code, TRUE);
334                 }
335                 arg.v = uri = g_strdup("stdin");
336         }
337         else {
338                 arg.v = uri = g_strdup_printf("file://%s", f);
339                 loaduri(c, &arg);
340         }
341         update(c, uri);
342         g_free(uri);
343 }
344
345 void
346 loaduri(Client *c, const Arg *arg) {
347         gchar *u;
348         const gchar *uri = (gchar *)arg->v;
349         if(!uri)
350                 uri = gtk_entry_get_text(GTK_ENTRY(c->urlbar));
351         u = g_strrstr(uri, "://") ? g_strdup(uri)
352                 : g_strdup_printf("http://%s", uri);
353         webkit_web_view_load_uri(c->view, u);
354         c->progress = 0;
355         update(c, u);
356         g_free(u);
357 }
358
359 void
360 navigate(Client *c, const Arg *arg) {
361         gint steps = *(gint *)arg;
362         webkit_web_view_go_back_or_forward(c->view, steps);
363 }
364
365 Client *
366 newclient(void) {
367         Client *c;
368         if(!(c = calloc(1, sizeof(Client))))
369                 die("Cannot malloc!\n");
370         /* Window */
371         if(embed) {
372                 c->win = gtk_plug_new(0);
373         }
374         else {
375                 c->win = gtk_window_new(GTK_WINDOW_TOPLEVEL);
376                 gtk_window_set_wmclass(GTK_WINDOW(c->win), "surf", "surf");
377         }
378         gtk_window_set_default_size(GTK_WINDOW(c->win), 800, 600);
379         g_signal_connect(G_OBJECT(c->win), "destroy", G_CALLBACK(destroywin), c);
380         g_signal_connect(G_OBJECT(c->win), "key-press-event", G_CALLBACK(keypress), c);
381
382         /* VBox */
383         c->vbox = gtk_vbox_new(FALSE, 0);
384
385         /* scrolled window */
386         c->scroll = gtk_scrolled_window_new(NULL, NULL);
387         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(c->scroll),
388                         GTK_POLICY_NEVER, GTK_POLICY_NEVER);
389
390         /* webview */
391         c->view = WEBKIT_WEB_VIEW(webkit_web_view_new());
392         g_signal_connect(G_OBJECT(c->view), "title-changed", G_CALLBACK(titlechange), c);
393         g_signal_connect(G_OBJECT(c->view), "load-progress-changed", G_CALLBACK(progresschange), c);
394         g_signal_connect(G_OBJECT(c->view), "load-committed", G_CALLBACK(loadcommit), c);
395         g_signal_connect(G_OBJECT(c->view), "load-started", G_CALLBACK(loadstart), c);
396         g_signal_connect(G_OBJECT(c->view), "hovering-over-link", G_CALLBACK(linkhover), c);
397         g_signal_connect(G_OBJECT(c->view), "create-web-view", G_CALLBACK(newwindow), c);
398         g_signal_connect(G_OBJECT(c->view), "download-requested", G_CALLBACK(initdownload), c);
399         g_signal_connect_after(session, "request-started", G_CALLBACK(request), c);
400
401         /* urlbar */
402         c->urlbar = gtk_entry_new();
403         gtk_entry_set_has_frame(GTK_ENTRY(c->urlbar), FALSE);
404
405         /* searchbar */
406         c->searchbar = gtk_entry_new();
407         gtk_entry_set_has_frame(GTK_ENTRY(c->searchbar), FALSE);
408
409         /* indicator */
410         c->indicator = gtk_drawing_area_new();
411         gtk_widget_set_size_request(c->indicator, 0, 2);
412         g_signal_connect (G_OBJECT (c->indicator), "expose_event",
413                         G_CALLBACK (exposeindicator), c);
414
415         /* downloadbar */
416
417         /* Arranging */
418         gtk_container_add(GTK_CONTAINER(c->scroll), GTK_WIDGET(c->view));
419         gtk_container_add(GTK_CONTAINER(c->win), c->vbox);
420         gtk_container_add(GTK_CONTAINER(c->vbox), c->scroll);
421         gtk_container_add(GTK_CONTAINER(c->vbox), c->searchbar);
422         gtk_container_add(GTK_CONTAINER(c->vbox), c->urlbar);
423         gtk_container_add(GTK_CONTAINER(c->vbox), c->indicator);
424
425         /* Setup */
426         gtk_box_set_child_packing(GTK_BOX(c->vbox), c->urlbar, FALSE, FALSE, 0, GTK_PACK_START);
427         gtk_box_set_child_packing(GTK_BOX(c->vbox), c->searchbar, FALSE, FALSE, 0, GTK_PACK_START);
428         gtk_box_set_child_packing(GTK_BOX(c->vbox), c->indicator, FALSE, FALSE, 0, GTK_PACK_START);
429         gtk_box_set_child_packing(GTK_BOX(c->vbox), c->scroll, TRUE, TRUE, 0, GTK_PACK_START);
430         gtk_widget_grab_focus(GTK_WIDGET(c->view));
431         gtk_widget_hide_all(c->searchbar);
432         gtk_widget_hide_all(c->urlbar);
433         gtk_widget_show(c->vbox);
434         gtk_widget_show(c->indicator);
435         gtk_widget_show(c->scroll);
436         gtk_widget_show(GTK_WIDGET(c->view));
437         gtk_widget_show(c->win);
438         gdk_window_set_events(GTK_WIDGET(c->win)->window, GDK_ALL_EVENTS_MASK);
439         gdk_window_add_filter(GTK_WIDGET(c->win)->window, processx, c);
440         webkit_web_view_set_full_content_zoom(c->view, TRUE);
441         c->download = NULL;
442         c->title = NULL;
443         c->next = clients;
444         clients = c;
445         if(showxid)
446                 printf("%u\n", (guint)GDK_WINDOW_XID(GTK_WIDGET(c->win)->window));
447         return c;
448 }
449
450 WebKitWebView *
451 newwindow(WebKitWebView  *v, WebKitWebFrame *f, Client *c) {
452         Client *n = newclient();
453         return n->view;
454 }
455
456  
457 void
458 pasteurl(GtkClipboard *clipboard, const gchar *text, gpointer d) {
459         Arg arg = {.v = text };
460         if(text != NULL)
461                 loaduri((Client *) d, &arg);
462 }
463
464 GdkFilterReturn
465 processx(GdkXEvent *e, GdkEvent *event, gpointer d) {
466         Client *c = (Client *)d;
467         XPropertyEvent *ev;
468         Atom adummy;
469         gint idummy;
470         unsigned long ldummy;
471         unsigned char *buf = NULL;
472         Arg arg;
473
474         if(((XEvent *)e)->type == PropertyNotify) {
475                 ev = &((XEvent *)e)->xproperty;
476                 if(ev->atom == urlprop && ev->state == PropertyNewValue) {
477                         if(ignore_once)
478                                ignore_once = FALSE;
479                         else {
480                                 XGetWindowProperty(dpy, ev->window, urlprop, 0L, BUFSIZ, False, XA_STRING,
481                                         &adummy, &idummy, &ldummy, &ldummy, &buf);
482                                 arg.v = buf;
483                                 loaduri(c, &arg);
484                                 XFree(buf);
485                         }
486                         return GDK_FILTER_REMOVE;
487                 }
488         }
489         return GDK_FILTER_CONTINUE;
490 }
491
492 void
493 print(Client *c, const Arg *arg) {
494         webkit_web_frame_print(webkit_web_view_get_main_frame(c->view));
495 }
496
497 void
498 progresschange(WebKitWebView* view, gint p, Client *c) {
499         c->progress = p;
500         update(c, NULL);
501 }
502
503 void
504 request(SoupSession *s, SoupMessage *m, Client *c) {
505         soup_message_add_header_handler(m, "got-headers", "Set-Cookie",
506                         G_CALLBACK(proccookies), c);
507 }
508
509 void
510 reload(Client *c, const Arg *arg) {
511         gboolean nocache = *(gboolean *)arg;
512         if(nocache)
513                  webkit_web_view_reload_bypass_cache(c->view);
514         else
515                  webkit_web_view_reload(c->view);
516 }
517
518 void
519 rereadcookies() {
520         const gchar *filename, *home;
521
522         home = g_get_home_dir();
523         filename = g_build_filename(home, ".surf", "cookies", NULL);
524 }
525
526 void
527 setcookie(char *name, char *val, char *dom, char *path, long exp) {
528
529 }
530
531 void
532 setup() {
533         dpy = GDK_DISPLAY();
534         session = webkit_get_default_session();
535         urlprop = XInternAtom(dpy, "_SURF_URL", False);
536 }
537
538 void
539 showsearch(Client *c, const Arg *arg) {
540         hideurl(c, NULL);
541         gtk_widget_show(c->searchbar);
542         gtk_widget_grab_focus(c->searchbar);
543 }
544
545 void
546 searchtext(Client *c, const Arg *arg) {
547         gboolean forward = *(gboolean *)arg;
548         webkit_web_view_search_text(c->view,
549                         gtk_entry_get_text(GTK_ENTRY(c->searchbar)),
550                         FALSE,
551                         forward,
552                         TRUE);
553 }
554
555 void
556 showurl(Client *c, const Arg *arg) {
557         gchar *uri;
558
559         hidesearch(c, NULL);
560         uri = geturi(c);
561         gtk_entry_set_text(GTK_ENTRY(c->urlbar), uri);
562         gtk_widget_show(c->urlbar);
563         gtk_widget_grab_focus(c->urlbar);
564 }
565
566 void
567 stop(Client *c, const Arg *arg) {
568         if(c->download)
569                 webkit_download_cancel(c->download);
570         else
571                 webkit_web_view_stop_loading(c->view);
572         c->download = NULL;
573 }
574
575 void
576 titlechange(WebKitWebView *v, WebKitWebFrame *f, const gchar *t, Client *c) {
577         update(c, t);
578 }
579
580 void
581 usage() {
582         fputs("surf - simple browser\n", stderr);
583         die("usage: surf [-e] [-x] [uri]\n");
584 }
585
586 void
587 update(Client *c, const char *title) {
588         gchar *t;
589
590         if(title) {
591                 if(c->title)
592                         g_free(c->title);
593                 c->title = g_strdup(title);
594         }
595         if(c->progress == 100)
596                 t = g_strdup(c->title);
597         else
598                 t = g_strdup_printf("%s [%i%%]", c->title, c->progress);
599         drawindicator(c);
600         gtk_window_set_title(GTK_WINDOW(c->win), t);
601         g_free(t);
602
603 }
604
605 void
606 zoom(Client *c, const Arg *arg) {
607         if(arg->i < 0)          /* zoom out */
608                 webkit_web_view_zoom_out(c->view);
609         else if(arg->i > 0)     /* zoom in */
610                 webkit_web_view_zoom_in(c->view);
611         else                    /* reset */
612                 webkit_web_view_set_zoom_level(c->view, 1.0);
613 }
614
615 int main(int argc, char *argv[]) {
616         SoupSession *s;
617         Client *c;
618         gint o;
619         const gchar *home, *filename;
620         Arg arg;
621
622         gtk_init(NULL, NULL);
623         if (!g_thread_supported())
624                 g_thread_init(NULL);
625         setup();
626         while((o = getopt(argc, argv, "vhxeu:f:")) != -1)
627                 switch(o) {
628                 case 'x':
629                         showxid = TRUE;
630                         break;
631                 case 'e':
632                         showxid = TRUE;
633                         embed = TRUE;
634                         break;
635                 case 'v':
636                         die("surf-"VERSION", © 2009 surf engineers, see LICENSE for details\n");
637                         break;
638                 default:
639                         usage();
640                 }
641         if(optind + 1 == argc) {
642                 c = newclient();
643                 arg.v = argv[optind];
644                 if(strchr("./", argv[optind][0]) || strcmp("-", argv[optind]) == 0)
645                         loadfile(c, argv[optind]);
646                 else
647                         loaduri(c, &arg);
648
649         }
650         else if(optind != argc)
651                 usage();
652         if(!clients)
653                 newclient();
654
655         /* make dirs */
656         home = g_get_home_dir();
657         filename = g_build_filename(home, ".surf", NULL);
658         g_mkdir_with_parents(filename, 0711);
659         filename = g_build_filename(home, ".surf", "dl", NULL);
660         g_mkdir_with_parents(filename, 0755);
661
662         /* cookie persistance */
663         s = webkit_get_default_session();
664         filename = g_build_filename(home, ".surf", "cookies.jar", NULL);
665         cookiejar = soup_cookie_jar_text_new(filename, FALSE);
666         soup_session_add_feature(s, SOUP_SESSION_FEATURE(cookiejar));
667
668         gtk_main();
669         cleanup();
670         return EXIT_SUCCESS;
671 }