session gets set properly in setup()
[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
66 static char *buildpath(const char *path);
67 static void cleanup(void);
68 static void clipboard(Client *c, const Arg *arg);
69 static void context(WebKitWebView *v, GtkMenu *m, Client *c);
70 static char *copystr(char **str, const char *src);
71 static WebKitWebView *createwindow(WebKitWebView *v, WebKitWebFrame *f, Client *c);
72 static gboolean decidedownload(WebKitWebView *v, WebKitWebFrame *f, WebKitNetworkRequest *r, gchar *m,  WebKitWebPolicyDecision *p, Client *c);
73 static gboolean decidewindow(WebKitWebView *v, WebKitWebFrame *f, WebKitNetworkRequest *r, WebKitWebNavigationAction *n, WebKitWebPolicyDecision *p, Client *c);
74 static void destroyclient(Client *c);
75 static void destroywin(GtkWidget* w, Client *c);
76 static void die(char *str);
77 static void download(Client *c, const Arg *arg);
78 static void drawindicator(Client *c);
79 static gboolean exposeindicator(GtkWidget *w, GdkEventExpose *e, Client *c);
80 static void find(Client *c, const Arg *arg);
81 static const char *getatom(Client *c, Atom a);
82 static char *geturi(Client *c);
83 static gboolean initdownload(WebKitWebView *v, WebKitDownload *o, Client *c);
84 static void itemclick(GtkMenuItem *mi, Client *c);
85 static gboolean keypress(GtkWidget *w, GdkEventKey *ev, Client *c);
86 static void linkhover(WebKitWebView *v, const char* t, const char* l, Client *c);
87 static void loadstatuschange(WebKitWebView *view, GParamSpec *pspec, Client *c);
88 static void loaduri(Client *c, const Arg *arg);
89 static void navigate(Client *c, const Arg *arg);
90 static Client *newclient(void);
91 static void newwindow(Client *c, const Arg *arg);
92 static void newrequest(WebKitWebView *v, WebKitWebFrame *f, WebKitWebResource *r, WebKitNetworkRequest *req, WebKitNetworkResponse *res, Client *c);
93 static void pasteuri(GtkClipboard *clipboard, const char *text, gpointer d);
94 static void print(Client *c, const Arg *arg);
95 static GdkFilterReturn processx(GdkXEvent *xevent, GdkEvent *event, gpointer d);
96 static void progresschange(WebKitWebView *view, GParamSpec *pspec, Client *c);
97 static void reload(Client *c, const Arg *arg);
98 static void resize(GtkWidget *w, GtkAllocation *a, Client *c);
99 static void scroll(Client *c, const Arg *arg);
100 static void setatom(Client *c, Atom a, const char *v);
101 static void setup(void);
102 static void sigchld(int unused);
103 static void source(Client *c, const Arg *arg);
104 static void spawn(Client *c, const Arg *arg);
105 static void stop(Client *c, const Arg *arg);
106 static void titlechange(WebKitWebView *v, WebKitWebFrame* frame, const char* title, Client *c);
107 static void update(Client *c);
108 static void updatedownload(WebKitDownload *o, GParamSpec *pspec, Client *c);
109 static void updatewinid(Client *c);
110 static void usage(void);
111 static void windowobjectcleared(GtkWidget *w, WebKitWebFrame *frame, JSContextRef js, JSObjectRef win, Client *c);
112 static void zoom(Client *c, const Arg *arg);
113
114 /* configuration, allows nested code to access above variables */
115 #include "config.h"
116
117 char *
118 buildpath(const char *path) {
119         char *apath, *p;
120         FILE *f;
121
122         /* creating directory */
123         if(path[0] == '/')
124                 apath = g_strdup(path);
125         else
126                 apath = g_strconcat(g_get_home_dir(), "/", path, NULL);
127         if((p = strrchr(apath, '/'))) {
128                 *p = '\0';
129                 g_mkdir_with_parents(apath, 0755);
130                 *p = '/';
131         }
132         /* creating file (gives error when apath ends with "/") */
133         if((f = g_fopen(apath, "a")))
134                 fclose(f);
135         return apath;
136 }
137
138 void
139 cleanup(void) {
140         while(clients)
141                 destroyclient(clients);
142         g_free(cookiefile);
143         g_free(dldir);
144         g_free(scriptfile);
145         g_free(stylefile);
146 }
147
148 void
149 clipboard(Client *c, const Arg *arg) {
150         gboolean paste = *(gboolean *)arg;
151
152         if(paste)
153                 gtk_clipboard_request_text(gtk_clipboard_get(GDK_SELECTION_PRIMARY), pasteuri, c);
154         else
155                 gtk_clipboard_set_text(gtk_clipboard_get(GDK_SELECTION_PRIMARY), c->linkhover ? c->linkhover : geturi(c), -1);
156 }
157
158 void
159 context(WebKitWebView *v, GtkMenu *m, Client *c) {
160         int i;
161         GtkContainer *parent;
162
163         gtk_widget_hide_all(GTK_WIDGET(m));
164         gtk_widget_show(GTK_WIDGET(m));
165         for(i = 0; i < LENGTH(items); i++) {
166                 parent = GTK_CONTAINER(gtk_widget_get_parent(c->items[i]));
167                 if(parent)
168                         gtk_container_remove(parent, c->items[i]);
169                 gtk_menu_shell_append(GTK_MENU_SHELL(m), c->items[i]);
170                 gtk_widget_show(c->items[i]);
171         }
172 }
173
174 char *
175 copystr(char **str, const char *src) {
176         char *tmp;
177         tmp = g_strdup(src);
178
179         if(str && *str) {
180                 g_free(*str);
181                 *str = tmp;
182         }
183         return tmp;
184 }
185
186 WebKitWebView *
187 createwindow(WebKitWebView  *v, WebKitWebFrame *f, Client *c) {
188         Client *n = newclient();
189         return n->view;
190 }
191
192 gboolean
193 decidedownload(WebKitWebView *v, WebKitWebFrame *f, WebKitNetworkRequest *r, gchar *m,  WebKitWebPolicyDecision *p, Client *c) {
194         if(!webkit_web_view_can_show_mime_type(v, m)) {
195                 webkit_web_policy_decision_download(p);
196                 return TRUE;
197         }
198         return FALSE;
199 }
200
201 gboolean
202 decidewindow(WebKitWebView *view, WebKitWebFrame *f, WebKitNetworkRequest *r, WebKitWebNavigationAction *n, WebKitWebPolicyDecision *p, Client *c) {
203         Arg arg;
204
205         if(webkit_web_navigation_action_get_reason(n) == WEBKIT_WEB_NAVIGATION_REASON_LINK_CLICKED) {
206                 webkit_web_policy_decision_ignore(p);
207                 arg.v = (void *)webkit_network_request_get_uri(r);
208                 newwindow(NULL, &arg);
209                 return TRUE;
210         }
211         return FALSE;
212 }
213
214 void
215 destroyclient(Client *c) {
216         int i;
217         Client *p;
218
219         gtk_widget_destroy(c->indicator);
220         gtk_widget_destroy(GTK_WIDGET(c->view));
221         gtk_widget_destroy(c->scroll);
222         gtk_widget_destroy(c->vbox);
223         gtk_widget_destroy(c->win);
224         for(i = 0; i < LENGTH(items); i++)
225                 gtk_widget_destroy(c->items[i]);
226         free(c->items);
227
228         for(p = clients; p && p->next != c; p = p->next);
229         if(p)
230                 p->next = c->next;
231         else
232                 clients = c->next;
233         free(c);
234         if(clients == NULL)
235                 gtk_main_quit();
236 }
237
238 void
239 destroywin(GtkWidget* w, Client *c) {
240         destroyclient(c);
241 }
242
243 void
244 die(char *str) {
245         fputs(str, stderr);
246         exit(EXIT_FAILURE);
247 }
248
249 void
250 download(Client *c, const Arg *arg) {
251         char *uri;
252         WebKitNetworkRequest *r;
253         WebKitDownload       *dl;
254
255         if(arg->v)
256                 uri = (char *)arg->v;
257         else
258                 uri = c->linkhover ? c->linkhover : geturi(c);
259         r = webkit_network_request_new(uri);
260         dl = webkit_download_new(r);
261         initdownload(c->view, dl, c);
262 }
263
264 void
265 drawindicator(Client *c) {
266         gint width;
267         const char *uri;
268         GtkWidget *w;
269         GdkGC *gc;
270         GdkColor fg;
271
272         uri = getatom(c, uriprop);
273         w = c->indicator;
274         width = c->progress * w->allocation.width / 100;
275         gc = gdk_gc_new(w->window);
276         gdk_color_parse(strstr(uri, "https://") == uri ?
277                         progress_trust : progress, &fg);
278         gdk_gc_set_rgb_fg_color(gc, &fg);
279         gdk_draw_rectangle(w->window,
280                         w->style->bg_gc[GTK_WIDGET_STATE(w)],
281                         TRUE, 0, 0, w->allocation.width, w->allocation.height);
282         gdk_draw_rectangle(w->window, gc, TRUE, 0, 0, width,
283                         w->allocation.height);
284         g_object_unref(gc);
285 }
286
287 gboolean
288 exposeindicator(GtkWidget *w, GdkEventExpose *e, Client *c) {
289         drawindicator(c);
290         return TRUE;
291 }
292
293 void
294 find(Client *c, const Arg *arg) {
295         const char *s;
296
297         s = getatom(c, findprop);
298         gboolean forward = *(gboolean *)arg;
299         webkit_web_view_search_text(c->view, s, FALSE, forward, TRUE);
300 }
301
302 const char *
303 getatom(Client *c, Atom a) {
304         static char buf[BUFSIZ];
305         Atom adummy;
306         int idummy;
307         unsigned long ldummy;
308         unsigned char *p = NULL;
309
310         XGetWindowProperty(dpy, GDK_WINDOW_XID(GTK_WIDGET(c->win)->window),
311                         a, 0L, BUFSIZ, False, XA_STRING,
312                         &adummy, &idummy, &ldummy, &ldummy, &p);
313         if(p)
314                 strncpy(buf, (char *)p, LENGTH(buf)-1);
315         else
316                 buf[0] = '\0';
317         XFree(p);
318         return buf;
319 }
320
321 char *
322 geturi(Client *c) {
323         char *uri;
324
325         if(!(uri = (char *)webkit_web_view_get_uri(c->view)))
326                 uri = "about:blank";
327         return uri;
328 }
329
330 gboolean
331 initdownload(WebKitWebView *view, WebKitDownload *o, Client *c) {
332         const char *filename;
333         char *uri, *html;
334
335         stop(c, NULL);
336         c->download = o;
337         filename = webkit_download_get_suggested_filename(o);
338         if(!strcmp("", filename))
339                 filename = "index.html";
340         uri = g_strconcat("file://", dldir, "/", filename, NULL);
341         webkit_download_set_destination_uri(c->download, uri);
342         c->progress = 0;
343         g_free(uri);
344         html = g_strdup_printf("Download <b>%s</b>...", filename);
345         webkit_web_view_load_html_string(c->view, html,
346                         webkit_download_get_uri(c->download));
347         g_signal_connect(c->download, "notify::progress", G_CALLBACK(updatedownload), c);
348         g_signal_connect(c->download, "notify::status", G_CALLBACK(updatedownload), c);
349         webkit_download_start(c->download);
350         
351         c->title = copystr(&c->title, filename);
352         update(c);
353         g_free(html);
354         return TRUE;
355 }
356
357 void
358 itemclick(GtkMenuItem *mi, Client *c) {
359         int i;
360         const char *label;
361
362         label = gtk_menu_item_get_label(mi);
363         for(i = 0; i < LENGTH(items); i++)
364                 if(!strcmp(items[i].label, label))
365                         items[i].func(c, &(items[i].arg));
366 }
367
368 gboolean
369 keypress(GtkWidget* w, GdkEventKey *ev, Client *c) {
370         guint i;
371         gboolean processed = FALSE;
372
373         updatewinid(c);
374         for(i = 0; i < LENGTH(keys); i++) {
375                 if(gdk_keyval_to_lower(ev->keyval) == keys[i].keyval
376                                 && CLEANMASK(ev->state) == keys[i].mod
377                                 && keys[i].func) {
378                         keys[i].func(c, &(keys[i].arg));
379                         processed = TRUE;
380                 }
381         }
382         return processed;
383 }
384
385 void
386 linkhover(WebKitWebView *v, const char* t, const char* l, Client *c) {
387         if(l)
388                 c->linkhover = copystr(&c->linkhover, l);
389         else if(c->linkhover) {
390                 free(c->linkhover);
391                 c->linkhover = NULL;
392         }
393         update(c);
394 }
395
396 void
397 loadstatuschange(WebKitWebView *view, GParamSpec *pspec, Client *c) {
398         switch(webkit_web_view_get_load_status (c->view)) {
399         case WEBKIT_LOAD_COMMITTED:
400                 setatom(c, uriprop, geturi(c));
401                 break;
402         case WEBKIT_LOAD_FINISHED:
403                 c->progress = 0;
404                 update(c);
405                 break;
406         case WEBKIT_LOAD_PROVISIONAL:
407         case WEBKIT_LOAD_FIRST_VISUALLY_NON_EMPTY_LAYOUT:
408                 break;
409         }
410 }
411
412 void
413 loaduri(Client *c, const Arg *arg) {
414         char *u;
415         const char *uri = (char *)arg->v;
416         Arg a = { .b = FALSE };
417
418         if(strcmp(uri, "") == 0)
419                 return;
420         u = g_strrstr(uri, "://") ? g_strdup(uri)
421                 : g_strdup_printf("http://%s", uri);
422         /* prevents endless loop */
423         if(c->uri && strcmp(u, c->uri) == 0) {
424                 reload(c, &a);
425         }
426         else {
427                 webkit_web_view_load_uri(c->view, u);
428                 c->progress = 0;
429                 c->title = copystr(&c->title, u);
430                 g_free(u);
431                 update(c);
432         }
433 }
434
435 void
436 navigate(Client *c, const Arg *arg) {
437         int steps = *(int *)arg;
438         webkit_web_view_go_back_or_forward(c->view, steps);
439 }
440
441 Client *
442 newclient(void) {
443         int i;
444         Client *c;
445         WebKitWebSettings *settings;
446         GdkGeometry hints = { 1, 1 };
447         char *uri, *ua;
448
449         if(!(c = calloc(1, sizeof(Client))))
450                 die("Cannot malloc!\n");
451         /* Window */
452         if(embed) {
453                 c->win = gtk_plug_new(embed);
454         }
455         else {
456                 c->win = gtk_window_new(GTK_WINDOW_TOPLEVEL);
457                 /* TA:  20091214:  Despite what the GNOME docs say, the ICCCM
458                  * is always correct, so we should still call this function.
459                  * But when doing so, we *must* differentiate between a
460                  * WM_CLASS and a resource on the window.  By convention, the
461                  * window class (WM_CLASS) is capped, while the resource is in
462                  * lowercase.   Both these values come as a pair.
463                  */
464                 gtk_window_set_wmclass(GTK_WINDOW(c->win), "surf", "surf");
465
466                 /* TA:  20091214:  And set the role here as well -- so that
467                  * sessions can pick this up.
468                  */
469                 gtk_window_set_role(GTK_WINDOW(c->win), "Surf");
470         }
471         gtk_window_set_default_size(GTK_WINDOW(c->win), 800, 600);
472         g_signal_connect(G_OBJECT(c->win), "destroy", G_CALLBACK(destroywin), c);
473         g_signal_connect(G_OBJECT(c->win), "key-press-event", G_CALLBACK(keypress), c);
474         g_signal_connect(G_OBJECT(c->win), "size-allocate", G_CALLBACK(resize), c);
475
476         if(!(c->items = calloc(1, sizeof(GtkWidget *) * LENGTH(items))))
477                 die("Cannot malloc!\n");
478
479         /* contextmenu */
480         for(i = 0; i < LENGTH(items); i++) {
481                 c->items[i] = gtk_menu_item_new_with_label(items[i].label);
482                 g_signal_connect(G_OBJECT(c->items[i]), "activate",
483                                 G_CALLBACK(itemclick), c);
484         }
485
486         /* VBox */
487         c->vbox = gtk_vbox_new(FALSE, 0);
488
489         /* Scrolled Window */
490         c->scroll = gtk_scrolled_window_new(NULL, NULL);
491         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(c->scroll),
492                         GTK_POLICY_NEVER, GTK_POLICY_NEVER);
493
494         /* Webview */
495         c->view = WEBKIT_WEB_VIEW(webkit_web_view_new());
496         g_signal_connect(G_OBJECT(c->view), "title-changed", G_CALLBACK(titlechange), c);
497         g_signal_connect(G_OBJECT(c->view), "hovering-over-link", G_CALLBACK(linkhover), c);
498         g_signal_connect(G_OBJECT(c->view), "create-web-view", G_CALLBACK(createwindow), c);
499         g_signal_connect(G_OBJECT(c->view), "new-window-policy-decision-requested", G_CALLBACK(decidewindow), c);
500         g_signal_connect(G_OBJECT(c->view), "mime-type-policy-decision-requested", G_CALLBACK(decidedownload), c);
501         g_signal_connect(G_OBJECT(c->view), "download-requested", G_CALLBACK(initdownload), c);
502         g_signal_connect(G_OBJECT(c->view), "window-object-cleared", G_CALLBACK(windowobjectcleared), c);
503         g_signal_connect(G_OBJECT(c->view), "populate-popup", G_CALLBACK(context), c);
504         g_signal_connect(G_OBJECT(c->view), "notify::load-status", G_CALLBACK(loadstatuschange), c);
505         g_signal_connect(G_OBJECT(c->view), "notify::progress", G_CALLBACK(progresschange), c);
506         g_signal_connect(G_OBJECT(c->view), "resource-request-starting", G_CALLBACK(newrequest), 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_free(uri);
540         setatom(c, findprop, "");
541         setatom(c, uriprop, "");
542
543         c->download = NULL;
544         c->title = NULL;
545         c->next = clients;
546         clients = c;
547         if(showxid) {
548                 gdk_display_sync(gtk_widget_get_display(c->win));
549                 printf("%u\n", (guint)GDK_WINDOW_XID(GTK_WIDGET(c->win)->window));
550                 fflush(NULL);
551         }
552         return c;
553 }
554
555 void func(const char *name, const char *value, void *dummy) {
556 printf("%s = %s\n", name, value);
557 }
558
559
560 static void newrequest(WebKitWebView *v, WebKitWebFrame *f, WebKitWebResource *r, WebKitNetworkRequest *req, WebKitNetworkResponse *res, Client *c) {
561         SoupMessage *msg = webkit_network_request_get_message(req);
562         SoupMessageHeaders *h;
563         if(!msg)
564                 return;
565         h = msg->request_headers;
566         soup_message_headers_foreach(h, func, NULL);
567 }
568
569 void
570 newwindow(Client *c, const Arg *arg) {
571         guint i = 0;
572         const char *cmd[7], *uri;
573         const Arg a = { .v = (void *)cmd };
574         char tmp[64];
575
576         cmd[i++] = progname;
577         if(embed) {
578                 cmd[i++] = "-e";
579                 snprintf(tmp, LENGTH(tmp), "%u\n", (int)embed);
580                 cmd[i++] = tmp;
581         }
582         if(showxid) {
583                 cmd[i++] = "-x";
584         }
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         /* create dirs and files */
699         cookiefile = buildpath(cookiefile);
700         dldir = buildpath(dldir);
701         scriptfile = buildpath(scriptfile);
702         stylefile = buildpath(stylefile);
703
704         s = webkit_get_default_session();
705
706         soup_session_remove_feature_by_type(s, soup_cookie_get_type());
707
708         /* proxy */
709         if((proxy = getenv("http_proxy")) && strcmp(proxy, "")) {
710                 new_proxy = g_strrstr(proxy, "http://") ? g_strdup(proxy) :
711                         g_strdup_printf("http://%s", proxy);
712
713                 puri = soup_uri_new(new_proxy);
714                 g_object_set(G_OBJECT(s), "proxy-uri", puri, NULL);
715                 soup_uri_free(puri);
716                 g_free(new_proxy);
717         }
718 }
719
720 void
721 sigchld(int unused) {
722         if(signal(SIGCHLD, sigchld) == SIG_ERR)
723                 die("Can't install SIGCHLD handler");
724         while(0 < waitpid(-1, NULL, WNOHANG));
725 }
726
727 void
728 source(Client *c, const Arg *arg) {
729         Arg a = { .b = FALSE };
730         gboolean s;
731
732         s = webkit_web_view_get_view_source_mode(c->view);
733         webkit_web_view_set_view_source_mode(c->view, !s);
734         reload(c, &a);
735 }
736
737 void
738 spawn(Client *c, const Arg *arg) {
739         if(fork() == 0) {
740                 if(dpy)
741                         close(ConnectionNumber(dpy));
742                 setsid();
743                 execvp(((char **)arg->v)[0], (char **)arg->v);
744                 fprintf(stderr, "surf: execvp %s", ((char **)arg->v)[0]);
745                 perror(" failed");
746                 exit(0);
747         }
748 }
749
750 void
751 stop(Client *c, const Arg *arg) {
752         if(c->download)
753                 webkit_download_cancel(c->download);
754         else
755                 webkit_web_view_stop_loading(c->view);
756         c->download = NULL;
757 }
758
759 void
760 titlechange(WebKitWebView *v, WebKitWebFrame *f, const char *t, Client *c) {
761         c->title = copystr(&c->title, t);
762         update(c);
763 }
764
765 void
766 update(Client *c) {
767         char *t;
768
769         if(c->progress != 100)
770                 t = g_strdup_printf("[%i%%] %s", c->progress, c->title);
771         else if(c->linkhover)
772                 t = g_strdup(c->linkhover);
773         else
774                 t = g_strdup(c->title);
775         drawindicator(c);
776         gtk_window_set_title(GTK_WINDOW(c->win), t);
777         g_free(t);
778 }
779
780 void
781 updatedownload(WebKitDownload *o, GParamSpec *pspec, Client *c) {
782         WebKitDownloadStatus status;
783
784         status = webkit_download_get_status(c->download);
785         if(status == WEBKIT_DOWNLOAD_STATUS_STARTED || status == WEBKIT_DOWNLOAD_STATUS_CREATED) {
786                 c->progress = (gint)(webkit_download_get_progress(c->download)*100);
787         }
788         update(c);
789 }
790
791 void
792 updatewinid(Client *c) {
793         snprintf(winid, LENGTH(winid), "%u",
794                         (int)GDK_WINDOW_XID(GTK_WIDGET(c->win)->window));
795 }
796
797 void
798 usage(void) {
799         fputs("surf - simple browser\n", stderr);
800         die("usage: surf [-e Window] [-x] [uri]\n");
801 }
802
803 void
804 windowobjectcleared(GtkWidget *w, WebKitWebFrame *frame, JSContextRef js, JSObjectRef win, Client *c) {
805         JSStringRef jsscript;
806         char *script;
807         JSValueRef exception = NULL;
808         GError *error;
809         
810         if(g_file_get_contents(scriptfile, &script, NULL, &error)) {
811                 jsscript = JSStringCreateWithUTF8CString(script);
812                 JSEvaluateScript(js, jsscript, JSContextGetGlobalObject(js), NULL, 0, &exception);
813         }
814 }
815
816 void
817 zoom(Client *c, const Arg *arg) {
818         c->zoomed = TRUE;
819         if(arg->i < 0)          /* zoom out */
820                 webkit_web_view_zoom_out(c->view);
821         else if(arg->i > 0)     /* zoom in */
822                 webkit_web_view_zoom_in(c->view);
823         else {                  /* reset */
824                 c->zoomed = FALSE;
825                 webkit_web_view_set_zoom_level(c->view, 1.0);
826         }
827 }
828
829 int main(int argc, char *argv[]) {
830         int i;
831         Arg arg;
832
833         progname = argv[0];
834         /* command line args */
835         for(i = 1, arg.v = NULL; i < argc && argv[i][0] == '-'; i++) {
836                 if(!strcmp(argv[i], "-x"))
837                         showxid = TRUE;
838                 else if(!strcmp(argv[i], "-e")) {
839                         if(++i < argc)
840                                 embed = atoi(argv[i]);
841                         else
842                                 usage();
843                 }
844                 else if(!strcmp(argv[i], "--")) {
845                         i++;
846                         break;
847                 }
848                 else if(!strcmp(argv[i], "-v"))
849                         die("surf-"VERSION", © 2009 surf engineers, see LICENSE for details\n");
850                 else
851                         usage();
852         }
853         if(i < argc)
854                 arg.v = argv[i];
855         setup();
856         newclient();
857         if(arg.v)
858                 loaduri(clients, &arg);
859         gtk_main();
860         cleanup();
861         return EXIT_SUCCESS;
862 }