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