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