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