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