adding environment variables for proxy and useragent
[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 WebKitWebView *createwindow(WebKitWebView *v, WebKitWebFrame *f, Client *c);
76 static gboolean decidedownload(WebKitWebView *v, WebKitWebFrame *f, WebKitNetworkRequest *r, gchar *m,  WebKitWebPolicyDecision *p, Client *c);
77 static gboolean decidewindow(WebKitWebView *v, WebKitWebFrame *f, WebKitNetworkRequest *r, WebKitWebNavigationAction *n, WebKitWebPolicyDecision *p, Client *c);
78 static void destroyclient(Client *c);
79 static void destroywin(GtkWidget* w, Client *c);
80 static void die(char *str);
81 static void download(Client *c, const Arg *arg);
82 static void drawindicator(Client *c);
83 static gboolean exposeindicator(GtkWidget *w, GdkEventExpose *e, Client *c);
84 static void find(Client *c, const Arg *arg);
85 static const char *getatom(Client *c, Atom a);
86 static char *geturi(Client *c);
87 static gboolean initdownload(WebKitWebView *v, WebKitDownload *o, Client *c);
88 static void itemclick(GtkMenuItem *mi, Client *c);
89 static gboolean keypress(GtkWidget *w, GdkEventKey *ev, Client *c);
90 static void linkhover(WebKitWebView *v, const char* t, const char* l, Client *c);
91 static void loadcommit(WebKitWebView *v, WebKitWebFrame *f, Client *c);
92 static void loadstart(WebKitWebView *v, WebKitWebFrame *f, Client *c);
93 static void loaduri(Client *c, const Arg *arg);
94 static void navigate(Client *c, const Arg *arg);
95 static Client *newclient(void);
96 static void newwindow(Client *c, const Arg *arg);
97 static void pasteuri(GtkClipboard *clipboard, const char *text, gpointer d);
98 static void print(Client *c, const Arg *arg);
99 static GdkFilterReturn processx(GdkXEvent *xevent, GdkEvent *event, gpointer d);
100 static void progresschange(WebKitWebView *v, gint p, Client *c);
101 static void reload(Client *c, const Arg *arg);
102 static void reloadcookies();
103 static void resize(GtkWidget *w, GtkAllocation *a, Client *c);
104 static void scroll(Client *c, const Arg *arg);
105 static void setatom(Client *c, Atom a, const char *v);
106 static void setup(void);
107 static void sigchld(int unused);
108 static void source(Client *c, const Arg *arg);
109 static void spawn(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 update(Client *c);
113 static void updatedownload(WebKitDownload *o, GParamSpec *pspec, Client *c);
114 static void updatewinid(Client *c);
115 static void usage(void);
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 WebKitWebView *
213 createwindow(WebKitWebView  *v, WebKitWebFrame *f, Client *c) {
214         Client *n = newclient();
215         return n->view;
216 }
217
218 gboolean
219 decidedownload(WebKitWebView *v, WebKitWebFrame *f, WebKitNetworkRequest *r, gchar *m,  WebKitWebPolicyDecision *p, Client *c) {
220         if(!webkit_web_view_can_show_mime_type(v, m)) {
221                 webkit_web_policy_decision_download(p);
222                 return TRUE;
223         }
224         return FALSE;
225 }
226
227 gboolean
228 decidewindow(WebKitWebView *view, WebKitWebFrame *f, WebKitNetworkRequest *r, WebKitWebNavigationAction *n, WebKitWebPolicyDecision *p, Client *c) {
229         Arg arg;
230
231         if(webkit_web_navigation_action_get_reason(n) == WEBKIT_WEB_NAVIGATION_REASON_LINK_CLICKED) {
232                 webkit_web_policy_decision_ignore(p);
233                 arg.v = (void *)webkit_network_request_get_uri(r);
234                 newwindow(NULL, &arg);
235                 return TRUE;
236         }
237         return FALSE;
238 }
239
240 void
241 destroyclient(Client *c) {
242         int i;
243         Client *p;
244
245         gtk_widget_destroy(c->indicator);
246         gtk_widget_destroy(GTK_WIDGET(c->view));
247         gtk_widget_destroy(c->scroll);
248         gtk_widget_destroy(c->vbox);
249         gtk_widget_destroy(c->win);
250         for(i = 0; i < LENGTH(items); i++)
251                 gtk_widget_destroy(c->items[i]);
252         free(c->items);
253
254         for(p = clients; p && p->next != c; p = p->next);
255         if(p)
256                 p->next = c->next;
257         else
258                 clients = c->next;
259         free(c);
260         if(clients == NULL)
261                 gtk_main_quit();
262 }
263
264 void
265 destroywin(GtkWidget* w, Client *c) {
266         destroyclient(c);
267 }
268
269 void
270 die(char *str) {
271         fputs(str, stderr);
272         exit(EXIT_FAILURE);
273 }
274
275 void
276 download(Client *c, const Arg *arg) {
277         char *uri;
278         WebKitNetworkRequest *r;
279         WebKitDownload       *dl;
280
281         if(arg->v)
282                 uri = (char *)arg->v;
283         else
284                 uri = c->linkhover ? c->linkhover : geturi(c);
285         r = webkit_network_request_new(uri);
286         dl = webkit_download_new(r);
287         initdownload(c->view, dl, c);
288 }
289
290 void
291 drawindicator(Client *c) {
292         gint width;
293         const char *uri;
294         GtkWidget *w;
295         GdkGC *gc;
296         GdkColor fg;
297
298         uri = getatom(c, uriprop);
299         w = c->indicator;
300         width = c->progress * w->allocation.width / 100;
301         gc = gdk_gc_new(w->window);
302         gdk_color_parse(strstr(uri, "https://") == uri ?
303                         progress_trust : progress, &fg);
304         gdk_gc_set_rgb_fg_color(gc, &fg);
305         gdk_draw_rectangle(w->window,
306                         w->style->bg_gc[GTK_WIDGET_STATE(w)],
307                         TRUE, 0, 0, w->allocation.width, w->allocation.height);
308         gdk_draw_rectangle(w->window, gc, TRUE, 0, 0, width,
309                         w->allocation.height);
310         g_object_unref(gc);
311 }
312
313 gboolean
314 exposeindicator(GtkWidget *w, GdkEventExpose *e, Client *c) {
315         drawindicator(c);
316         return TRUE;
317 }
318
319 void
320 find(Client *c, const Arg *arg) {
321         const char *s;
322
323         s = getatom(c, findprop);
324         gboolean forward = *(gboolean *)arg;
325         webkit_web_view_search_text(c->view, s, FALSE, forward, TRUE);
326 }
327
328 const char *
329 getatom(Client *c, Atom a) {
330         static char buf[BUFSIZ];
331         Atom adummy;
332         int idummy;
333         unsigned long ldummy;
334         unsigned char *p = NULL;
335
336         XGetWindowProperty(dpy, GDK_WINDOW_XID(GTK_WIDGET(c->win)->window),
337                         a, 0L, BUFSIZ, False, XA_STRING,
338                         &adummy, &idummy, &ldummy, &ldummy, &p);
339         if(p)
340                 strncpy(buf, (char *)p, LENGTH(buf)-1);
341         else
342                 buf[0] = '\0';
343         XFree(p);
344         return buf;
345 }
346
347 char *
348 geturi(Client *c) {
349         char *uri;
350
351         if(!(uri = (char *)webkit_web_view_get_uri(c->view)))
352                 uri = "about:blank";
353         return uri;
354 }
355
356 gboolean
357 initdownload(WebKitWebView *view, WebKitDownload *o, Client *c) {
358         const char *filename;
359         char *uri, *html;
360
361         stop(c, NULL);
362         c->download = o;
363         filename = webkit_download_get_suggested_filename(o);
364         if(!strcmp("", filename))
365                 filename = "index.html";
366         uri = g_strconcat("file://", dldir, "/", filename, NULL);
367         webkit_download_set_destination_uri(c->download, uri);
368         c->progress = 0;
369         g_free(uri);
370         html = g_strdup_printf("Download <b>%s</b>...", filename);
371         webkit_web_view_load_html_string(c->view, html,
372                         webkit_download_get_uri(c->download));
373         g_signal_connect(c->download, "notify::progress", G_CALLBACK(updatedownload), c);
374         g_signal_connect(c->download, "notify::status", G_CALLBACK(updatedownload), c);
375         webkit_download_start(c->download);
376         
377         c->title = copystr(&c->title, filename);
378         update(c);
379         g_free(html);
380         return TRUE;
381 }
382
383 void
384 itemclick(GtkMenuItem *mi, Client *c) {
385         int i;
386         const char *label;
387
388         label = gtk_menu_item_get_label(mi);
389         for(i = 0; i < LENGTH(items); i++)
390                 if(!strcmp(items[i].label, label))
391                         items[i].func(c, &(items[i].arg));
392 }
393
394 gboolean
395 keypress(GtkWidget* w, GdkEventKey *ev, Client *c) {
396         guint i;
397         gboolean processed = FALSE;
398
399         updatewinid(c);
400         for(i = 0; i < LENGTH(keys); i++) {
401                 if(gdk_keyval_to_lower(ev->keyval) == keys[i].keyval
402                                 && CLEANMASK(ev->state) == keys[i].mod
403                                 && keys[i].func) {
404                         keys[i].func(c, &(keys[i].arg));
405                         processed = TRUE;
406                 }
407         }
408         return processed;
409 }
410
411 void
412 linkhover(WebKitWebView *v, const char* t, const char* l, Client *c) {
413         if(l)
414                 c->linkhover = copystr(&c->linkhover, l);
415         else if(c->linkhover) {
416                 free(c->linkhover);
417                 c->linkhover = NULL;
418         }
419         update(c);
420 }
421
422 void
423 loadcommit(WebKitWebView *view, WebKitWebFrame *f, Client *c) {
424         setatom(c, uriprop, geturi(c));
425 }
426
427 void
428 loadstart(WebKitWebView *view, WebKitWebFrame *f, Client *c) {
429         c->progress = 0;
430         update(c);
431         reloadcookies();
432 }
433
434 void
435 loaduri(Client *c, const Arg *arg) {
436         char *u;
437         const char *uri = (char *)arg->v;
438
439         u = g_strrstr(uri, "://") ? g_strdup(uri)
440                 : g_strdup_printf("http://%s", uri);
441         webkit_web_view_load_uri(c->view, u);
442         c->progress = 0;
443         c->title = copystr(&c->title, u);
444         g_free(u);
445         update(c);
446 }
447
448 void
449 navigate(Client *c, const Arg *arg) {
450         gint steps = *(gint *)arg;
451         webkit_web_view_go_back_or_forward(c->view, steps);
452 }
453
454 Client *
455 newclient(void) {
456         int i;
457         Client *c;
458         WebKitWebSettings *settings;
459         GdkGeometry hints = { 1, 1 };
460         char *uri, *ua;
461
462         if(!(c = calloc(1, sizeof(Client))))
463                 die("Cannot malloc!\n");
464         /* Window */
465         if(embed) {
466                 c->win = gtk_plug_new(embed);
467         }
468         else {
469                 c->win = gtk_window_new(GTK_WINDOW_TOPLEVEL);
470                 gtk_window_set_wmclass(GTK_WINDOW(c->win), "surf", "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), "load-progress-changed", G_CALLBACK(progresschange), c);
499         g_signal_connect(G_OBJECT(c->view), "load-committed", G_CALLBACK(loadcommit), c);
500         g_signal_connect(G_OBJECT(c->view), "load-started", G_CALLBACK(loadstart), c);
501         g_signal_connect(G_OBJECT(c->view), "hovering-over-link", G_CALLBACK(linkhover), c);
502         g_signal_connect(G_OBJECT(c->view), "create-web-view", G_CALLBACK(createwindow), c);
503         g_signal_connect(G_OBJECT(c->view), "new-window-policy-decision-requested", G_CALLBACK(decidewindow), c);
504         g_signal_connect(G_OBJECT(c->view), "mime-type-policy-decision-requested", G_CALLBACK(decidedownload), c);
505         g_signal_connect(G_OBJECT(c->view), "download-requested", G_CALLBACK(initdownload), c);
506         g_signal_connect(G_OBJECT(c->view), "window-object-cleared", G_CALLBACK(windowobjectcleared), c);
507         g_signal_connect(G_OBJECT(c->view), "populate-popup", G_CALLBACK(context), 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
543         c->download = NULL;
544         c->title = NULL;
545         c->next = clients;
546         clients = c;
547         if(showxid) {
548                 gdk_display_sync(gtk_widget_get_display(c->win));
549                 printf("%u\n", (guint)GDK_WINDOW_XID(GTK_WIDGET(c->win)->window));
550                 fflush(NULL);
551         }
552         return c;
553 }
554
555 void
556 newwindow(Client *c, const Arg *arg) {
557         guint i = 0;
558         const char *cmd[7], *uri;
559         const Arg a = { .v = (void *)cmd };
560         char tmp[64];
561
562         cmd[i++] = progname;
563         if(embed) {
564                 cmd[i++] = "-e";
565                 snprintf(tmp, LENGTH(tmp), "%u\n", (int)embed);
566                 cmd[i++] = tmp;
567         }
568         if(showxid) {
569                 cmd[i++] = "-x";
570         }
571         cmd[i++] = "--";
572         uri = arg->v ? (char *)arg->v : c->linkhover;
573         if(uri)
574                 cmd[i++] = uri;
575         cmd[i++] = NULL;
576         spawn(NULL, &a);
577 }
578
579 void
580 pasteuri(GtkClipboard *clipboard, const char *text, gpointer d) {
581         Arg arg = {.v = text };
582         if(text != NULL)
583                 loaduri((Client *) d, &arg);
584 }
585
586 void
587 print(Client *c, const Arg *arg) {
588         webkit_web_frame_print(webkit_web_view_get_main_frame(c->view));
589 }
590
591 GdkFilterReturn
592 processx(GdkXEvent *e, GdkEvent *event, gpointer d) {
593         Client *c = (Client *)d;
594         XPropertyEvent *ev;
595         Arg arg;
596
597         if(((XEvent *)e)->type == PropertyNotify) {
598                 ev = &((XEvent *)e)->xproperty;
599                 if(ignorexprop)
600                         ignorexprop--;
601                 else if(ev->state == PropertyNewValue) {
602                         if(ev->atom == uriprop) {
603                                 arg.v = getatom(c, uriprop);
604                                 loaduri(c, &arg);
605                         }
606                         else if(ev->atom == findprop) {
607                                 arg.b = TRUE;
608                                 find(c, &arg);
609                         }
610                         return GDK_FILTER_REMOVE;
611                 }
612         }
613         return GDK_FILTER_CONTINUE;
614 }
615
616 void
617 progresschange(WebKitWebView *v, gint p, Client *c) {
618         c->progress = p;
619         update(c);
620 }
621
622 void
623 reload(Client *c, const Arg *arg) {
624         gboolean nocache = *(gboolean *)arg;
625         if(nocache)
626                  webkit_web_view_reload_bypass_cache(c->view);
627         else
628                  webkit_web_view_reload(c->view);
629 }
630
631 void
632 reloadcookies() {
633         SoupCookieJar *jar;
634         GSList *l, *e;
635
636         lockcookie = TRUE;
637         for(l = e = soup_cookie_jar_all_cookies(cookies); e; e = e->next)
638                 soup_cookie_jar_delete_cookie(cookies, (SoupCookie *)e->data);
639         soup_cookies_free(l);
640         jar = soup_cookie_jar_text_new(cookiefile, TRUE);
641         for(l = e = soup_cookie_jar_all_cookies(jar); e; e = e->next)
642                 soup_cookie_jar_add_cookie(cookies, (SoupCookie *)e->data);
643         g_slist_free(l);
644         lockcookie = FALSE;
645         g_object_unref(jar);
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 scroll(Client *c, const Arg *arg) {
663         gdouble v;
664         GtkAdjustment *a;
665
666         a = gtk_scrolled_window_get_vadjustment(GTK_SCROLLED_WINDOW(c->scroll));
667         v = gtk_adjustment_get_value(a);
668         v += gtk_adjustment_get_step_increment(a) * arg->i;
669         v = MAX(v, 0.0);
670         v = MIN(v, gtk_adjustment_get_upper(a) - gtk_adjustment_get_page_size(a));
671         gtk_adjustment_set_value(a, v);
672 }
673
674 void
675 setatom(Client *c, Atom a, const char *v) {
676         XSync(dpy, False);
677         ignorexprop++;
678         XChangeProperty(dpy, GDK_WINDOW_XID(GTK_WIDGET(c->win)->window), a,
679                         XA_STRING, 8, PropModeReplace, (unsigned char *)v,
680                         strlen(v) + 1);
681 }
682
683 void
684 setup(void) {
685         SoupSession *s;
686         char *proxy;
687         SoupURI *puri;
688
689         /* clean up any zombies immediately */
690         sigchld(0);
691         gtk_init(NULL, NULL);
692         if (!g_thread_supported())
693                 g_thread_init(NULL);
694
695         dpy = GDK_DISPLAY();
696         session = webkit_get_default_session();
697         uriprop = XInternAtom(dpy, "_SURF_URI", False);
698         findprop = XInternAtom(dpy, "_SURF_FIND", False);
699
700         /* create dirs and files */
701         cookiefile = buildpath(cookiefile);
702         dldir = buildpath(dldir);
703         scriptfile = buildpath(scriptfile);
704         stylefile = buildpath(stylefile);
705
706         /* cookie persistance */
707         s = webkit_get_default_session();
708         cookies = soup_cookie_jar_new();
709         soup_session_add_feature(s, SOUP_SESSION_FEATURE(cookies));
710         g_signal_connect(cookies, "changed", G_CALLBACK(changecookie), NULL);
711         if((proxy = getenv("http_proxy")) && strcmp(proxy, "")) {
712                 puri = soup_uri_new(proxy);
713                 g_object_set(G_OBJECT(s), "proxy-uri", puri, NULL);
714                 soup_uri_free(puri);
715         }
716         reloadcookies();
717 }
718
719 void
720 sigchld(int unused) {
721         if(signal(SIGCHLD, sigchld) == SIG_ERR)
722                 die("Can't install SIGCHLD handler");
723         while(0 < waitpid(-1, NULL, WNOHANG));
724 }
725
726 void
727 source(Client *c, const Arg *arg) {
728         Arg a = { .b = FALSE };
729         gboolean s;
730
731         s = webkit_web_view_get_view_source_mode(c->view);
732         webkit_web_view_set_view_source_mode(c->view, !s);
733         reload(c, &a);
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 stop(Client *c, const Arg *arg) {
751         if(c->download)
752                 webkit_download_cancel(c->download);
753         else
754                 webkit_web_view_stop_loading(c->view);
755         c->download = NULL;
756 }
757
758 void
759 titlechange(WebKitWebView *v, WebKitWebFrame *f, const char *t, Client *c) {
760         c->title = copystr(&c->title, t);
761         update(c);
762 }
763
764 void
765 update(Client *c) {
766         char *t;
767
768         if(c->progress != 100)
769                 t = g_strdup_printf("[%i%%] %s", c->progress, c->title);
770         else if(c->linkhover)
771                 t = g_strdup(c->linkhover);
772         else
773                 t = g_strdup(c->title);
774         drawindicator(c);
775         gtk_window_set_title(GTK_WINDOW(c->win), t);
776         g_free(t);
777 }
778
779 void
780 updatedownload(WebKitDownload *o, GParamSpec *pspec, Client *c) {
781         WebKitDownloadStatus status;
782
783         status = webkit_download_get_status(c->download);
784         if(status == WEBKIT_DOWNLOAD_STATUS_STARTED || status == WEBKIT_DOWNLOAD_STATUS_CREATED) {
785                 c->progress = (gint)(webkit_download_get_progress(c->download)*100);
786         }
787         update(c);
788 }
789
790 void
791 updatewinid(Client *c) {
792         snprintf(winid, LENGTH(winid), "%u",
793                         (int)GDK_WINDOW_XID(GTK_WIDGET(c->win)->window));
794 }
795
796 void
797 usage(void) {
798         fputs("surf - simple browser\n", stderr);
799         die("usage: surf [-e Window] [-x] [uri]\n");
800 }
801
802 void
803 windowobjectcleared(GtkWidget *w, WebKitWebFrame *frame, JSContextRef js, JSObjectRef win, Client *c) {
804         JSStringRef jsscript;
805         char *script;
806         JSValueRef exception = NULL;
807         GError *error;
808         
809         if(g_file_get_contents(scriptfile, &script, NULL, &error)) {
810                 jsscript = JSStringCreateWithUTF8CString(script);
811                 JSEvaluateScript(js, jsscript, JSContextGetGlobalObject(js), NULL, 0, &exception);
812         }
813 }
814
815 void
816 zoom(Client *c, const Arg *arg) {
817         c->zoomed = TRUE;
818         if(arg->i < 0)          /* zoom out */
819                 webkit_web_view_zoom_out(c->view);
820         else if(arg->i > 0)     /* zoom in */
821                 webkit_web_view_zoom_in(c->view);
822         else {                  /* reset */
823                 c->zoomed = FALSE;
824                 webkit_web_view_set_zoom_level(c->view, 1.0);
825         }
826 }
827
828 int main(int argc, char *argv[]) {
829         int i;
830         Arg arg;
831
832         progname = argv[0];
833         /* command line args */
834         for(i = 1, arg.v = NULL; i < argc && argv[i][0] == '-'; i++) {
835                 if(!strcmp(argv[i], "-x"))
836                         showxid = TRUE;
837                 else if(!strcmp(argv[i], "-e")) {
838                         if(++i < argc)
839                                 embed = atoi(argv[i]);
840                         else
841                                 usage();
842                 }
843                 else if(!strcmp(argv[i], "--")) {
844                         i++;
845                         break;
846                 }
847                 else if(!strcmp(argv[i], "-v"))
848                         die("surf-"VERSION", © 2009 surf engineers, see LICENSE for details\n");
849                 else
850                         usage();
851         }
852         if(i < argc)
853                 arg.v = argv[i];
854         setup();
855         newclient();
856         if(arg.v)
857                 loaduri(clients, &arg);
858         gtk_main();
859         cleanup();
860         return EXIT_SUCCESS;
861 }