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