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