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