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