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