reappling printing; changing some keys.
[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         gboolean forward = *(gboolean *)arg;
352         if(forward)
353                 webkit_web_view_go_forward(c->view);
354         else
355                 webkit_web_view_go_back(c->view);
356 }
357
358 Client *
359 newclient(void) {
360         Client *c;
361         if(!(c = calloc(1, sizeof(Client))))
362                 die("Cannot malloc!\n");
363         /* Window */
364         if(embed) {
365                 c->win = gtk_plug_new(0);
366         }
367         else {
368                 c->win = gtk_window_new(GTK_WINDOW_TOPLEVEL);
369                 gtk_window_set_wmclass(GTK_WINDOW(c->win), "surf", "surf");
370         }
371         gtk_window_set_default_size(GTK_WINDOW(c->win), 800, 600);
372         g_signal_connect(G_OBJECT(c->win), "destroy", G_CALLBACK(destroywin), c);
373         g_signal_connect(G_OBJECT(c->win), "key-press-event", G_CALLBACK(keypress), c);
374
375         /* VBox */
376         c->vbox = gtk_vbox_new(FALSE, 0);
377
378         /* scrolled window */
379         c->scroll = gtk_scrolled_window_new(NULL, NULL);
380         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(c->scroll),
381                         GTK_POLICY_NEVER, GTK_POLICY_NEVER);
382
383         /* webview */
384         c->view = WEBKIT_WEB_VIEW(webkit_web_view_new());
385         g_signal_connect(G_OBJECT(c->view), "title-changed", G_CALLBACK(titlechange), c);
386         g_signal_connect(G_OBJECT(c->view), "load-progress-changed", G_CALLBACK(progresschange), c);
387         g_signal_connect(G_OBJECT(c->view), "load-committed", G_CALLBACK(loadcommit), c);
388         g_signal_connect(G_OBJECT(c->view), "load-started", G_CALLBACK(loadstart), c);
389         g_signal_connect(G_OBJECT(c->view), "hovering-over-link", G_CALLBACK(linkhover), c);
390         g_signal_connect(G_OBJECT(c->view), "create-web-view", G_CALLBACK(newwindow), c);
391         g_signal_connect(G_OBJECT(c->view), "download-requested", G_CALLBACK(initdownload), c);
392         g_signal_connect_after(session, "request-started", G_CALLBACK(request), c);
393
394         /* urlbar */
395         c->urlbar = gtk_entry_new();
396         gtk_entry_set_has_frame(GTK_ENTRY(c->urlbar), FALSE);
397
398         /* searchbar */
399         c->searchbar = gtk_entry_new();
400         gtk_entry_set_has_frame(GTK_ENTRY(c->searchbar), FALSE);
401
402         /* downloadbar */
403
404         /* Arranging */
405         gtk_container_add(GTK_CONTAINER(c->scroll), GTK_WIDGET(c->view));
406         gtk_container_add(GTK_CONTAINER(c->win), c->vbox);
407         gtk_container_add(GTK_CONTAINER(c->vbox), c->scroll);
408         gtk_container_add(GTK_CONTAINER(c->vbox), c->searchbar);
409         gtk_container_add(GTK_CONTAINER(c->vbox), c->urlbar);
410
411         /* Setup */
412         gtk_box_set_child_packing(GTK_BOX(c->vbox), c->urlbar, FALSE, FALSE, 0, GTK_PACK_START);
413         gtk_box_set_child_packing(GTK_BOX(c->vbox), c->searchbar, FALSE, FALSE, 0, GTK_PACK_START);
414         gtk_box_set_child_packing(GTK_BOX(c->vbox), c->scroll, TRUE, TRUE, 0, GTK_PACK_START);
415         gtk_widget_grab_focus(GTK_WIDGET(c->view));
416         gtk_widget_hide_all(c->searchbar);
417         gtk_widget_hide_all(c->urlbar);
418         gtk_widget_show(c->vbox);
419         gtk_widget_show(c->scroll);
420         gtk_widget_show(GTK_WIDGET(c->view));
421         gtk_widget_show(c->win);
422         gdk_window_set_events(GTK_WIDGET(c->win)->window, GDK_ALL_EVENTS_MASK);
423         gdk_window_add_filter(GTK_WIDGET(c->win)->window, processx, c);
424         webkit_web_view_set_full_content_zoom(c->view, TRUE);
425         c->download = NULL;
426         c->title = NULL;
427         c->next = clients;
428         clients = c;
429         if(showxid)
430                 printf("%u\n", (unsigned int)GDK_WINDOW_XID(GTK_WIDGET(c->win)->window));
431         return c;
432 }
433
434 WebKitWebView *
435 newwindow(WebKitWebView  *v, WebKitWebFrame *f, Client *c) {
436         Client *n = newclient();
437         return n->view;
438 }
439
440  
441 void
442 pasteurl(GtkClipboard *clipboard, const gchar *text, gpointer d) {
443         Arg arg = {.v = text };
444         if(text != NULL)
445                 loaduri((Client *) d, &arg);
446 }
447
448 GdkFilterReturn
449 processx(GdkXEvent *e, GdkEvent *event, gpointer d) {
450         Client *c = (Client *)d;
451         XPropertyEvent *ev;
452         Atom adummy;
453         int idummy;
454         unsigned long ldummy;
455         unsigned char *buf = NULL;
456         Arg arg;
457
458         if(((XEvent *)e)->type == PropertyNotify) {
459                 ev = &((XEvent *)e)->xproperty;
460                 if(ev->atom == urlprop && ev->state == PropertyNewValue) {
461                         if(ignore_once)
462                                ignore_once = FALSE;
463                         else {
464                                 XGetWindowProperty(dpy, ev->window, urlprop, 0L, BUFSIZ, False, XA_STRING,
465                                         &adummy, &idummy, &ldummy, &ldummy, &buf);
466                                 arg.v = buf;
467                                 loaduri(c, &arg);
468                                 XFree(buf);
469                         }
470                         return GDK_FILTER_REMOVE;
471                 }
472         }
473         return GDK_FILTER_CONTINUE;
474 }
475
476 void
477 print(Client *c, const Arg *arg) {
478         webkit_web_frame_print(webkit_web_view_get_main_frame(c->view));
479 }
480
481 void
482 progresschange(WebKitWebView* view, gint p, Client *c) {
483         c->progress = p;
484         updatetitle(c, NULL);
485 }
486
487 void
488 request(SoupSession *s, SoupMessage *m, Client *c) {
489         soup_message_add_header_handler(m, "got-headers", "Set-Cookie",
490                         G_CALLBACK(proccookies), c);
491 }
492
493 void
494 reload(Client *c, const Arg *arg) {
495         gboolean nocache = *(gboolean *)arg;
496         if(nocache)
497                  webkit_web_view_reload_bypass_cache(c->view);
498         else
499                  webkit_web_view_reload(c->view);
500 }
501
502 void
503 setcookie(char *name, char *val, char *dom, char *path, long exp) {
504         printf("%s %s %s %s %li\n", name, val, dom, path, exp);
505 }
506
507 void
508 setup() {
509         dpy = GDK_DISPLAY();
510         session = webkit_get_default_session();
511         urlprop = XInternAtom(dpy, "_SURF_URL", False);
512 }
513
514 void
515 showsearch(Client *c, const Arg *arg) {
516         hideurl(c, NULL);
517         gtk_widget_show(c->searchbar);
518         gtk_widget_grab_focus(c->searchbar);
519 }
520
521 void
522 searchtext(Client *c, const Arg *arg) {
523         gboolean forward = *(gboolean *)arg;
524         webkit_web_view_search_text(c->view,
525                         gtk_entry_get_text(GTK_ENTRY(c->searchbar)),
526                         FALSE,
527                         forward,
528                         TRUE);
529 }
530
531 void
532 showurl(Client *c, const Arg *arg) {
533         gchar *uri;
534
535         hidesearch(c, NULL);
536         uri = geturi(c);
537         gtk_entry_set_text(GTK_ENTRY(c->urlbar), uri);
538         gtk_widget_show(c->urlbar);
539         gtk_widget_grab_focus(c->urlbar);
540 }
541
542 void
543 stop(Client *c, const Arg *arg) {
544         if(c->download)
545                 webkit_download_cancel(c->download);
546         else
547                 webkit_web_view_stop_loading(c->view);
548         c->download = NULL;
549 }
550
551 void
552 titlechange(WebKitWebView *v, WebKitWebFrame *f, const gchar *t, Client *c) {
553         updatetitle(c, t);
554 }
555
556 void
557 usage() {
558         fputs("surf - simple browser\n", stderr);
559         die("usage: surf [-e] [-x] [uri]\n");
560 }
561
562 void
563 updatetitle(Client *c, const char *title) {
564         gchar *t;
565
566         if(title) {
567                 if(c->title)
568                         g_free(c->title);
569                 c->title = g_strdup(title);
570         }
571         if(c->progress == 100)
572                 t = g_strdup(c->title);
573         else
574                 t = g_strdup_printf("%s [%i%%]", c->title, c->progress);
575         gtk_window_set_title(GTK_WINDOW(c->win), t);
576         g_free(t);
577
578 }
579
580 void
581 zoompage(Client *c, const Arg *arg) {
582         if(*(float *)arg < 0)           /* zoom out */
583                 webkit_web_view_zoom_out(c->view);
584         else if(*(float *)arg == 0)     /* zoom in */
585                 webkit_web_view_zoom_in(c->view);
586         else                            /* absolute level */
587                 webkit_web_view_set_zoom_level(c->view, *(float *)arg);
588 }
589
590 int main(int argc, char *argv[]) {
591         SoupSession *s;
592         Client *c;
593         int o;
594         const gchar *home, *filename;
595         Arg arg;
596
597         gtk_init(NULL, NULL);
598         if (!g_thread_supported())
599                 g_thread_init(NULL);
600         setup();
601         while((o = getopt(argc, argv, "vhxeu:f:")) != -1)
602                 switch(o) {
603                 case 'x':
604                         showxid = TRUE;
605                         break;
606                 case 'e':
607                         showxid = TRUE;
608                         embed = TRUE;
609                         break;
610                 case 'v':
611                         die("surf-"VERSION", © 2009 surf engineers, see LICENSE for details\n");
612                         break;
613                 default:
614                         usage();
615                 }
616         if(optind + 1 == argc) {
617                 c = newclient();
618                 arg.v = argv[optind];
619                 if(strchr("./", argv[optind][0]) || strcmp("-", argv[optind]) == 0)
620                         loadfile(c, argv[optind]);
621                 else
622                         loaduri(c, &arg);
623
624         }
625         else if(optind != argc)
626                 usage();
627         if(!clients)
628                 newclient();
629
630         /* make dirs */
631         home = g_get_home_dir();
632         filename = g_build_filename(home, ".surf", NULL);
633         g_mkdir_with_parents(filename, 0711);
634         filename = g_build_filename(home, ".surf", "dl", NULL);
635         g_mkdir_with_parents(filename, 0755);
636
637         /* cookie persistance */
638         s = webkit_get_default_session();
639         filename = g_build_filename(home, ".surf", "cookies", NULL);
640         cookiejar = soup_cookie_jar_text_new(filename, FALSE);
641         soup_session_add_feature(s, SOUP_SESSION_FEATURE(cookiejar));
642
643         gtk_main();
644         cleanup();
645         return EXIT_SUCCESS;
646 }