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