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