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