fixing downloads
[surf.git] / surf.c
1 /* See LICENSE file for copyright and license details.
2  *
3  * To understand surf, start reading main().
4  */
5 #include <signal.h>
6 #include <X11/X.h>
7 #include <X11/Xatom.h>
8 #include <gtk/gtk.h>
9 #include <gdk/gdkx.h>
10 #include <gdk/gdk.h>
11 #include <gdk/gdkkeysyms.h>
12 #include <string.h>
13 #include <sys/types.h>
14 #include <sys/wait.h>
15 #include <unistd.h>
16 #include <stdlib.h>
17 #include <stdio.h>
18 #include <webkit/webkit.h>
19 #include <glib/gstdio.h>
20 #include <JavaScriptCore/JavaScript.h>
21
22 #define LENGTH(x)               (sizeof x / sizeof x[0])
23 #define CLEANMASK(mask)         (mask & ~(GDK_MOD2_MASK))
24
25 typedef union Arg Arg;
26 union Arg {
27         gboolean b;
28         gint i;
29         const void *v;
30 };
31
32 typedef struct Client {
33         GtkWidget *win, *scroll, *vbox, *indicator;
34         GtkWidget **items;
35         WebKitWebView *view;
36         WebKitDownload *download;
37         char *title, *linkhover;
38         const char *uri, *needle;
39         gint progress;
40         struct Client *next;
41         gboolean zoomed;
42 } Client;
43
44 typedef struct {
45         char *label;
46         void (*func)(Client *c, const Arg *arg);
47         const Arg arg;
48 } Item;
49
50 typedef struct {
51         guint mod;
52         guint keyval;
53         void (*func)(Client *c, const Arg *arg);
54         const Arg arg;
55 } Key;
56
57 static Display *dpy;
58 static Atom uriprop, findprop;
59 static Client *clients = NULL;
60 static GdkNativeWindow embed = 0;
61 static gboolean showxid = FALSE;
62 static int ignorexprop = 0;
63 static char winid[64];
64 static char *progname;
65 static gboolean loadimage = 1, plugin = 1, script = 1;
66
67 static char *buildpath(const char *path);
68 static void cleanup(void);
69 static void clipboard(Client *c, const Arg *arg);
70 static void context(WebKitWebView *v, GtkMenu *m, Client *c);
71 static char *copystr(char **str, const char *src);
72 static WebKitWebView *createwindow(WebKitWebView *v, WebKitWebFrame *f, Client *c);
73 static gboolean decidedownload(WebKitWebView *v, WebKitWebFrame *f, WebKitNetworkRequest *r, gchar *m,  WebKitWebPolicyDecision *p, Client *c);
74 static gboolean decidewindow(WebKitWebView *v, WebKitWebFrame *f, WebKitNetworkRequest *r, WebKitWebNavigationAction *n, WebKitWebPolicyDecision *p, Client *c);
75 static void destroyclient(Client *c);
76 static void destroywin(GtkWidget* w, Client *c);
77 static void die(char *str);
78 static void download(Client *c, const Arg *arg);
79 static void drawindicator(Client *c);
80 static gboolean exposeindicator(GtkWidget *w, GdkEventExpose *e, Client *c);
81 static void find(Client *c, const Arg *arg);
82 static const char *getatom(Client *c, Atom a);
83 static const char *getcookies(SoupURI *uri);
84 static char *geturi(Client *c);
85 void gotheaders(SoupMessage *msg, gpointer user_data);
86 static gboolean initdownload(WebKitWebView *v, WebKitDownload *o, Client *c);
87 static void itemclick(GtkMenuItem *mi, Client *c);
88 static gboolean keypress(GtkWidget *w, GdkEventKey *ev, Client *c);
89 static void linkhover(WebKitWebView *v, const char* t, const char* l, Client *c);
90 static void loadstatuschange(WebKitWebView *view, GParamSpec *pspec, Client *c);
91 static void loaduri(Client *c, const Arg *arg);
92 static void navigate(Client *c, const Arg *arg);
93 static Client *newclient(void);
94 static void newwindow(Client *c, const Arg *arg);
95 static void newrequest(SoupSession *s, SoupMessage *msg, gpointer v);
96 static void pasteuri(GtkClipboard *clipboard, const char *text, gpointer d);
97 static void print(Client *c, const Arg *arg);
98 static GdkFilterReturn processx(GdkXEvent *xevent, GdkEvent *event, gpointer d);
99 static void progresschange(WebKitWebView *view, GParamSpec *pspec, Client *c);
100 static void reload(Client *c, const Arg *arg);
101 static void resize(GtkWidget *w, GtkAllocation *a, Client *c);
102 static void scroll(Client *c, const Arg *arg);
103 static void setatom(Client *c, Atom a, const char *v);
104 static void setcookie(SoupCookie *c);
105 static void setup(void);
106 static void sigchld(int unused);
107 static void source(Client *c, const Arg *arg);
108 static void spawn(Client *c, const Arg *arg);
109 static void stop(Client *c, const Arg *arg);
110 static void titlechange(WebKitWebView *v, WebKitWebFrame* frame, const char* title, Client *c);
111 static void update(Client *c);
112 static void updatedownload(WebKitDownload *o, GParamSpec *pspec, Client *c);
113 static void updatewinid(Client *c);
114 static void usage(void);
115 static void windowobjectcleared(GtkWidget *w, WebKitWebFrame *frame, JSContextRef js, JSObjectRef win, Client *c);
116 static void zoom(Client *c, const Arg *arg);
117
118 /* configuration, allows nested code to access above variables */
119 #include "config.h"
120
121 char *
122 buildpath(const char *path) {
123         char *apath, *p;
124         FILE *f;
125
126         /* creating directory */
127         if(path[0] == '/')
128                 apath = g_strdup(path);
129         else
130                 apath = g_strconcat(g_get_home_dir(), "/", path, NULL);
131         if((p = strrchr(apath, '/'))) {
132                 *p = '\0';
133                 g_mkdir_with_parents(apath, 0755);
134                 *p = '/';
135         }
136         /* creating file (gives error when apath ends with "/") */
137         if((f = g_fopen(apath, "a")))
138                 fclose(f);
139         return apath;
140 }
141
142 void
143 cleanup(void) {
144         while(clients)
145                 destroyclient(clients);
146         g_free(cookiefile);
147         g_free(dldir);
148         g_free(scriptfile);
149         g_free(stylefile);
150 }
151
152 void
153 clipboard(Client *c, const Arg *arg) {
154         gboolean paste = *(gboolean *)arg;
155
156         if(paste)
157                 gtk_clipboard_request_text(gtk_clipboard_get(GDK_SELECTION_PRIMARY), pasteuri, c);
158         else
159                 gtk_clipboard_set_text(gtk_clipboard_get(GDK_SELECTION_PRIMARY), c->linkhover ? c->linkhover : geturi(c), -1);
160 }
161
162 void
163 context(WebKitWebView *v, GtkMenu *m, Client *c) {
164         int i;
165         GtkContainer *parent;
166
167         gtk_widget_hide_all(GTK_WIDGET(m));
168         gtk_widget_show(GTK_WIDGET(m));
169         for(i = 0; i < LENGTH(items); i++) {
170                 parent = GTK_CONTAINER(gtk_widget_get_parent(c->items[i]));
171                 if(parent)
172                         gtk_container_remove(parent, c->items[i]);
173                 gtk_menu_shell_append(GTK_MENU_SHELL(m), c->items[i]);
174                 gtk_widget_show(c->items[i]);
175         }
176 }
177
178 char *
179 copystr(char **str, const char *src) {
180         char *tmp;
181         tmp = g_strdup(src);
182
183         if(str && *str) {
184                 g_free(*str);
185                 *str = tmp;
186         }
187         return tmp;
188 }
189
190 WebKitWebView *
191 createwindow(WebKitWebView  *v, WebKitWebFrame *f, Client *c) {
192         Client *n = newclient();
193         return n->view;
194 }
195
196 gboolean
197 decidedownload(WebKitWebView *v, WebKitWebFrame *f, WebKitNetworkRequest *r, gchar *m,  WebKitWebPolicyDecision *p, Client *c) {
198         if(!webkit_web_view_can_show_mime_type(v, m)) {
199                 webkit_web_policy_decision_download(p);
200                 return TRUE;
201         }
202         return FALSE;
203 }
204
205 gboolean
206 decidewindow(WebKitWebView *view, WebKitWebFrame *f, WebKitNetworkRequest *r, WebKitWebNavigationAction *n, WebKitWebPolicyDecision *p, Client *c) {
207         Arg arg;
208
209         if(webkit_web_navigation_action_get_reason(n) == WEBKIT_WEB_NAVIGATION_REASON_LINK_CLICKED) {
210                 webkit_web_policy_decision_ignore(p);
211                 arg.v = (void *)webkit_network_request_get_uri(r);
212                 newwindow(NULL, &arg);
213                 return TRUE;
214         }
215         return FALSE;
216 }
217
218 void
219 destroyclient(Client *c) {
220         int i;
221         Client *p;
222
223         gtk_widget_destroy(c->indicator);
224         gtk_widget_destroy(GTK_WIDGET(c->view));
225         gtk_widget_destroy(c->scroll);
226         gtk_widget_destroy(c->vbox);
227         gtk_widget_destroy(c->win);
228         for(i = 0; i < LENGTH(items); i++)
229                 gtk_widget_destroy(c->items[i]);
230         free(c->items);
231
232         for(p = clients; p && p->next != c; p = p->next);
233         if(p)
234                 p->next = c->next;
235         else
236                 clients = c->next;
237         free(c);
238         if(clients == NULL)
239                 gtk_main_quit();
240 }
241
242 void
243 destroywin(GtkWidget* w, Client *c) {
244         destroyclient(c);
245 }
246
247 void
248 die(char *str) {
249         fputs(str, stderr);
250         exit(EXIT_FAILURE);
251 }
252
253 void
254 download(Client *c, const Arg *arg) {
255         char *uri;
256         WebKitNetworkRequest *r;
257         WebKitDownload       *dl;
258
259         if(arg->v)
260                 uri = (char *)arg->v;
261         else
262                 uri = c->linkhover ? c->linkhover : geturi(c);
263         r = webkit_network_request_new(uri);
264         dl = webkit_download_new(r);
265         initdownload(c->view, dl, c);
266         webkit_download_start(c->download);
267 }
268
269 void
270 drawindicator(Client *c) {
271         gint width;
272         const char *uri;
273         GtkWidget *w;
274         GdkGC *gc;
275         GdkColor fg;
276
277         uri = getatom(c, uriprop);
278         w = c->indicator;
279         width = c->progress * w->allocation.width / 100;
280         gc = gdk_gc_new(w->window);
281         gdk_color_parse(strstr(uri, "https://") == uri ?
282                         progress_trust : progress, &fg);
283         gdk_gc_set_rgb_fg_color(gc, &fg);
284         gdk_draw_rectangle(w->window,
285                         w->style->bg_gc[GTK_WIDGET_STATE(w)],
286                         TRUE, 0, 0, w->allocation.width, w->allocation.height);
287         gdk_draw_rectangle(w->window, gc, TRUE, 0, 0, width,
288                         w->allocation.height);
289         g_object_unref(gc);
290 }
291
292 gboolean
293 exposeindicator(GtkWidget *w, GdkEventExpose *e, Client *c) {
294         drawindicator(c);
295         return TRUE;
296 }
297
298 void
299 find(Client *c, const Arg *arg) {
300         const char *s;
301
302         s = getatom(c, findprop);
303         gboolean forward = *(gboolean *)arg;
304         webkit_web_view_search_text(c->view, s, FALSE, forward, TRUE);
305 }
306
307 const char *
308 getcookies(SoupURI *uri) {
309         return NULL;
310 }
311
312 const char *
313 getatom(Client *c, Atom a) {
314         static char buf[BUFSIZ];
315         Atom adummy;
316         int idummy;
317         unsigned long ldummy;
318         unsigned char *p = NULL;
319
320         XGetWindowProperty(dpy, GDK_WINDOW_XID(GTK_WIDGET(c->win)->window),
321                         a, 0L, BUFSIZ, False, XA_STRING,
322                         &adummy, &idummy, &ldummy, &ldummy, &p);
323         if(p)
324                 strncpy(buf, (char *)p, LENGTH(buf)-1);
325         else
326                 buf[0] = '\0';
327         XFree(p);
328         return buf;
329 }
330
331 char *
332 geturi(Client *c) {
333         char *uri;
334
335         if(!(uri = (char *)webkit_web_view_get_uri(c->view)))
336                 uri = "about:blank";
337         return uri;
338 }
339
340 void
341 gotheaders(SoupMessage *msg, gpointer v) {
342         SoupURI *uri;
343         GSList *l, *p;
344
345         uri = soup_message_get_uri(msg);
346         for(p = l = soup_cookies_from_response(msg); p;
347                 p = g_slist_next(p))  {
348                 setcookie((SoupCookie *)p->data);
349         }
350         soup_cookies_free(l);
351 }
352
353 gboolean
354 initdownload(WebKitWebView *view, WebKitDownload *o, Client *c) {
355         const char *filename;
356         char *uri;
357         WebKitWebBackForwardList *h;
358         WebKitWebHistoryItem *i;
359
360         c->download = o;
361         filename = webkit_download_get_suggested_filename(o);
362         if(!strcmp("", filename))
363                 filename = "index.html";
364         uri = g_strconcat("file://", dldir, "/", filename, NULL);
365         webkit_download_set_destination_uri(c->download, uri);
366         c->progress = 0;
367         h = webkit_web_view_get_back_forward_list(c->view);
368         i = webkit_web_history_item_new_with_data(webkit_download_get_uri(c->download), filename);
369         webkit_web_back_forward_list_add_item(h, i);
370         g_signal_connect(c->download, "notify::progress", G_CALLBACK(updatedownload), c);
371         g_signal_connect(c->download, "notify::status", G_CALLBACK(updatedownload), c);
372         
373         c->title = copystr(&c->title, filename);
374         update(c);
375         return TRUE;
376 }
377
378 void
379 itemclick(GtkMenuItem *mi, Client *c) {
380         int i;
381         const char *label;
382
383         label = gtk_menu_item_get_label(mi);
384         for(i = 0; i < LENGTH(items); i++)
385                 if(!strcmp(items[i].label, label))
386                         items[i].func(c, &(items[i].arg));
387 }
388
389 gboolean
390 keypress(GtkWidget* w, GdkEventKey *ev, Client *c) {
391         guint i;
392         gboolean processed = FALSE;
393
394         updatewinid(c);
395         for(i = 0; i < LENGTH(keys); i++) {
396                 if(gdk_keyval_to_lower(ev->keyval) == keys[i].keyval
397                                 && CLEANMASK(ev->state) == keys[i].mod
398                                 && keys[i].func) {
399                         keys[i].func(c, &(keys[i].arg));
400                         processed = TRUE;
401                 }
402         }
403         return processed;
404 }
405
406 void
407 linkhover(WebKitWebView *v, const char* t, const char* l, Client *c) {
408         if(l)
409                 c->linkhover = copystr(&c->linkhover, l);
410         else if(c->linkhover) {
411                 free(c->linkhover);
412                 c->linkhover = NULL;
413         }
414         update(c);
415 }
416
417 void
418 loadstatuschange(WebKitWebView *view, GParamSpec *pspec, Client *c) {
419         if(c->download)
420                 stop(c, NULL);
421         switch(webkit_web_view_get_load_status (c->view)) {
422         case WEBKIT_LOAD_COMMITTED:
423                 setatom(c, uriprop, geturi(c));
424                 break;
425         case WEBKIT_LOAD_FINISHED:
426                 c->progress = 0;
427                 update(c);
428                 break;
429         case WEBKIT_LOAD_PROVISIONAL:
430         case WEBKIT_LOAD_FIRST_VISUALLY_NON_EMPTY_LAYOUT:
431                 break;
432         }
433 }
434
435 void
436 loaduri(Client *c, const Arg *arg) {
437         char *u;
438         const char *uri = (char *)arg->v;
439         Arg a = { .b = FALSE };
440
441         if(strcmp(uri, "") == 0)
442                 return;
443         u = g_strrstr(uri, "://") ? g_strdup(uri)
444                 : g_strdup_printf("http://%s", uri);
445         /* prevents endless loop */
446         if(c->uri && strcmp(u, c->uri) == 0) {
447                 reload(c, &a);
448         }
449         else {
450                 webkit_web_view_load_uri(c->view, u);
451                 c->progress = 0;
452                 c->title = copystr(&c->title, u);
453                 g_free(u);
454                 update(c);
455         }
456 }
457
458 void
459 navigate(Client *c, const Arg *arg) {
460         int steps = *(int *)arg;
461         webkit_web_view_go_back_or_forward(c->view, steps);
462 }
463
464 Client *
465 newclient(void) {
466         int i;
467         Client *c;
468         WebKitWebSettings *settings;
469         GdkGeometry hints = { 1, 1 };
470         char *uri, *ua;
471
472         if(!(c = calloc(1, sizeof(Client))))
473                 die("Cannot malloc!\n");
474         /* Window */
475         if(embed) {
476                 c->win = gtk_plug_new(embed);
477         }
478         else {
479                 c->win = gtk_window_new(GTK_WINDOW_TOPLEVEL);
480                 /* TA:  20091214:  Despite what the GNOME docs say, the ICCCM
481                  * is always correct, so we should still call this function.
482                  * But when doing so, we *must* differentiate between a
483                  * WM_CLASS and a resource on the window.  By convention, the
484                  * window class (WM_CLASS) is capped, while the resource is in
485                  * lowercase.   Both these values come as a pair.
486                  */
487                 gtk_window_set_wmclass(GTK_WINDOW(c->win), "surf", "surf");
488
489                 /* TA:  20091214:  And set the role here as well -- so that
490                  * sessions can pick this up.
491                  */
492                 gtk_window_set_role(GTK_WINDOW(c->win), "Surf");
493         }
494         gtk_window_set_default_size(GTK_WINDOW(c->win), 800, 600);
495         g_signal_connect(G_OBJECT(c->win), "destroy", G_CALLBACK(destroywin), c);
496         g_signal_connect(G_OBJECT(c->win), "key-press-event", G_CALLBACK(keypress), c);
497         g_signal_connect(G_OBJECT(c->win), "size-allocate", G_CALLBACK(resize), c);
498
499         if(!(c->items = calloc(1, sizeof(GtkWidget *) * LENGTH(items))))
500                 die("Cannot malloc!\n");
501
502         /* contextmenu */
503         for(i = 0; i < LENGTH(items); i++) {
504                 c->items[i] = gtk_menu_item_new_with_label(items[i].label);
505                 g_signal_connect(G_OBJECT(c->items[i]), "activate",
506                                 G_CALLBACK(itemclick), c);
507         }
508
509         /* VBox */
510         c->vbox = gtk_vbox_new(FALSE, 0);
511
512         /* Scrolled Window */
513         c->scroll = gtk_scrolled_window_new(NULL, NULL);
514         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(c->scroll),
515                         GTK_POLICY_NEVER, GTK_POLICY_NEVER);
516
517         /* Webview */
518         c->view = WEBKIT_WEB_VIEW(webkit_web_view_new());
519         g_signal_connect(G_OBJECT(c->view), "title-changed", G_CALLBACK(titlechange), c);
520         g_signal_connect(G_OBJECT(c->view), "hovering-over-link", G_CALLBACK(linkhover), c);
521         g_signal_connect(G_OBJECT(c->view), "create-web-view", G_CALLBACK(createwindow), c);
522         g_signal_connect(G_OBJECT(c->view), "new-window-policy-decision-requested", G_CALLBACK(decidewindow), c);
523         g_signal_connect(G_OBJECT(c->view), "mime-type-policy-decision-requested", G_CALLBACK(decidedownload), c);
524         g_signal_connect(G_OBJECT(c->view), "download-requested", G_CALLBACK(initdownload), c);
525         g_signal_connect(G_OBJECT(c->view), "window-object-cleared", G_CALLBACK(windowobjectcleared), c);
526         g_signal_connect(G_OBJECT(c->view), "populate-popup", G_CALLBACK(context), c);
527         g_signal_connect(G_OBJECT(c->view), "notify::load-status", G_CALLBACK(loadstatuschange), c);
528         g_signal_connect(G_OBJECT(c->view), "notify::progress", G_CALLBACK(progresschange), c);
529
530         /* Indicator */
531         c->indicator = gtk_drawing_area_new();
532         gtk_widget_set_size_request(c->indicator, 0, 2);
533         g_signal_connect (G_OBJECT (c->indicator), "expose_event",
534                         G_CALLBACK (exposeindicator), c);
535
536         /* Arranging */
537         gtk_container_add(GTK_CONTAINER(c->scroll), GTK_WIDGET(c->view));
538         gtk_container_add(GTK_CONTAINER(c->win), c->vbox);
539         gtk_container_add(GTK_CONTAINER(c->vbox), c->scroll);
540         gtk_container_add(GTK_CONTAINER(c->vbox), c->indicator);
541
542         /* Setup */
543         gtk_box_set_child_packing(GTK_BOX(c->vbox), c->indicator, FALSE, FALSE, 0, GTK_PACK_START);
544         gtk_box_set_child_packing(GTK_BOX(c->vbox), c->scroll, TRUE, TRUE, 0, GTK_PACK_START);
545         gtk_widget_grab_focus(GTK_WIDGET(c->view));
546         gtk_widget_show(c->vbox);
547         gtk_widget_show(c->indicator);
548         gtk_widget_show(c->scroll);
549         gtk_widget_show(GTK_WIDGET(c->view));
550         gtk_widget_show(c->win);
551         gtk_window_set_geometry_hints(GTK_WINDOW(c->win), NULL, &hints, GDK_HINT_MIN_SIZE);
552         gdk_window_set_events(GTK_WIDGET(c->win)->window, GDK_ALL_EVENTS_MASK);
553         gdk_window_add_filter(GTK_WIDGET(c->win)->window, processx, c);
554         webkit_web_view_set_full_content_zoom(c->view, TRUE);
555         settings = webkit_web_view_get_settings(c->view);
556         if(!(ua = getenv("SURF_USERAGENT")))
557                 ua = useragent;
558         g_object_set(G_OBJECT(settings), "user-agent", ua, NULL);
559         uri = g_strconcat("file://", stylefile, NULL);
560         g_object_set(G_OBJECT(settings), "user-stylesheet-uri", uri, NULL);
561         g_object_set(G_OBJECT(settings), "auto-load-images", loadimage, NULL);
562         g_object_set(G_OBJECT(settings), "enable-plugins", plugin, NULL);
563         g_object_set(G_OBJECT(settings), "enable-scripts", script, NULL);
564         g_free(uri);
565         setatom(c, findprop, "");
566         setatom(c, uriprop, "");
567
568         c->download = NULL;
569         c->title = NULL;
570         c->next = clients;
571         clients = c;
572         if(showxid) {
573                 gdk_display_sync(gtk_widget_get_display(c->win));
574                 printf("%u\n", (guint)GDK_WINDOW_XID(GTK_WIDGET(c->win)->window));
575                 fflush(NULL);
576         }
577         return c;
578 }
579
580 void
581 newrequest(SoupSession *s, SoupMessage *msg, gpointer v) {
582         SoupMessageHeaders *h = msg->request_headers;
583         SoupURI *uri;
584         const char *c;
585
586         soup_message_headers_remove(h, "Cookie");
587         uri = soup_message_get_uri(msg);
588         if((c = getcookies(uri))) {
589                 soup_message_headers_append(h, "Cookie", c);
590         }
591         g_signal_connect_after(G_OBJECT(msg), "got-headers", G_CALLBACK(gotheaders), NULL);
592 }
593
594 void
595 newwindow(Client *c, const Arg *arg) {
596         guint i = 0;
597         const char *cmd[10], *uri;
598         const Arg a = { .v = (void *)cmd };
599         char tmp[64];
600
601         cmd[i++] = progname;
602         if(embed) {
603                 cmd[i++] = "-e";
604                 snprintf(tmp, LENGTH(tmp), "%u\n", (int)embed);
605                 cmd[i++] = tmp;
606         }
607         if(!script)
608                 cmd[i++] = "-s";
609         if(!plugin)
610                 cmd[i++] = "-p";
611         if(!loadimage)
612                 cmd[i++] = "-l";
613         if(showxid)
614                 cmd[i++] = "-x";
615         cmd[i++] = "--";
616         uri = arg->v ? (char *)arg->v : c->linkhover;
617         if(uri)
618                 cmd[i++] = uri;
619         cmd[i++] = NULL;
620         spawn(NULL, &a);
621 }
622
623 void
624 pasteuri(GtkClipboard *clipboard, const char *text, gpointer d) {
625         Arg arg = {.v = text };
626         if(text != NULL)
627                 loaduri((Client *) d, &arg);
628 }
629
630 void
631 print(Client *c, const Arg *arg) {
632         webkit_web_frame_print(webkit_web_view_get_main_frame(c->view));
633 }
634
635 GdkFilterReturn
636 processx(GdkXEvent *e, GdkEvent *event, gpointer d) {
637         Client *c = (Client *)d;
638         XPropertyEvent *ev;
639         Arg arg;
640
641         if(((XEvent *)e)->type == PropertyNotify) {
642                 ev = &((XEvent *)e)->xproperty;
643                 if(ignorexprop)
644                         ignorexprop--;
645                 else if(ev->state == PropertyNewValue) {
646                         if(ev->atom == uriprop) {
647                                 arg.v = getatom(c, uriprop);
648                                 loaduri(c, &arg);
649                         }
650                         else if(ev->atom == findprop) {
651                                 arg.b = TRUE;
652                                 find(c, &arg);
653                         }
654                         return GDK_FILTER_REMOVE;
655                 }
656         }
657         return GDK_FILTER_CONTINUE;
658 }
659
660 void
661 progresschange(WebKitWebView *view, GParamSpec *pspec, Client *c) {
662         c->progress = webkit_web_view_get_progress(c->view) * 100;
663         update(c);
664 }
665
666 void
667 reload(Client *c, const Arg *arg) {
668         gboolean nocache = *(gboolean *)arg;
669         if(nocache)
670                  webkit_web_view_reload_bypass_cache(c->view);
671         else
672                  webkit_web_view_reload(c->view);
673 }
674
675 void
676 resize(GtkWidget *w, GtkAllocation *a, Client *c) {
677         double zoom;
678
679         if(c->zoomed)
680                 return;
681         zoom = webkit_web_view_get_zoom_level(c->view);
682         if(a->width * a->height < 300 * 400 && zoom != 0.2)
683                 webkit_web_view_set_zoom_level(c->view, 0.2);
684         else if(zoom != 1.0)
685                 webkit_web_view_set_zoom_level(c->view, 1.0);
686 }
687
688 void
689 scroll(Client *c, const Arg *arg) {
690         gdouble v;
691         GtkAdjustment *a;
692
693         a = gtk_scrolled_window_get_vadjustment(GTK_SCROLLED_WINDOW(c->scroll));
694         v = gtk_adjustment_get_value(a);
695         v += gtk_adjustment_get_step_increment(a) * arg->i;
696         v = MAX(v, 0.0);
697         v = MIN(v, gtk_adjustment_get_upper(a) - gtk_adjustment_get_page_size(a));
698         gtk_adjustment_set_value(a, v);
699 }
700
701 void
702 setcookie(SoupCookie *c) {
703
704 }
705
706 void
707 setatom(Client *c, Atom a, const char *v) {
708         XSync(dpy, False);
709         ignorexprop++;
710         XChangeProperty(dpy, GDK_WINDOW_XID(GTK_WIDGET(c->win)->window), a,
711                         XA_STRING, 8, PropModeReplace, (unsigned char *)v,
712                         strlen(v) + 1);
713 }
714
715 void
716 setup(void) {
717         char *proxy;
718         char *new_proxy;
719         SoupURI *puri;
720         SoupSession *s;
721
722         /* clean up any zombies immediately */
723         sigchld(0);
724         gtk_init(NULL, NULL);
725         if (!g_thread_supported())
726                 g_thread_init(NULL);
727
728         dpy = GDK_DISPLAY();
729         s = webkit_get_default_session();
730         uriprop = XInternAtom(dpy, "_SURF_URI", False);
731         findprop = XInternAtom(dpy, "_SURF_FIND", False);
732
733         /* dirs and files */
734         cookiefile = buildpath(cookiefile);
735         dldir = buildpath(dldir);
736         scriptfile = buildpath(scriptfile);
737         stylefile = buildpath(stylefile);
738
739         /* request handler */
740         s = webkit_get_default_session();
741         soup_session_remove_feature_by_type(s, soup_cookie_get_type());
742         soup_session_remove_feature_by_type(s, soup_cookie_jar_get_type());
743         g_signal_connect_after(G_OBJECT(s), "request-started", G_CALLBACK(newrequest), NULL);
744
745
746         /* proxy */
747         if((proxy = getenv("http_proxy")) && strcmp(proxy, "")) {
748                 new_proxy = g_strrstr(proxy, "http://") ? g_strdup(proxy) :
749                         g_strdup_printf("http://%s", proxy);
750
751                 puri = soup_uri_new(new_proxy);
752                 g_object_set(G_OBJECT(s), "proxy-uri", puri, NULL);
753                 soup_uri_free(puri);
754                 g_free(new_proxy);
755         }
756 }
757
758 void
759 sigchld(int unused) {
760         if(signal(SIGCHLD, sigchld) == SIG_ERR)
761                 die("Can't install SIGCHLD handler");
762         while(0 < waitpid(-1, NULL, WNOHANG));
763 }
764
765 void
766 source(Client *c, const Arg *arg) {
767         Arg a = { .b = FALSE };
768         gboolean s;
769
770         s = webkit_web_view_get_view_source_mode(c->view);
771         webkit_web_view_set_view_source_mode(c->view, !s);
772         reload(c, &a);
773 }
774
775 void
776 spawn(Client *c, const Arg *arg) {
777         if(fork() == 0) {
778                 if(dpy)
779                         close(ConnectionNumber(dpy));
780                 setsid();
781                 execvp(((char **)arg->v)[0], (char **)arg->v);
782                 fprintf(stderr, "surf: execvp %s", ((char **)arg->v)[0]);
783                 perror(" failed");
784                 exit(0);
785         }
786 }
787
788 void
789 stop(Client *c, const Arg *arg) {
790         if(c->download)
791                 webkit_download_cancel(c->download);
792         else
793                 webkit_web_view_stop_loading(c->view);
794         c->download = NULL;
795 }
796
797 void
798 titlechange(WebKitWebView *v, WebKitWebFrame *f, const char *t, Client *c) {
799         c->title = copystr(&c->title, t);
800         update(c);
801 }
802
803 void
804 update(Client *c) {
805         char *t;
806
807         if(c->progress != 100)
808                 t = g_strdup_printf("[%i%%] %s", c->progress, c->title);
809         else if(c->linkhover)
810                 t = g_strdup(c->linkhover);
811         else
812                 t = g_strdup(c->title);
813         drawindicator(c);
814         gtk_window_set_title(GTK_WINDOW(c->win), t);
815         g_free(t);
816 }
817
818 void
819 updatedownload(WebKitDownload *o, GParamSpec *pspec, Client *c) {
820         WebKitDownloadStatus status;
821
822         status = webkit_download_get_status(c->download);
823         if(status == WEBKIT_DOWNLOAD_STATUS_STARTED || status == WEBKIT_DOWNLOAD_STATUS_CREATED) {
824                 c->progress = (gint)(webkit_download_get_progress(c->download)*100);
825         }
826         else
827                 stop(c, NULL);
828         update(c);
829 }
830
831 void
832 updatewinid(Client *c) {
833         snprintf(winid, LENGTH(winid), "%u",
834                         (int)GDK_WINDOW_XID(GTK_WIDGET(c->win)->window));
835 }
836
837 void
838 usage(void) {
839         fputs("surf - simple browser\n", stderr);
840         die("usage: surf [-e Window] [-x] [-i] [-p] [-s] [uri]\n");
841 }
842
843 void
844 windowobjectcleared(GtkWidget *w, WebKitWebFrame *frame, JSContextRef js, JSObjectRef win, Client *c) {
845         JSStringRef jsscript;
846         char *script;
847         JSValueRef exception = NULL;
848         GError *error;
849         
850         if(g_file_get_contents(scriptfile, &script, NULL, &error)) {
851                 jsscript = JSStringCreateWithUTF8CString(script);
852                 JSEvaluateScript(js, jsscript, JSContextGetGlobalObject(js), NULL, 0, &exception);
853         }
854 }
855
856 void
857 zoom(Client *c, const Arg *arg) {
858         c->zoomed = TRUE;
859         if(arg->i < 0)          /* zoom out */
860                 webkit_web_view_zoom_out(c->view);
861         else if(arg->i > 0)     /* zoom in */
862                 webkit_web_view_zoom_in(c->view);
863         else {                  /* reset */
864                 c->zoomed = FALSE;
865                 webkit_web_view_set_zoom_level(c->view, 1.0);
866         }
867 }
868
869 int
870 main(int argc, char *argv[]) {
871         int i;
872         Arg arg;
873
874         progname = argv[0];
875         /* command line args */
876         for(i = 1, arg.v = NULL; i < argc && argv[i][0] == '-' &&
877                         argv[i][1] != '\0' && argv[i][2] == '\0'; i++) {
878                 if(!strcmp(argv[i], "--")) {
879                         i++;
880                         break;
881                 }
882                 switch(argv[i][1]) {
883                 case 'x':
884                         showxid = TRUE;
885                         break;
886                 case 'e':
887                         if(++i < argc)
888                                 embed = atoi(argv[i]);
889                         else
890                                 usage();
891                         break;
892                 case 'i':
893                         loadimage = 0;
894                         break;
895                 case 'p':
896                         plugin = 0;
897                         break;
898                 case 's':
899                         script = 0;
900                         break;
901                 case 'v':
902                         die("surf-"VERSION", © 2009 surf engineers, see LICENSE for details\n");
903                 }
904         }
905         if(i < argc)
906                 arg.v = argv[i];
907         setup();
908         newclient();
909         if(arg.v)
910                 loaduri(clients, &arg);
911         gtk_main();
912         cleanup();
913         return EXIT_SUCCESS;
914 }