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