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