fixing downloads based on Evan Gates' patch.
[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 SoupCookieJar *cookies;
60 static SoupSession *session;
61 static Client *clients = NULL;
62 static GdkNativeWindow embed = 0;
63 static gboolean showxid = FALSE;
64 static int ignorexprop = 0;
65 static char winid[64];
66 static char *progname;
67 static gboolean lockcookie = FALSE;
68
69 static char *buildpath(const char *path);
70 static void changecookie(SoupCookieJar *jar, SoupCookie *o, SoupCookie *n, gpointer p);
71 static void cleanup(void);
72 static void clipboard(Client *c, const Arg *arg);
73 static void context(WebKitWebView *v, GtkMenu *m, Client *c);
74 static char *copystr(char **str, const char *src);
75 static gboolean decidewindow(WebKitWebView *v, WebKitWebFrame *f, WebKitNetworkRequest *r, WebKitWebNavigationAction *n, WebKitWebPolicyDecision *p, Client *c);
76 static void destroyclient(Client *c);
77 static void destroywin(GtkWidget* w, Client *c);
78 static void die(char *str);
79 static void download(Client *c, const Arg *arg);
80 static void drawindicator(Client *c);
81 static gboolean exposeindicator(GtkWidget *w, GdkEventExpose *e, Client *c);
82 static char *geturi(Client *c);
83 static const char *getatom(Client *c, Atom a);
84 static gboolean initdownload(WebKitWebView *v, WebKitDownload *o, Client *c);
85 static void itemclick(GtkMenuItem *mi, Client *c);
86 static gboolean keypress(GtkWidget *w, GdkEventKey *ev, Client *c);
87 static void linkhover(WebKitWebView *v, const char* t, const char* l, Client *c);
88 static void loadcommit(WebKitWebView *v, WebKitWebFrame *f, Client *c);
89 static void loadstart(WebKitWebView *v, WebKitWebFrame *f, Client *c);
90 static void loaduri(Client *c, const Arg *arg);
91 static void navigate(Client *c, const Arg *arg);
92 static Client *newclient(void);
93 static void newwindow(Client *c, const Arg *arg);
94 static WebKitWebView *createwindow(WebKitWebView *v, WebKitWebFrame *f, Client *c);
95 static void pasteuri(GtkClipboard *clipboard, const char *text, gpointer d);
96 static GdkFilterReturn processx(GdkXEvent *xevent, GdkEvent *event, gpointer d);
97 static void print(Client *c, const Arg *arg);
98 static void progresschange(WebKitWebView *v, gint p, Client *c);
99 static void reloadcookies();
100 static void reload(Client *c, const Arg *arg);
101 static void resize(GtkWidget *w, GtkAllocation *a, Client *c);
102 static void sigchld(int unused);
103 static void setatom(Client *c, Atom a, const char *v);
104 static void setup(void);
105 static void spawn(Client *c, const Arg *arg);
106 static void scroll(Client *c, const Arg *arg);
107 static void find(Client *c, const Arg *arg);
108 static void source(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 usage(void);
112 static void update(Client *c);
113 static void updatedownload(WebKitDownload *o, GParamSpec *pspec, Client *c);
114 static void updatewinid(Client *c);
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 changecookie(SoupCookieJar *j, SoupCookie *oc, SoupCookie *c, gpointer p) {
144         SoupDate *e;
145         SoupCookieJar *jar;
146
147         if(lockcookie)
148                 return;
149         if(c && c->expires == NULL) {
150                 e = soup_date_new_from_time_t(time(NULL) + sessiontime);
151                 c = soup_cookie_copy(c);
152                 soup_cookie_set_expires(c, e);
153         }
154         
155         jar = soup_cookie_jar_text_new(cookiefile, FALSE);
156         if(c)
157                 soup_cookie_jar_add_cookie(jar, soup_cookie_copy(c));
158         else
159                 soup_cookie_jar_delete_cookie(jar, oc);
160         g_object_unref(jar);
161 }
162
163 void
164 cleanup(void) {
165         while(clients)
166                 destroyclient(clients);
167         g_free(cookiefile);
168         g_free(dldir);
169         g_free(scriptfile);
170         g_free(stylefile);
171 }
172
173 void
174 clipboard(Client *c, const Arg *arg) {
175         gboolean paste = *(gboolean *)arg;
176
177         if(paste)
178                 gtk_clipboard_request_text(gtk_clipboard_get(GDK_SELECTION_PRIMARY), pasteuri, c);
179         else
180                 gtk_clipboard_set_text(gtk_clipboard_get(GDK_SELECTION_PRIMARY), c->linkhover ? c->linkhover : geturi(c), -1);
181 }
182
183 void
184 context(WebKitWebView *v, GtkMenu *m, Client *c) {
185         int i;
186         GtkContainer *parent;
187
188         gtk_widget_hide_all(GTK_WIDGET(m));
189         gtk_widget_show(GTK_WIDGET(m));
190         for(i = 0; i < LENGTH(items); i++) {
191                 parent = GTK_CONTAINER(gtk_widget_get_parent(c->items[i]));
192                 if(parent)
193                         gtk_container_remove(parent, c->items[i]);
194                 gtk_menu_shell_append(GTK_MENU_SHELL(m), c->items[i]);
195                 gtk_widget_show(c->items[i]);
196         }
197 }
198
199 char *
200 copystr(char **str, const char *src) {
201         char *tmp;
202         tmp = g_strdup(src);
203
204         if(str && *str) {
205                 g_free(*str);
206                 *str = tmp;
207         }
208         return tmp;
209 }
210
211 void
212 destroyclient(Client *c) {
213         int i;
214         Client *p;
215
216         gtk_widget_destroy(GTK_WIDGET(c->view));
217         gtk_widget_destroy(c->scroll);
218         gtk_widget_destroy(c->vbox);
219         gtk_widget_destroy(c->indicator);
220         gtk_widget_destroy(c->win);
221         for(i = 0; i < LENGTH(items); i++)
222                 gtk_widget_destroy(c->items[i]);
223         free(c->items);
224
225         for(p = clients; p && p->next != c; p = p->next);
226         if(p)
227                 p->next = c->next;
228         else
229                 clients = c->next;
230         free(c);
231         if(clients == NULL)
232                 gtk_main_quit();
233 }
234
235 gboolean
236 mime_policy_cb(WebKitWebView *web_view, WebKitWebFrame *frame, WebKitNetworkRequest *request, gchar *mime_type,  WebKitWebPolicyDecision *policy_decision, gpointer user_data) {
237         if(webkit_web_view_can_show_mime_type(web_view, mime_type))
238                 webkit_web_policy_decision_use(policy_decision);
239         else
240                 webkit_web_policy_decision_download(policy_decision);
241         return TRUE;
242 }
243
244 gboolean
245 decidewindow(WebKitWebView *view, WebKitWebFrame *f, WebKitNetworkRequest *r, WebKitWebNavigationAction *n, WebKitWebPolicyDecision *p, Client *c) {
246         Arg arg;
247
248         if(webkit_web_navigation_action_get_reason(n) == WEBKIT_WEB_NAVIGATION_REASON_LINK_CLICKED) {
249                 webkit_web_policy_decision_ignore(p);
250                 arg.v = (void *)webkit_network_request_get_uri(r);
251                 newwindow(NULL, &arg);
252                 return TRUE;
253         }
254         return FALSE;
255 }
256
257 void
258 destroywin(GtkWidget* w, Client *c) {
259         destroyclient(c);
260 }
261
262 void
263 die(char *str) {
264         fputs(str, stderr);
265         exit(EXIT_FAILURE);
266 }
267
268 void
269 drawindicator(Client *c) {
270         gint width;
271         const char *uri;
272         GtkWidget *w;
273         GdkGC *gc;
274         GdkColor fg;
275
276         uri = getatom(c, uriprop);
277         w = c->indicator;
278         width = c->progress * w->allocation.width / 100;
279         gc = gdk_gc_new(w->window);
280         gdk_color_parse(strstr(uri, "https://") == uri ?
281                         progress_trust : progress, &fg);
282         gdk_gc_set_rgb_fg_color(gc, &fg);
283         gdk_draw_rectangle(w->window,
284                         w->style->bg_gc[GTK_WIDGET_STATE(w)],
285                         TRUE, 0, 0, w->allocation.width, w->allocation.height);
286         gdk_draw_rectangle(w->window, gc, TRUE, 0, 0, width,
287                         w->allocation.height);
288         g_object_unref(gc);
289 }
290
291 gboolean
292 exposeindicator(GtkWidget *w, GdkEventExpose *e, Client *c) {
293         drawindicator(c);
294         return TRUE;
295 }
296
297 void
298 download(Client *c, const Arg *arg) {
299         char *uri;
300         WebKitNetworkRequest *r;
301         WebKitDownload       *dl;
302
303         if(arg->v)
304                 uri = (char *)arg->v;
305         else
306                 uri = c->linkhover ? c->linkhover : geturi(c);
307         r = webkit_network_request_new(uri);
308         dl = webkit_download_new(r);
309         initdownload(c->view, dl, c);
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 gboolean
332 initdownload(WebKitWebView *view, WebKitDownload *o, Client *c) {
333         const char *filename;
334         char *uri, *html;
335
336         stop(c, NULL);
337         c->download = o;
338         filename = webkit_download_get_suggested_filename(o);
339         if(!strcmp("", filename))
340                 filename = "index.html";
341         uri = g_strconcat("file://", dldir, "/", filename, NULL);
342         webkit_download_set_destination_uri(c->download, uri);
343         c->progress = 0;
344         g_free(uri);
345         html = g_strdup_printf("Download <b>%s</b>...", filename);
346         webkit_web_view_load_html_string(c->view, html,
347                         webkit_download_get_uri(c->download));
348         g_signal_connect(c->download, "notify::progress", G_CALLBACK(updatedownload), c);
349         g_signal_connect(c->download, "notify::status", G_CALLBACK(updatedownload), c);
350         webkit_download_start(c->download);
351         
352         c->title = copystr(&c->title, filename);
353         update(c);
354         g_free(html);
355         return TRUE;
356 }
357
358 char *
359 geturi(Client *c) {
360         char *uri;
361
362         if(!(uri = (char *)webkit_web_view_get_uri(c->view)))
363                 uri = "about:blank";
364         return uri;
365 }
366
367 void
368 itemclick(GtkMenuItem *mi, Client *c) {
369         int i;
370         const char *label;
371
372         label = gtk_menu_item_get_label(mi);
373         for(i = 0; i < LENGTH(items); i++)
374                 if(!strcmp(items[i].label, label))
375                         items[i].func(c, &(items[i].arg));
376 }
377
378 gboolean
379 keypress(GtkWidget* w, GdkEventKey *ev, Client *c) {
380         guint i;
381         gboolean processed = FALSE;
382
383         updatewinid(c);
384         for(i = 0; i < LENGTH(keys); i++) {
385                 if(gdk_keyval_to_lower(ev->keyval) == keys[i].keyval
386                                 && CLEANMASK(ev->state) == keys[i].mod
387                                 && keys[i].func) {
388                         keys[i].func(c, &(keys[i].arg));
389                         processed = TRUE;
390                 }
391         }
392         return processed;
393 }
394
395 void
396 linkhover(WebKitWebView *v, const char* t, const char* l, Client *c) {
397         if(l)
398                 c->linkhover = copystr(&c->linkhover, l);
399         else if(c->linkhover) {
400                 free(c->linkhover);
401                 c->linkhover = NULL;
402         }
403         update(c);
404 }
405
406 void
407 loadcommit(WebKitWebView *view, WebKitWebFrame *f, Client *c) {
408         setatom(c, uriprop, geturi(c));
409 }
410
411 void
412 loadstart(WebKitWebView *view, WebKitWebFrame *f, Client *c) {
413         c->progress = 0;
414         update(c);
415         reloadcookies();
416 }
417
418 void
419 loaduri(Client *c, const Arg *arg) {
420         char *u;
421         const char *uri = (char *)arg->v;
422
423         u = g_strrstr(uri, "://") ? g_strdup(uri)
424                 : g_strdup_printf("http://%s", uri);
425         webkit_web_view_load_uri(c->view, u);
426         c->progress = 0;
427         c->title = copystr(&c->title, u);
428         g_free(u);
429         update(c);
430 }
431
432 void
433 navigate(Client *c, const Arg *arg) {
434         gint steps = *(gint *)arg;
435         webkit_web_view_go_back_or_forward(c->view, steps);
436 }
437
438 Client *
439 newclient(void) {
440         int i;
441         Client *c;
442         WebKitWebSettings *settings;
443         GdkGeometry hints = { 1, 1 };
444         char *uri;
445
446         if(!(c = calloc(1, sizeof(Client))))
447                 die("Cannot malloc!\n");
448         /* Window */
449         if(embed) {
450                 c->win = gtk_plug_new(embed);
451         }
452         else {
453                 c->win = gtk_window_new(GTK_WINDOW_TOPLEVEL);
454                 gtk_window_set_wmclass(GTK_WINDOW(c->win), "surf", "surf");
455         }
456         gtk_window_set_default_size(GTK_WINDOW(c->win), 800, 600);
457         g_signal_connect(G_OBJECT(c->win), "destroy", G_CALLBACK(destroywin), c);
458         g_signal_connect(G_OBJECT(c->win), "key-press-event", G_CALLBACK(keypress), c);
459         g_signal_connect(G_OBJECT(c->win), "size-allocate", G_CALLBACK(resize), c);
460
461         if(!(c->items = calloc(1, sizeof(GtkWidget *) * LENGTH(items))))
462                 die("Cannot malloc!\n");
463
464         /* contextmenu */
465         for(i = 0; i < LENGTH(items); i++) {
466                 c->items[i] = gtk_menu_item_new_with_label(items[i].label);
467                 g_signal_connect(G_OBJECT(c->items[i]), "activate",
468                                 G_CALLBACK(itemclick), c);
469         }
470
471         /* VBox */
472         c->vbox = gtk_vbox_new(FALSE, 0);
473
474         /* scrolled window */
475         c->scroll = gtk_scrolled_window_new(NULL, NULL);
476         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(c->scroll),
477                         GTK_POLICY_NEVER, GTK_POLICY_NEVER);
478
479         /* webview */
480         c->view = WEBKIT_WEB_VIEW(webkit_web_view_new());
481         g_signal_connect(G_OBJECT(c->view), "title-changed", G_CALLBACK(titlechange), c);
482         g_signal_connect(G_OBJECT(c->view), "load-progress-changed", G_CALLBACK(progresschange), c);
483         g_signal_connect(G_OBJECT(c->view), "load-committed", G_CALLBACK(loadcommit), c);
484         g_signal_connect(G_OBJECT(c->view), "load-started", G_CALLBACK(loadstart), c);
485         g_signal_connect(G_OBJECT(c->view), "hovering-over-link", G_CALLBACK(linkhover), c);
486         g_signal_connect(G_OBJECT(c->view), "create-web-view", G_CALLBACK(createwindow), c);
487         g_signal_connect(G_OBJECT(c->view), "new-window-policy-decision-requested", G_CALLBACK(decidewindow), c);
488         g_signal_connect(G_OBJECT(c->view), "download-requested", G_CALLBACK(initdownload), c);
489         g_signal_connect(G_OBJECT(c->view), "window-object-cleared", G_CALLBACK(windowobjectcleared), c);
490         g_signal_connect(G_OBJECT(c->view), "populate-popup", G_CALLBACK(context), c);
491
492         /* indicator */
493         c->indicator = gtk_drawing_area_new();
494         gtk_widget_set_size_request(c->indicator, 0, 2);
495         g_signal_connect (G_OBJECT (c->indicator), "expose_event",
496                         G_CALLBACK (exposeindicator), c);
497
498         /* Arranging */
499         gtk_container_add(GTK_CONTAINER(c->scroll), GTK_WIDGET(c->view));
500         gtk_container_add(GTK_CONTAINER(c->win), c->vbox);
501         gtk_container_add(GTK_CONTAINER(c->vbox), c->scroll);
502         gtk_container_add(GTK_CONTAINER(c->vbox), c->indicator);
503
504         /* Setup */
505         gtk_box_set_child_packing(GTK_BOX(c->vbox), c->indicator, FALSE, FALSE, 0, GTK_PACK_START);
506         gtk_box_set_child_packing(GTK_BOX(c->vbox), c->scroll, TRUE, TRUE, 0, GTK_PACK_START);
507         gtk_widget_grab_focus(GTK_WIDGET(c->view));
508         gtk_widget_show(c->vbox);
509         gtk_widget_show(c->indicator);
510         gtk_widget_show(c->scroll);
511         gtk_widget_show(GTK_WIDGET(c->view));
512         gtk_widget_show(c->win);
513         gtk_window_set_geometry_hints(GTK_WINDOW(c->win), NULL, &hints, GDK_HINT_MIN_SIZE);
514         gdk_window_set_events(GTK_WIDGET(c->win)->window, GDK_ALL_EVENTS_MASK);
515         gdk_window_add_filter(GTK_WIDGET(c->win)->window, processx, c);
516         webkit_web_view_set_full_content_zoom(c->view, TRUE);
517         settings = webkit_web_view_get_settings(c->view);
518         g_object_set(G_OBJECT(settings), "user-agent", useragent, NULL);
519         uri = g_strconcat("file://", stylefile, NULL);
520         g_object_set(G_OBJECT(settings), "user-stylesheet-uri", uri, NULL);
521         g_free(uri);
522         setatom(c, findprop, "");
523
524         c->download = NULL;
525         c->title = NULL;
526         c->next = clients;
527         clients = c;
528         if(showxid) {
529                 gdk_display_sync(gtk_widget_get_display(c->win));
530                 printf("%u\n", (guint)GDK_WINDOW_XID(GTK_WIDGET(c->win)->window));
531                 fflush(NULL);
532         }
533         return c;
534 }
535
536 void
537 newwindow(Client *c, const Arg *arg) {
538         guint i = 0;
539         const char *cmd[7], *uri;
540         const Arg a = { .v = (void *)cmd };
541         char tmp[64];
542
543         cmd[i++] = progname;
544         if(embed) {
545                 cmd[i++] = "-e";
546                 snprintf(tmp, LENGTH(tmp), "%u\n", (int)embed);
547                 cmd[i++] = tmp;
548         }
549         if(showxid) {
550                 cmd[i++] = "-x";
551         }
552         cmd[i++] = "--";
553         uri = arg->v ? (char *)arg->v : c->linkhover;
554         if(uri)
555                 cmd[i++] = uri;
556         cmd[i++] = NULL;
557         spawn(NULL, &a);
558 }
559
560 WebKitWebView *
561 createwindow(WebKitWebView  *v, WebKitWebFrame *f, Client *c) {
562         Client *n = newclient();
563         return n->view;
564 }
565
566 void
567 pasteuri(GtkClipboard *clipboard, const char *text, gpointer d) {
568         Arg arg = {.v = text };
569         if(text != NULL)
570                 loaduri((Client *) d, &arg);
571 }
572
573 GdkFilterReturn
574 processx(GdkXEvent *e, GdkEvent *event, gpointer d) {
575         Client *c = (Client *)d;
576         XPropertyEvent *ev;
577         Arg arg;
578
579         if(((XEvent *)e)->type == PropertyNotify) {
580                 ev = &((XEvent *)e)->xproperty;
581                 if(ignorexprop)
582                         ignorexprop--;
583                 else if(ev->state == PropertyNewValue) {
584                         if(ev->atom == uriprop) {
585                                 arg.v = getatom(c, uriprop);
586                                 loaduri(c, &arg);
587                         }
588                         else if(ev->atom == findprop) {
589                                 arg.b = TRUE;
590                                 find(c, &arg);
591                         }
592                         return GDK_FILTER_REMOVE;
593                 }
594         }
595         return GDK_FILTER_CONTINUE;
596 }
597
598 void
599 print(Client *c, const Arg *arg) {
600         webkit_web_frame_print(webkit_web_view_get_main_frame(c->view));
601 }
602
603 void
604 progresschange(WebKitWebView *v, gint p, Client *c) {
605         c->progress = p;
606         update(c);
607 }
608
609 void
610 reload(Client *c, const Arg *arg) {
611         gboolean nocache = *(gboolean *)arg;
612         if(nocache)
613                  webkit_web_view_reload_bypass_cache(c->view);
614         else
615                  webkit_web_view_reload(c->view);
616 }
617
618 void
619 reloadcookies() {
620         SoupCookieJar *jar;
621         GSList *l, *e;
622
623         lockcookie = TRUE;
624         for(l = e = soup_cookie_jar_all_cookies(cookies); e; e = e->next)
625                 soup_cookie_jar_delete_cookie(cookies, (SoupCookie *)e->data);
626         soup_cookies_free(l);
627         jar = soup_cookie_jar_text_new(cookiefile, TRUE);
628         for(l = e = soup_cookie_jar_all_cookies(jar); e; e = e->next)
629                 soup_cookie_jar_add_cookie(cookies, (SoupCookie *)e->data);
630         g_slist_free(l);
631         lockcookie = FALSE;
632         g_object_unref(jar);
633 }
634
635 void
636 scroll(Client *c, const Arg *arg) {
637         gdouble v;
638         GtkAdjustment *a;
639
640         a = gtk_scrolled_window_get_vadjustment(GTK_SCROLLED_WINDOW(c->scroll));
641         v = gtk_adjustment_get_value(a);
642         v += gtk_adjustment_get_step_increment(a) * arg->i;
643         v = MAX(v, 0.0);
644         v = MIN(v, gtk_adjustment_get_upper(a) - gtk_adjustment_get_page_size(a));
645         gtk_adjustment_set_value(a, v);
646 }
647
648 void
649 resize(GtkWidget *w, GtkAllocation *a, Client *c) {
650         double zoom;
651
652         if(c->zoomed)
653                 return;
654         zoom = webkit_web_view_get_zoom_level(c->view);
655         if(a->width * a->height < 300 * 400 && zoom != 0.2)
656                 webkit_web_view_set_zoom_level(c->view, 0.2);
657         else if(zoom != 1.0)
658                 webkit_web_view_set_zoom_level(c->view, 1.0);
659 }
660
661 void
662 sigchld(int unused) {
663         if(signal(SIGCHLD, sigchld) == SIG_ERR)
664                 die("Can't install SIGCHLD handler");
665         while(0 < waitpid(-1, NULL, WNOHANG));
666 }
667
668 void
669 setatom(Client *c, Atom a, const char *v) {
670         XSync(dpy, False);
671         ignorexprop++;
672         XChangeProperty(dpy, GDK_WINDOW_XID(GTK_WIDGET(c->win)->window), a,
673                         XA_STRING, 8, PropModeReplace, (unsigned char *)v,
674                         strlen(v) + 1);
675 }
676
677 void
678 setup(void) {
679         SoupSession *s;
680
681         /* clean up any zombies immediately */
682         sigchld(0);
683         gtk_init(NULL, NULL);
684         if (!g_thread_supported())
685                 g_thread_init(NULL);
686
687         dpy = GDK_DISPLAY();
688         session = webkit_get_default_session();
689         uriprop = XInternAtom(dpy, "_SURF_URI", False);
690         findprop = XInternAtom(dpy, "_SURF_FIND", False);
691
692         /* create dirs and files */
693         cookiefile = buildpath(cookiefile);
694         dldir = buildpath(dldir);
695         scriptfile = buildpath(scriptfile);
696         stylefile = buildpath(stylefile);
697
698         /* cookie persistance */
699         s = webkit_get_default_session();
700         cookies = soup_cookie_jar_new();
701         soup_session_add_feature(s, SOUP_SESSION_FEATURE(cookies));
702         g_signal_connect(cookies, "changed", G_CALLBACK(changecookie), NULL);
703         reloadcookies();
704 }
705
706 void
707 source(Client *c, const Arg *arg) {
708         Arg a = { .b = FALSE };
709         gboolean s;
710
711         s = webkit_web_view_get_view_source_mode(c->view);
712         webkit_web_view_set_view_source_mode(c->view, !s);
713         reload(c, &a);
714 }
715
716 void
717 find(Client *c, const Arg *arg) {
718         const char *s;
719
720         s = getatom(c, findprop);
721         gboolean forward = *(gboolean *)arg;
722         webkit_web_view_search_text(c->view, s, FALSE, forward, TRUE);
723 }
724
725 void
726 stop(Client *c, const Arg *arg) {
727         if(c->download)
728                 webkit_download_cancel(c->download);
729         else
730                 webkit_web_view_stop_loading(c->view);
731         c->download = NULL;
732 }
733
734 void
735 spawn(Client *c, const Arg *arg) {
736         if(fork() == 0) {
737                 if(dpy)
738                         close(ConnectionNumber(dpy));
739                 setsid();
740                 execvp(((char **)arg->v)[0], (char **)arg->v);
741                 fprintf(stderr, "surf: execvp %s", ((char **)arg->v)[0]);
742                 perror(" failed");
743                 exit(0);
744         }
745 }
746
747 void
748 titlechange(WebKitWebView *v, WebKitWebFrame *f, const char *t, Client *c) {
749         c->title = copystr(&c->title, t);
750         update(c);
751 }
752
753 void
754 usage(void) {
755         fputs("surf - simple browser\n", stderr);
756         die("usage: surf [-e Window] [-x] [uri]\n");
757 }
758
759 void
760 update(Client *c) {
761         char *t;
762
763         if(c->progress != 100)
764                 t = g_strdup_printf("%s [%i%%]", c->title, c->progress);
765         else if(c->linkhover)
766                 t = g_strdup(c->linkhover);
767         else
768                 t = g_strdup(c->title);
769         drawindicator(c);
770         gtk_window_set_title(GTK_WINDOW(c->win), t);
771         g_free(t);
772 }
773
774 void
775 updatedownload(WebKitDownload *o, GParamSpec *pspec, Client *c) {
776         WebKitDownloadStatus status;
777
778         status = webkit_download_get_status(c->download);
779         if(status == WEBKIT_DOWNLOAD_STATUS_STARTED || status == WEBKIT_DOWNLOAD_STATUS_CREATED) {
780                 c->progress = (gint)(webkit_download_get_progress(c->download)*100);
781         }
782         update(c);
783 }
784
785 void
786 updatewinid(Client *c) {
787         snprintf(winid, LENGTH(winid), "%u",
788                         (int)GDK_WINDOW_XID(GTK_WIDGET(c->win)->window));
789 }
790
791 void
792 windowobjectcleared(GtkWidget *w, WebKitWebFrame *frame, JSContextRef js, JSObjectRef win, Client *c) {
793         JSStringRef jsscript;
794         char *script;
795         JSValueRef exception = NULL;
796         GError *error;
797         
798         if(g_file_get_contents(scriptfile, &script, NULL, &error)) {
799                 jsscript = JSStringCreateWithUTF8CString(script);
800                 JSEvaluateScript(js, jsscript, JSContextGetGlobalObject(js), NULL, 0, &exception);
801         }
802 }
803
804 void
805 zoom(Client *c, const Arg *arg) {
806         c->zoomed = TRUE;
807         if(arg->i < 0)          /* zoom out */
808                 webkit_web_view_zoom_out(c->view);
809         else if(arg->i > 0)     /* zoom in */
810                 webkit_web_view_zoom_in(c->view);
811         else {                  /* reset */
812                 c->zoomed = FALSE;
813                 webkit_web_view_set_zoom_level(c->view, 1.0);
814         }
815 }
816
817 int main(int argc, char *argv[]) {
818         int i;
819         Arg arg;
820
821         progname = argv[0];
822         /* command line args */
823         for(i = 1, arg.v = NULL; i < argc && argv[i][0] == '-'; i++) {
824                 if(!strcmp(argv[i], "-x"))
825                         showxid = TRUE;
826                 else if(!strcmp(argv[i], "-e")) {
827                         if(++i < argc)
828                                 embed = atoi(argv[i]);
829                         else
830                                 usage();
831                 }
832                 else if(!strcmp(argv[i], "--")) {
833                         i++;
834                         break;
835                 }
836                 else if(!strcmp(argv[i], "-v"))
837                         die("surf-"VERSION", © 2009 surf engineers, see LICENSE for details\n");
838                 else
839                         usage();
840         }
841         if(i < argc)
842                 arg.v = argv[i];
843         setup();
844         newclient();
845         if(arg.v) {
846                 loaduri(clients, &arg);
847         }
848         gtk_main();
849         cleanup();
850         return EXIT_SUCCESS;
851 }