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