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