implementing cookie persistance with multiple processes.
[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                 g_signal_connect(G_OBJECT(c->items[i]), "activate",
191                                 G_CALLBACK(itemclick), c);
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 loadfinished(WebKitWebView *v, WebKitWebFrame *f, Client *c) {
403         reloadcookie();
404 }
405
406 void
407 loadstart(WebKitWebView *view, WebKitWebFrame *f, Client *c) {
408         reloadcookie();
409         c->progress = 0;
410         update(c);
411 }
412
413 void
414 loaduri(Client *c, const Arg *arg) {
415         char *u;
416         const char *uri = (char *)arg->v;
417
418         if(!uri)
419                 uri = autouri(c);
420         if(!uri)
421                 return;
422         u = g_strrstr(uri, "://") ? g_strdup(uri)
423                 : g_strdup_printf("http://%s", uri);
424         webkit_web_view_load_uri(c->view, u);
425         c->progress = 0;
426         c->title = copystr(&c->title, u);
427         g_free(u);
428         update(c);
429 }
430
431 void
432 navigate(Client *c, const Arg *arg) {
433         gint steps = *(gint *)arg;
434         webkit_web_view_go_back_or_forward(c->view, steps);
435 }
436
437 Client *
438 newclient(void) {
439         int i;
440         Client *c;
441         WebKitWebSettings *settings;
442         char *uri;
443
444         if(!(c = calloc(1, sizeof(Client))))
445                 die("Cannot malloc!\n");
446         /* Window */
447         if(embed) {
448                 c->win = gtk_plug_new(embed);
449         }
450         else {
451                 c->win = gtk_window_new(GTK_WINDOW_TOPLEVEL);
452                 gtk_window_set_wmclass(GTK_WINDOW(c->win), "surf", "surf");
453         }
454         gtk_window_set_default_size(GTK_WINDOW(c->win), 800, 600);
455         g_signal_connect(G_OBJECT(c->win), "destroy", G_CALLBACK(destroywin), c);
456         g_signal_connect(G_OBJECT(c->win), "key-press-event", G_CALLBACK(keypress), c);
457
458         if(!(c->items = calloc(1, sizeof(GtkWidget *) * LENGTH(items))))
459                 die("Cannot malloc!\n");
460
461         /* contextmenu */
462         for(i = 0; i < LENGTH(items); i++)
463                 c->items[i] = gtk_menu_item_new_with_label(items[i].label);
464
465
466         /* VBox */
467         c->vbox = gtk_vbox_new(FALSE, 0);
468
469         /* scrolled window */
470         c->scroll = gtk_scrolled_window_new(NULL, NULL);
471         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(c->scroll),
472                         GTK_POLICY_NEVER, GTK_POLICY_NEVER);
473
474         /* webview */
475         c->view = WEBKIT_WEB_VIEW(webkit_web_view_new());
476         g_signal_connect(G_OBJECT(c->view), "title-changed", G_CALLBACK(titlechange), c);
477         g_signal_connect(G_OBJECT(c->view), "load-progress-changed", G_CALLBACK(progresschange), c);
478         g_signal_connect(G_OBJECT(c->view), "load-finished", G_CALLBACK(loadfinished), c);
479         g_signal_connect(G_OBJECT(c->view), "load-committed", G_CALLBACK(loadcommit), c);
480         g_signal_connect(G_OBJECT(c->view), "load-started", G_CALLBACK(loadstart), c);
481         g_signal_connect(G_OBJECT(c->view), "hovering-over-link", G_CALLBACK(linkhover), c);
482         g_signal_connect(G_OBJECT(c->view), "create-web-view", G_CALLBACK(createwindow), c);
483         g_signal_connect(G_OBJECT(c->view), "new-window-policy-decision-requested", G_CALLBACK(decidewindow), c);
484         g_signal_connect(G_OBJECT(c->view), "download-requested", G_CALLBACK(initdownload), c);
485         g_signal_connect(G_OBJECT(c->view), "window-object-cleared", G_CALLBACK(windowobjectcleared), c);
486         g_signal_connect(G_OBJECT(c->view), "focus-in-event", G_CALLBACK(focusview), c);
487         g_signal_connect(G_OBJECT(c->view), "populate-popup", G_CALLBACK(context), c);
488
489         /* uribar */
490         c->uribar = gtk_entry_new();
491         gtk_entry_set_has_frame(GTK_ENTRY(c->uribar), FALSE);
492
493         /* searchbar */
494         c->searchbar = gtk_entry_new();
495         gtk_entry_set_has_frame(GTK_ENTRY(c->searchbar), FALSE);
496
497         /* indicator */
498         c->indicator = gtk_drawing_area_new();
499         gtk_widget_set_size_request(c->indicator, 0, 2);
500         g_signal_connect (G_OBJECT (c->indicator), "expose_event",
501                         G_CALLBACK (exposeindicator), c);
502
503         /* Arranging */
504         gtk_container_add(GTK_CONTAINER(c->scroll), GTK_WIDGET(c->view));
505         gtk_container_add(GTK_CONTAINER(c->win), c->vbox);
506         gtk_container_add(GTK_CONTAINER(c->vbox), c->scroll);
507         gtk_container_add(GTK_CONTAINER(c->vbox), c->searchbar);
508         gtk_container_add(GTK_CONTAINER(c->vbox), c->uribar);
509         gtk_container_add(GTK_CONTAINER(c->vbox), c->indicator);
510
511         /* Setup */
512         gtk_box_set_child_packing(GTK_BOX(c->vbox), c->uribar, FALSE, FALSE, 0, GTK_PACK_START);
513         gtk_box_set_child_packing(GTK_BOX(c->vbox), c->searchbar, FALSE, FALSE, 0, GTK_PACK_START);
514         gtk_box_set_child_packing(GTK_BOX(c->vbox), c->indicator, FALSE, FALSE, 0, GTK_PACK_START);
515         gtk_box_set_child_packing(GTK_BOX(c->vbox), c->scroll, TRUE, TRUE, 0, GTK_PACK_START);
516         gtk_widget_grab_focus(GTK_WIDGET(c->view));
517         gtk_widget_hide_all(c->searchbar);
518         gtk_widget_hide_all(c->uribar);
519         gtk_widget_show(c->vbox);
520         gtk_widget_show(c->indicator);
521         gtk_widget_show(c->scroll);
522         gtk_widget_show(GTK_WIDGET(c->view));
523         gtk_widget_show(c->win);
524         gdk_window_set_events(GTK_WIDGET(c->win)->window, GDK_ALL_EVENTS_MASK);
525         gdk_window_add_filter(GTK_WIDGET(c->win)->window, processx, c);
526         webkit_web_view_set_full_content_zoom(c->view, TRUE);
527         settings = webkit_web_view_get_settings(c->view);
528         g_object_set(G_OBJECT(settings), "user-agent", useragent, NULL);
529         uri = g_strconcat("file://", stylefile, NULL);
530         g_object_set(G_OBJECT(settings), "user-stylesheet-uri", uri, NULL);
531         g_free(uri);
532
533         c->download = NULL;
534         c->title = NULL;
535         c->next = clients;
536         clients = c;
537         if(showxid) {
538                 gdk_display_sync(gtk_widget_get_display(c->win));
539                 printf("%u\n", (guint)GDK_WINDOW_XID(GTK_WIDGET(c->win)->window));
540                 fflush(NULL);
541         }
542         return c;
543 }
544
545 void
546 newwindow(Client *c, const Arg *arg) {
547         guint i = 0;
548         const char *cmd[7], *uri;
549         const Arg a = { .v = (void *)cmd };
550         char tmp[64];
551
552         cmd[i++] = progname;
553         if(embed) {
554                 cmd[i++] = "-e";
555                 snprintf(tmp, LENGTH(tmp), "%u\n", (int)embed);
556                 cmd[i++] = tmp;
557         }
558         if(showxid) {
559                 cmd[i++] = "-x";
560         }
561         cmd[i++] = "--";
562         uri = arg->v ? (char *)arg->v : autouri(c);
563         if(uri)
564                 cmd[i++] = uri;
565         cmd[i++] = NULL;
566         spawn(NULL, &a);
567 }
568
569 WebKitWebView *
570 createwindow(WebKitWebView  *v, WebKitWebFrame *f, Client *c) {
571         Client *n = newclient();
572         return n->view;
573 }
574
575 void
576 pasteuri(GtkClipboard *clipboard, const char *text, gpointer d) {
577         Arg arg = {.v = text };
578         if(text != NULL)
579                 loaduri((Client *) d, &arg);
580 }
581
582 GdkFilterReturn
583 processx(GdkXEvent *e, GdkEvent *event, gpointer d) {
584         Client *c = (Client *)d;
585         XPropertyEvent *ev;
586         Atom adummy;
587         gint idummy;
588         unsigned long ldummy;
589         unsigned char *buf = NULL;
590         Arg arg;
591
592         if(((XEvent *)e)->type == PropertyNotify) {
593                 ev = &((XEvent *)e)->xproperty;
594                 if(ev->atom == uriprop && ev->state == PropertyNewValue) {
595                         if(ignore_once)
596                                ignore_once = FALSE;
597                         else {
598                                 XGetWindowProperty(dpy, ev->window, uriprop, 0L, BUFSIZ, False, XA_STRING,
599                                         &adummy, &idummy, &ldummy, &ldummy, &buf);
600                                 arg.v = buf;
601                                 loaduri(c, &arg);
602                                 XFree(buf);
603                         }
604                         return GDK_FILTER_REMOVE;
605                 }
606         }
607         return GDK_FILTER_CONTINUE;
608 }
609
610 void
611 print(Client *c, const Arg *arg) {
612         webkit_web_frame_print(webkit_web_view_get_main_frame(c->view));
613 }
614
615 void
616 progresschange(WebKitWebView *v, gint p, Client *c) {
617         c->progress = p;
618         update(c);
619 }
620
621 void
622 reload(Client *c, const Arg *arg) {
623         gboolean nocache = *(gboolean *)arg;
624         if(nocache)
625                  webkit_web_view_reload_bypass_cache(c->view);
626         else
627                  webkit_web_view_reload(c->view);
628 }
629
630 void
631 reloadcookie(void) {
632         SoupSession *s;
633
634         /* This forces the cookie to be written to hdd */
635         s = webkit_get_default_session();
636         soup_session_remove_feature(s, SOUP_SESSION_FEATURE(cookiejar));
637         soup_session_add_feature(s, SOUP_SESSION_FEATURE(cookiejar));
638
639
640 void
641 scroll(Client *c, const Arg *arg) {
642         gdouble v;
643         GtkAdjustment *a;
644
645         a = gtk_scrolled_window_get_vadjustment(GTK_SCROLLED_WINDOW(c->scroll));
646         v = gtk_adjustment_get_value(a);
647         v += gtk_adjustment_get_step_increment(a) * arg->i;
648         v = MAX(v, 0.0);
649         v = MIN(v, gtk_adjustment_get_upper(a) - gtk_adjustment_get_page_size(a));
650         gtk_adjustment_set_value(a, v);
651 }
652
653 void
654 sigchld(int unused) {
655         if(signal(SIGCHLD, sigchld) == SIG_ERR)
656                 die("Can't install SIGCHLD handler");
657         while(0 < waitpid(-1, NULL, WNOHANG));
658 }
659
660 void
661 setup(void) {
662         SoupSession *s;
663
664         /* clean up any zombies immediately */
665         sigchld(0);
666         gtk_init(NULL, NULL);
667         if (!g_thread_supported())
668                 g_thread_init(NULL);
669
670         dpy = GDK_DISPLAY();
671         session = webkit_get_default_session();
672         uriprop = XInternAtom(dpy, "_SURF_uri", False);
673
674         /* create dirs and files */
675         cookiefile = buildpath(cookiefile);
676         dldir = buildpath(dldir);
677         scriptfile = buildpath(scriptfile);
678         stylefile = buildpath(stylefile);
679
680         /* cookie persistance */
681         s = webkit_get_default_session();
682         cookiejar = soup_cookie_jar_text_new(cookiefile, FALSE);
683         soup_session_add_feature(s, SOUP_SESSION_FEATURE(cookiejar));
684 }
685
686 void
687 showsearch(Client *c, const Arg *arg) {
688         hideuri(c, NULL);
689         gtk_widget_show(c->searchbar);
690         gtk_widget_grab_focus(c->searchbar);
691 }
692
693 void
694 source(Client *c, const Arg *arg) {
695         Arg a = { .b = FALSE };
696         gboolean s;
697
698         s = webkit_web_view_get_view_source_mode(c->view);
699         webkit_web_view_set_view_source_mode(c->view, !s);
700         reload(c, &a);
701 }
702
703 void
704 searchtext(Client *c, const Arg *arg) {
705         const char *text;
706         gboolean forward = *(gboolean *)arg;
707         text = gtk_entry_get_text(GTK_ENTRY(c->searchbar));
708         webkit_web_view_search_text(c->view, text, FALSE, forward, TRUE);
709         webkit_web_view_mark_text_matches(c->view, text, FALSE, 0);
710 }
711
712 void
713 showuri(Client *c, const Arg *arg) {
714         char *uri;
715
716         hidesearch(c, NULL);
717         uri = geturi(c);
718         gtk_entry_set_text(GTK_ENTRY(c->uribar), uri);
719         gtk_widget_show(c->uribar);
720         gtk_widget_grab_focus(c->uribar);
721 }
722
723 void
724 stop(Client *c, const Arg *arg) {
725         if(c->download)
726                 webkit_download_cancel(c->download);
727         else
728                 webkit_web_view_stop_loading(c->view);
729         c->download = NULL;
730 }
731
732 void
733 spawn(Client *c, const Arg *arg) {
734         if(fork() == 0) {
735                 if(dpy)
736                         close(ConnectionNumber(dpy));
737                 setsid();
738                 execvp(((char **)arg->v)[0], (char **)arg->v);
739                 fprintf(stderr, "tabbed: execvp %s", ((char **)arg->v)[0]);
740                 perror(" failed");
741                 exit(0);
742         }
743 }
744
745 void
746 titlechange(WebKitWebView *v, WebKitWebFrame *f, const char *t, Client *c) {
747         c->title = copystr(&c->title, t);
748         update(c);
749 }
750
751 gboolean
752 focusview(GtkWidget *w, GdkEventFocus *e, Client *c) {
753         hidesearch(c, NULL);
754         hideuri(c, NULL);
755         return FALSE;
756 }
757
758 void
759 usage(void) {
760         fputs("surf - simple browser\n", stderr);
761         die("usage: surf [-e Window] [-x] [uri]\n");
762 }
763
764 void
765 update(Client *c) {
766         char *t;
767
768         if(c->progress != 100)
769                 t = g_strdup_printf("%s [%i%%]", c->title, c->progress);
770         else if(c->linkhover)
771                 t = g_strdup(c->linkhover);
772         else
773                 t = g_strdup(c->title);
774         drawindicator(c);
775         gtk_window_set_title(GTK_WINDOW(c->win), t);
776         g_free(t);
777
778 }
779
780 void
781 updatewinid(Client *c) {
782         snprintf(winid, LENGTH(winid), "%u",
783                         (int)GDK_WINDOW_XID(GTK_WIDGET(c->win)->window));
784 }
785
786 void
787 windowobjectcleared(GtkWidget *w, WebKitWebFrame *frame, JSContextRef js, JSObjectRef win, Client *c) {
788         JSStringRef jsscript;
789         char *script;
790         JSValueRef exception = NULL;
791         GError *error;
792         
793         if(g_file_get_contents(scriptfile, &script, NULL, &error)) {
794                 jsscript = JSStringCreateWithUTF8CString(script);
795                 JSEvaluateScript(js, jsscript, JSContextGetGlobalObject(js), NULL, 0, &exception);
796         }
797 }
798
799 void
800 zoom(Client *c, const Arg *arg) {
801         if(arg->i < 0)          /* zoom out */
802                 webkit_web_view_zoom_out(c->view);
803         else if(arg->i > 0)     /* zoom in */
804                 webkit_web_view_zoom_in(c->view);
805         else                    /* reset */
806                 webkit_web_view_set_zoom_level(c->view, 1.0);
807 }
808
809 int main(int argc, char *argv[]) {
810         int i;
811         Arg arg;
812
813         progname = argv[0];
814         /* command line args */
815         for(i = 1, arg.v = NULL; i < argc && argv[i][0] == '-'; i++) {
816                 if(!strcmp(argv[i], "-x"))
817                         showxid = TRUE;
818                 else if(!strcmp(argv[i], "-e")) {
819                         if(++i < argc)
820                                 embed = atoi(argv[i]);
821                         else
822                                 usage();
823                 }
824                 else if(!strcmp(argv[i], "--")) {
825                         i++;
826                         break;
827                 }
828                 else if(!strcmp(argv[i], "-v"))
829                         die("surf-"VERSION", © 2009 surf engineers, see LICENSE for details\n");
830                 else
831                         usage();
832         }
833         if(i < argc)
834                 arg.v = argv[i];
835         setup();
836         newclient();
837         if(arg.v) {
838                 loaduri(clients, &arg);
839         }
840         gtk_main();
841         cleanup();
842         return EXIT_SUCCESS;
843 }