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