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