Adding Lorenzo Bollas hints patch.
[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         GdkGeometry hints = { 1, 1 };
428         char *uri;
429
430         if(!(c = calloc(1, sizeof(Client))))
431                 die("Cannot malloc!\n");
432         /* Window */
433         if(embed) {
434                 c->win = gtk_plug_new(embed);
435         }
436         else {
437                 c->win = gtk_window_new(GTK_WINDOW_TOPLEVEL);
438                 gtk_window_set_wmclass(GTK_WINDOW(c->win), "surf", "surf");
439         }
440         gtk_window_set_default_size(GTK_WINDOW(c->win), 800, 600);
441         g_signal_connect(G_OBJECT(c->win), "destroy", G_CALLBACK(destroywin), c);
442         g_signal_connect(G_OBJECT(c->win), "key-press-event", G_CALLBACK(keypress), c);
443         g_signal_connect(G_OBJECT(c->win), "size-allocate", G_CALLBACK(resize), c);
444
445         if(!(c->items = calloc(1, sizeof(GtkWidget *) * LENGTH(items))))
446                 die("Cannot malloc!\n");
447
448         /* contextmenu */
449         for(i = 0; i < LENGTH(items); i++) {
450                 c->items[i] = gtk_menu_item_new_with_label(items[i].label);
451                 g_signal_connect(G_OBJECT(c->items[i]), "activate",
452                                 G_CALLBACK(itemclick), c);
453         }
454
455         /* VBox */
456         c->vbox = gtk_vbox_new(FALSE, 0);
457
458         /* scrolled window */
459         c->scroll = gtk_scrolled_window_new(NULL, NULL);
460         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(c->scroll),
461                         GTK_POLICY_NEVER, GTK_POLICY_NEVER);
462
463         /* webview */
464         c->view = WEBKIT_WEB_VIEW(webkit_web_view_new());
465         g_signal_connect(G_OBJECT(c->view), "title-changed", G_CALLBACK(titlechange), c);
466         g_signal_connect(G_OBJECT(c->view), "load-progress-changed", G_CALLBACK(progresschange), c);
467         g_signal_connect(G_OBJECT(c->view), "load-committed", G_CALLBACK(loadcommit), c);
468         g_signal_connect(G_OBJECT(c->view), "load-started", G_CALLBACK(loadstart), c);
469         g_signal_connect(G_OBJECT(c->view), "hovering-over-link", G_CALLBACK(linkhover), c);
470         g_signal_connect(G_OBJECT(c->view), "create-web-view", G_CALLBACK(createwindow), c);
471         g_signal_connect(G_OBJECT(c->view), "new-window-policy-decision-requested", G_CALLBACK(decidewindow), c);
472         g_signal_connect(G_OBJECT(c->view), "download-requested", G_CALLBACK(initdownload), c);
473         g_signal_connect(G_OBJECT(c->view), "window-object-cleared", G_CALLBACK(windowobjectcleared), c);
474         g_signal_connect(G_OBJECT(c->view), "populate-popup", G_CALLBACK(context), c);
475
476         /* indicator */
477         c->indicator = gtk_drawing_area_new();
478         gtk_widget_set_size_request(c->indicator, 0, 2);
479         g_signal_connect (G_OBJECT (c->indicator), "expose_event",
480                         G_CALLBACK (exposeindicator), c);
481
482         /* Arranging */
483         gtk_container_add(GTK_CONTAINER(c->scroll), GTK_WIDGET(c->view));
484         gtk_container_add(GTK_CONTAINER(c->win), c->vbox);
485         gtk_container_add(GTK_CONTAINER(c->vbox), c->scroll);
486         gtk_container_add(GTK_CONTAINER(c->vbox), c->indicator);
487
488         /* Setup */
489         gtk_box_set_child_packing(GTK_BOX(c->vbox), c->indicator, FALSE, FALSE, 0, GTK_PACK_START);
490         gtk_box_set_child_packing(GTK_BOX(c->vbox), c->scroll, TRUE, TRUE, 0, GTK_PACK_START);
491         gtk_widget_grab_focus(GTK_WIDGET(c->view));
492         gtk_widget_show(c->vbox);
493         gtk_widget_show(c->indicator);
494         gtk_widget_show(c->scroll);
495         gtk_widget_show(GTK_WIDGET(c->view));
496         gtk_widget_show(c->win);
497         gtk_window_set_geometry_hints(GTK_WINDOW(c->win), NULL, &hints, GDK_HINT_MIN_SIZE);
498         gdk_window_set_events(GTK_WIDGET(c->win)->window, GDK_ALL_EVENTS_MASK);
499         gdk_window_add_filter(GTK_WIDGET(c->win)->window, processx, c);
500         webkit_web_view_set_full_content_zoom(c->view, TRUE);
501         settings = webkit_web_view_get_settings(c->view);
502         g_object_set(G_OBJECT(settings), "user-agent", useragent, NULL);
503         uri = g_strconcat("file://", stylefile, NULL);
504         g_object_set(G_OBJECT(settings), "user-stylesheet-uri", uri, NULL);
505         g_free(uri);
506         setatom(c, findprop, "");
507
508         c->download = NULL;
509         c->title = NULL;
510         c->next = clients;
511         clients = c;
512         if(showxid) {
513                 gdk_display_sync(gtk_widget_get_display(c->win));
514                 printf("%u\n", (guint)GDK_WINDOW_XID(GTK_WIDGET(c->win)->window));
515                 fflush(NULL);
516         }
517         return c;
518 }
519
520 void
521 newwindow(Client *c, const Arg *arg) {
522         guint i = 0;
523         const char *cmd[7], *uri;
524         const Arg a = { .v = (void *)cmd };
525         char tmp[64];
526
527         cmd[i++] = progname;
528         if(embed) {
529                 cmd[i++] = "-e";
530                 snprintf(tmp, LENGTH(tmp), "%u\n", (int)embed);
531                 cmd[i++] = tmp;
532         }
533         if(showxid) {
534                 cmd[i++] = "-x";
535         }
536         cmd[i++] = "--";
537         uri = arg->v ? (char *)arg->v : c->linkhover;
538         if(uri)
539                 cmd[i++] = uri;
540         cmd[i++] = NULL;
541         spawn(NULL, &a);
542 }
543
544 WebKitWebView *
545 createwindow(WebKitWebView  *v, WebKitWebFrame *f, Client *c) {
546         Client *n = newclient();
547         return n->view;
548 }
549
550 void
551 pasteuri(GtkClipboard *clipboard, const char *text, gpointer d) {
552         Arg arg = {.v = text };
553         if(text != NULL)
554                 loaduri((Client *) d, &arg);
555 }
556
557 GdkFilterReturn
558 processx(GdkXEvent *e, GdkEvent *event, gpointer d) {
559         Client *c = (Client *)d;
560         XPropertyEvent *ev;
561         Arg arg;
562
563         if(((XEvent *)e)->type == PropertyNotify) {
564                 ev = &((XEvent *)e)->xproperty;
565                 if(ignorexprop)
566                         ignorexprop--;
567                 else if(ev->state == PropertyNewValue) {
568                         if(ev->atom == uriprop) {
569                                 arg.v = getatom(c, uriprop);
570                                 loaduri(c, &arg);
571                         }
572                         else if(ev->atom == findprop) {
573                                 arg.b = TRUE;
574                                 find(c, &arg);
575                         }
576                         return GDK_FILTER_REMOVE;
577                 }
578         }
579         return GDK_FILTER_CONTINUE;
580 }
581
582 void
583 print(Client *c, const Arg *arg) {
584         webkit_web_frame_print(webkit_web_view_get_main_frame(c->view));
585 }
586
587 void
588 progresschange(WebKitWebView *v, gint p, Client *c) {
589         c->progress = p;
590         update(c);
591 }
592
593 void
594 reload(Client *c, const Arg *arg) {
595         gboolean nocache = *(gboolean *)arg;
596         if(nocache)
597                  webkit_web_view_reload_bypass_cache(c->view);
598         else
599                  webkit_web_view_reload(c->view);
600 }
601
602 void
603 reloadcookies() {
604         SoupCookieJar *jar;
605         GSList *l, *e;
606
607         lockcookie = TRUE;
608         for(l = e = soup_cookie_jar_all_cookies(cookies); e; e = e->next)
609                 soup_cookie_jar_delete_cookie(cookies, (SoupCookie *)e->data);
610         soup_cookies_free(l);
611         jar = soup_cookie_jar_text_new(cookiefile, TRUE);
612         for(l = e = soup_cookie_jar_all_cookies(jar); e; e = e->next)
613                 soup_cookie_jar_add_cookie(cookies, (SoupCookie *)e->data);
614         g_slist_free(l);
615         lockcookie = FALSE;
616         g_object_unref(jar);
617 }
618
619 void
620 scroll(Client *c, const Arg *arg) {
621         gdouble v;
622         GtkAdjustment *a;
623
624         a = gtk_scrolled_window_get_vadjustment(GTK_SCROLLED_WINDOW(c->scroll));
625         v = gtk_adjustment_get_value(a);
626         v += gtk_adjustment_get_step_increment(a) * arg->i;
627         v = MAX(v, 0.0);
628         v = MIN(v, gtk_adjustment_get_upper(a) - gtk_adjustment_get_page_size(a));
629         gtk_adjustment_set_value(a, v);
630 }
631
632 void
633 resize(GtkWidget *w, GtkAllocation *a, Client *c) {
634         double zoom;
635
636         if(c->zoomed)
637                 return;
638         zoom = webkit_web_view_get_zoom_level(c->view);
639         if(a->width * a->height < 300 * 400 && zoom != 0.2)
640                 webkit_web_view_set_zoom_level(c->view, 0.2);
641         else if(zoom != 1.0)
642                 webkit_web_view_set_zoom_level(c->view, 1.0);
643 }
644
645 void
646 sigchld(int unused) {
647         if(signal(SIGCHLD, sigchld) == SIG_ERR)
648                 die("Can't install SIGCHLD handler");
649         while(0 < waitpid(-1, NULL, WNOHANG));
650 }
651
652 void
653 setatom(Client *c, Atom a, const char *v) {
654         XSync(dpy, False);
655         ignorexprop++;
656         XChangeProperty(dpy, GDK_WINDOW_XID(GTK_WIDGET(c->win)->window), a,
657                         XA_STRING, 8, PropModeReplace, (unsigned char *)v,
658                         strlen(v) + 1);
659 }
660
661 void
662 setup(void) {
663         SoupSession *s;
664
665         /* clean up any zombies immediately */
666         sigchld(0);
667         gtk_init(NULL, NULL);
668         if (!g_thread_supported())
669                 g_thread_init(NULL);
670
671         dpy = GDK_DISPLAY();
672         session = webkit_get_default_session();
673         uriprop = XInternAtom(dpy, "_SURF_URI", False);
674         findprop = XInternAtom(dpy, "_SURF_FIND", False);
675
676         /* create dirs and files */
677         cookiefile = buildpath(cookiefile);
678         dldir = buildpath(dldir);
679         scriptfile = buildpath(scriptfile);
680         stylefile = buildpath(stylefile);
681
682         /* cookie persistance */
683         s = webkit_get_default_session();
684         cookies = soup_cookie_jar_new();
685         soup_session_add_feature(s, SOUP_SESSION_FEATURE(cookies));
686         g_signal_connect(cookies, "changed", G_CALLBACK(changecookie), NULL);
687         reloadcookies();
688 }
689
690 void
691 source(Client *c, const Arg *arg) {
692         Arg a = { .b = FALSE };
693         gboolean s;
694
695         s = webkit_web_view_get_view_source_mode(c->view);
696         webkit_web_view_set_view_source_mode(c->view, !s);
697         reload(c, &a);
698 }
699
700 void
701 find(Client *c, const Arg *arg) {
702         const char *s;
703
704         s = getatom(c, findprop);
705         gboolean forward = *(gboolean *)arg;
706         webkit_web_view_search_text(c->view, s, FALSE, forward, TRUE);
707 }
708
709 void
710 stop(Client *c, const Arg *arg) {
711         if(c->download)
712                 webkit_download_cancel(c->download);
713         else
714                 webkit_web_view_stop_loading(c->view);
715         c->download = NULL;
716 }
717
718 void
719 spawn(Client *c, const Arg *arg) {
720         if(fork() == 0) {
721                 if(dpy)
722                         close(ConnectionNumber(dpy));
723                 setsid();
724                 execvp(((char **)arg->v)[0], (char **)arg->v);
725                 fprintf(stderr, "surf: execvp %s", ((char **)arg->v)[0]);
726                 perror(" failed");
727                 exit(0);
728         }
729 }
730
731 void
732 titlechange(WebKitWebView *v, WebKitWebFrame *f, const char *t, Client *c) {
733         c->title = copystr(&c->title, t);
734         update(c);
735 }
736
737 void
738 usage(void) {
739         fputs("surf - simple browser\n", stderr);
740         die("usage: surf [-e Window] [-x] [uri]\n");
741 }
742
743 void
744 update(Client *c) {
745         char *t;
746
747         if(c->progress != 100)
748                 t = g_strdup_printf("%s [%i%%]", c->title, c->progress);
749         else if(c->linkhover)
750                 t = g_strdup(c->linkhover);
751         else
752                 t = g_strdup(c->title);
753         drawindicator(c);
754         gtk_window_set_title(GTK_WINDOW(c->win), t);
755         g_free(t);
756
757 }
758
759 void
760 updatewinid(Client *c) {
761         snprintf(winid, LENGTH(winid), "%u",
762                         (int)GDK_WINDOW_XID(GTK_WIDGET(c->win)->window));
763 }
764
765 void
766 windowobjectcleared(GtkWidget *w, WebKitWebFrame *frame, JSContextRef js, JSObjectRef win, Client *c) {
767         JSStringRef jsscript;
768         char *script;
769         JSValueRef exception = NULL;
770         GError *error;
771         
772         if(g_file_get_contents(scriptfile, &script, NULL, &error)) {
773                 jsscript = JSStringCreateWithUTF8CString(script);
774                 JSEvaluateScript(js, jsscript, JSContextGetGlobalObject(js), NULL, 0, &exception);
775         }
776 }
777
778 void
779 zoom(Client *c, const Arg *arg) {
780         c->zoomed = TRUE;
781         if(arg->i < 0)          /* zoom out */
782                 webkit_web_view_zoom_out(c->view);
783         else if(arg->i > 0)     /* zoom in */
784                 webkit_web_view_zoom_in(c->view);
785         else {                  /* reset */
786                 c->zoomed = FALSE;
787                 webkit_web_view_set_zoom_level(c->view, 1.0);
788         }
789 }
790
791 int main(int argc, char *argv[]) {
792         int i;
793         Arg arg;
794
795         progname = argv[0];
796         /* command line args */
797         for(i = 1, arg.v = NULL; i < argc && argv[i][0] == '-'; i++) {
798                 if(!strcmp(argv[i], "-x"))
799                         showxid = TRUE;
800                 else if(!strcmp(argv[i], "-e")) {
801                         if(++i < argc)
802                                 embed = atoi(argv[i]);
803                         else
804                                 usage();
805                 }
806                 else if(!strcmp(argv[i], "--")) {
807                         i++;
808                         break;
809                 }
810                 else if(!strcmp(argv[i], "-v"))
811                         die("surf-"VERSION", © 2009 surf engineers, see LICENSE for details\n");
812                 else
813                         usage();
814         }
815         if(i < argc)
816                 arg.v = argv[i];
817         setup();
818         newclient();
819         if(arg.v) {
820                 loaduri(clients, &arg);
821         }
822         gtk_main();
823         cleanup();
824         return EXIT_SUCCESS;
825 }