adding cmd-switches for turning of images/plugins/scripts
[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         }
580         if(!plugin) {
581                 cmd[i++] = "-p";
582         }
583         if(!loadimage) {
584                 cmd[i++] = "-l";
585         }
586         if(showxid) {
587                 cmd[i++] = "-x";
588         }
589         cmd[i++] = "--";
590         uri = arg->v ? (char *)arg->v : c->linkhover;
591         if(uri)
592                 cmd[i++] = uri;
593         cmd[i++] = NULL;
594         spawn(NULL, &a);
595 }
596
597 void
598 pasteuri(GtkClipboard *clipboard, const char *text, gpointer d) {
599         Arg arg = {.v = text };
600         if(text != NULL)
601                 loaduri((Client *) d, &arg);
602 }
603
604 void
605 print(Client *c, const Arg *arg) {
606         webkit_web_frame_print(webkit_web_view_get_main_frame(c->view));
607 }
608
609 GdkFilterReturn
610 processx(GdkXEvent *e, GdkEvent *event, gpointer d) {
611         Client *c = (Client *)d;
612         XPropertyEvent *ev;
613         Arg arg;
614
615         if(((XEvent *)e)->type == PropertyNotify) {
616                 ev = &((XEvent *)e)->xproperty;
617                 if(ignorexprop)
618                         ignorexprop--;
619                 else if(ev->state == PropertyNewValue) {
620                         if(ev->atom == uriprop) {
621                                 arg.v = getatom(c, uriprop);
622                                 loaduri(c, &arg);
623                         }
624                         else if(ev->atom == findprop) {
625                                 arg.b = TRUE;
626                                 find(c, &arg);
627                         }
628                         return GDK_FILTER_REMOVE;
629                 }
630         }
631         return GDK_FILTER_CONTINUE;
632 }
633
634 void
635 progresschange(WebKitWebView *view, GParamSpec *pspec, Client *c) {
636         c->progress = webkit_web_view_get_progress(c->view) * 100;
637         update(c);
638 }
639
640 void
641 reload(Client *c, const Arg *arg) {
642         gboolean nocache = *(gboolean *)arg;
643         if(nocache)
644                  webkit_web_view_reload_bypass_cache(c->view);
645         else
646                  webkit_web_view_reload(c->view);
647 }
648
649 void
650 resize(GtkWidget *w, GtkAllocation *a, Client *c) {
651         double zoom;
652
653         if(c->zoomed)
654                 return;
655         zoom = webkit_web_view_get_zoom_level(c->view);
656         if(a->width * a->height < 300 * 400 && zoom != 0.2)
657                 webkit_web_view_set_zoom_level(c->view, 0.2);
658         else if(zoom != 1.0)
659                 webkit_web_view_set_zoom_level(c->view, 1.0);
660 }
661
662 void
663 scroll(Client *c, const Arg *arg) {
664         gdouble v;
665         GtkAdjustment *a;
666
667         a = gtk_scrolled_window_get_vadjustment(GTK_SCROLLED_WINDOW(c->scroll));
668         v = gtk_adjustment_get_value(a);
669         v += gtk_adjustment_get_step_increment(a) * arg->i;
670         v = MAX(v, 0.0);
671         v = MIN(v, gtk_adjustment_get_upper(a) - gtk_adjustment_get_page_size(a));
672         gtk_adjustment_set_value(a, v);
673 }
674
675 void
676 setatom(Client *c, Atom a, const char *v) {
677         XSync(dpy, False);
678         ignorexprop++;
679         XChangeProperty(dpy, GDK_WINDOW_XID(GTK_WIDGET(c->win)->window), a,
680                         XA_STRING, 8, PropModeReplace, (unsigned char *)v,
681                         strlen(v) + 1);
682 }
683
684 void
685 setup(void) {
686         char *proxy;
687         char *new_proxy;
688         SoupURI *puri;
689         SoupSession *s;
690
691         /* clean up any zombies immediately */
692         sigchld(0);
693         gtk_init(NULL, NULL);
694         if (!g_thread_supported())
695                 g_thread_init(NULL);
696
697         dpy = GDK_DISPLAY();
698         s = webkit_get_default_session();
699         uriprop = XInternAtom(dpy, "_SURF_URI", False);
700         findprop = XInternAtom(dpy, "_SURF_FIND", False);
701
702         /* dirs and files */
703         cookiefile = buildpath(cookiefile);
704         dldir = buildpath(dldir);
705         scriptfile = buildpath(scriptfile);
706         stylefile = buildpath(stylefile);
707
708         /* request handler */
709         s = webkit_get_default_session();
710         soup_session_remove_feature_by_type(s, soup_cookie_get_type());
711         soup_session_remove_feature_by_type(s, soup_cookie_jar_get_type());
712         g_signal_connect_after(G_OBJECT(s), "request-started", G_CALLBACK(newrequest), NULL);
713
714
715         /* proxy */
716         if((proxy = getenv("http_proxy")) && strcmp(proxy, "")) {
717                 new_proxy = g_strrstr(proxy, "http://") ? g_strdup(proxy) :
718                         g_strdup_printf("http://%s", proxy);
719
720                 puri = soup_uri_new(new_proxy);
721                 g_object_set(G_OBJECT(s), "proxy-uri", puri, NULL);
722                 soup_uri_free(puri);
723                 g_free(new_proxy);
724         }
725 }
726
727 void
728 sigchld(int unused) {
729         if(signal(SIGCHLD, sigchld) == SIG_ERR)
730                 die("Can't install SIGCHLD handler");
731         while(0 < waitpid(-1, NULL, WNOHANG));
732 }
733
734 void
735 source(Client *c, const Arg *arg) {
736         Arg a = { .b = FALSE };
737         gboolean s;
738
739         s = webkit_web_view_get_view_source_mode(c->view);
740         webkit_web_view_set_view_source_mode(c->view, !s);
741         reload(c, &a);
742 }
743
744 void
745 spawn(Client *c, const Arg *arg) {
746         if(fork() == 0) {
747                 if(dpy)
748                         close(ConnectionNumber(dpy));
749                 setsid();
750                 execvp(((char **)arg->v)[0], (char **)arg->v);
751                 fprintf(stderr, "surf: execvp %s", ((char **)arg->v)[0]);
752                 perror(" failed");
753                 exit(0);
754         }
755 }
756
757 void
758 stop(Client *c, const Arg *arg) {
759         if(c->download)
760                 webkit_download_cancel(c->download);
761         else
762                 webkit_web_view_stop_loading(c->view);
763         c->download = NULL;
764 }
765
766 void
767 titlechange(WebKitWebView *v, WebKitWebFrame *f, const char *t, Client *c) {
768         c->title = copystr(&c->title, t);
769         update(c);
770 }
771
772 void
773 update(Client *c) {
774         char *t;
775
776         if(c->progress != 100)
777                 t = g_strdup_printf("[%i%%] %s", c->progress, c->title);
778         else if(c->linkhover)
779                 t = g_strdup(c->linkhover);
780         else
781                 t = g_strdup(c->title);
782         drawindicator(c);
783         gtk_window_set_title(GTK_WINDOW(c->win), t);
784         g_free(t);
785 }
786
787 void
788 updatedownload(WebKitDownload *o, GParamSpec *pspec, Client *c) {
789         WebKitDownloadStatus status;
790
791         status = webkit_download_get_status(c->download);
792         if(status == WEBKIT_DOWNLOAD_STATUS_STARTED || status == WEBKIT_DOWNLOAD_STATUS_CREATED) {
793                 c->progress = (gint)(webkit_download_get_progress(c->download)*100);
794         }
795         update(c);
796 }
797
798 void
799 updatewinid(Client *c) {
800         snprintf(winid, LENGTH(winid), "%u",
801                         (int)GDK_WINDOW_XID(GTK_WIDGET(c->win)->window));
802 }
803
804 void
805 usage(void) {
806         fputs("surf - simple browser\n", stderr);
807         die("usage: surf [-e Window] [-x] [-i] [-p] [-s] [uri]\n");
808 }
809
810 void
811 windowobjectcleared(GtkWidget *w, WebKitWebFrame *frame, JSContextRef js, JSObjectRef win, Client *c) {
812         JSStringRef jsscript;
813         char *script;
814         JSValueRef exception = NULL;
815         GError *error;
816         
817         if(g_file_get_contents(scriptfile, &script, NULL, &error)) {
818                 jsscript = JSStringCreateWithUTF8CString(script);
819                 JSEvaluateScript(js, jsscript, JSContextGetGlobalObject(js), NULL, 0, &exception);
820         }
821 }
822
823 void
824 zoom(Client *c, const Arg *arg) {
825         c->zoomed = TRUE;
826         if(arg->i < 0)          /* zoom out */
827                 webkit_web_view_zoom_out(c->view);
828         else if(arg->i > 0)     /* zoom in */
829                 webkit_web_view_zoom_in(c->view);
830         else {                  /* reset */
831                 c->zoomed = FALSE;
832                 webkit_web_view_set_zoom_level(c->view, 1.0);
833         }
834 }
835
836 int main(int argc, char *argv[]) {
837         int i;
838         Arg arg;
839
840         progname = argv[0];
841         /* command line args */
842         for(i = 1, arg.v = NULL; i < argc && argv[i][0] == '-' &&
843                         argv[i][1] != '\0' && argv[i][2] == '\0'; i++) {
844                 if(!strcmp(argv[i], "--")) {
845                         i++;
846                         break;
847                 }
848                 switch(argv[i][1]) {
849                 case 'x':
850                         showxid = TRUE;
851                         break;
852                 case 'e':
853                         if(++i < argc)
854                                 embed = atoi(argv[i]);
855                         else
856                                 usage();
857                         break;
858                 case 'i':
859                         loadimage = 0;
860                         break;
861                 case 'p':
862                         plugin = 0;
863                         break;
864                 case 's':
865                         script = 0;
866                         break;
867                 case 'v':
868                         die("surf-"VERSION", © 2009 surf engineers, see LICENSE for details\n");
869                 }
870         }
871         if(i < argc)
872                 arg.v = argv[i];
873         setup();
874         newclient();
875         if(arg.v)
876                 loaduri(clients, &arg);
877         gtk_main();
878         cleanup();
879         return EXIT_SUCCESS;
880 }