now we've got access to cookies before they're sended. Let's start building a cookieh...
[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(SoupSession *s, SoupMessage *msg, gpointer v);
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
507         /* Indicator */
508         c->indicator = gtk_drawing_area_new();
509         gtk_widget_set_size_request(c->indicator, 0, 2);
510         g_signal_connect (G_OBJECT (c->indicator), "expose_event",
511                         G_CALLBACK (exposeindicator), c);
512
513         /* Arranging */
514         gtk_container_add(GTK_CONTAINER(c->scroll), GTK_WIDGET(c->view));
515         gtk_container_add(GTK_CONTAINER(c->win), c->vbox);
516         gtk_container_add(GTK_CONTAINER(c->vbox), c->scroll);
517         gtk_container_add(GTK_CONTAINER(c->vbox), c->indicator);
518
519         /* Setup */
520         gtk_box_set_child_packing(GTK_BOX(c->vbox), c->indicator, FALSE, FALSE, 0, GTK_PACK_START);
521         gtk_box_set_child_packing(GTK_BOX(c->vbox), c->scroll, TRUE, TRUE, 0, GTK_PACK_START);
522         gtk_widget_grab_focus(GTK_WIDGET(c->view));
523         gtk_widget_show(c->vbox);
524         gtk_widget_show(c->indicator);
525         gtk_widget_show(c->scroll);
526         gtk_widget_show(GTK_WIDGET(c->view));
527         gtk_widget_show(c->win);
528         gtk_window_set_geometry_hints(GTK_WINDOW(c->win), NULL, &hints, GDK_HINT_MIN_SIZE);
529         gdk_window_set_events(GTK_WIDGET(c->win)->window, GDK_ALL_EVENTS_MASK);
530         gdk_window_add_filter(GTK_WIDGET(c->win)->window, processx, c);
531         webkit_web_view_set_full_content_zoom(c->view, TRUE);
532         settings = webkit_web_view_get_settings(c->view);
533         if(!(ua = getenv("SURF_USERAGENT")))
534                 ua = useragent;
535         g_object_set(G_OBJECT(settings), "user-agent", ua, NULL);
536         uri = g_strconcat("file://", stylefile, NULL);
537         g_object_set(G_OBJECT(settings), "user-stylesheet-uri", uri, NULL);
538         g_free(uri);
539         setatom(c, findprop, "");
540         setatom(c, uriprop, "");
541
542         c->download = NULL;
543         c->title = NULL;
544         c->next = clients;
545         clients = c;
546         if(showxid) {
547                 gdk_display_sync(gtk_widget_get_display(c->win));
548                 printf("%u\n", (guint)GDK_WINDOW_XID(GTK_WIDGET(c->win)->window));
549                 fflush(NULL);
550         }
551         return c;
552 }
553
554 static void newrequest(SoupSession *s, SoupMessage *msg, gpointer v) {
555         SoupMessageHeaders *h = msg->request_headers;
556
557         soup_message_headers_remove(h, "Cookie");
558 }
559
560 void
561 newwindow(Client *c, const Arg *arg) {
562         guint i = 0;
563         const char *cmd[7], *uri;
564         const Arg a = { .v = (void *)cmd };
565         char tmp[64];
566
567         cmd[i++] = progname;
568         if(embed) {
569                 cmd[i++] = "-e";
570                 snprintf(tmp, LENGTH(tmp), "%u\n", (int)embed);
571                 cmd[i++] = tmp;
572         }
573         if(showxid) {
574                 cmd[i++] = "-x";
575         }
576         cmd[i++] = "--";
577         uri = arg->v ? (char *)arg->v : c->linkhover;
578         if(uri)
579                 cmd[i++] = uri;
580         cmd[i++] = NULL;
581         spawn(NULL, &a);
582 }
583
584 void
585 pasteuri(GtkClipboard *clipboard, const char *text, gpointer d) {
586         Arg arg = {.v = text };
587         if(text != NULL)
588                 loaduri((Client *) d, &arg);
589 }
590
591 void
592 print(Client *c, const Arg *arg) {
593         webkit_web_frame_print(webkit_web_view_get_main_frame(c->view));
594 }
595
596 GdkFilterReturn
597 processx(GdkXEvent *e, GdkEvent *event, gpointer d) {
598         Client *c = (Client *)d;
599         XPropertyEvent *ev;
600         Arg arg;
601
602         if(((XEvent *)e)->type == PropertyNotify) {
603                 ev = &((XEvent *)e)->xproperty;
604                 if(ignorexprop)
605                         ignorexprop--;
606                 else if(ev->state == PropertyNewValue) {
607                         if(ev->atom == uriprop) {
608                                 arg.v = getatom(c, uriprop);
609                                 loaduri(c, &arg);
610                         }
611                         else if(ev->atom == findprop) {
612                                 arg.b = TRUE;
613                                 find(c, &arg);
614                         }
615                         return GDK_FILTER_REMOVE;
616                 }
617         }
618         return GDK_FILTER_CONTINUE;
619 }
620
621 void
622 progresschange(WebKitWebView *view, GParamSpec *pspec, Client *c) {
623         c->progress = webkit_web_view_get_progress(c->view) * 100;
624         update(c);
625 }
626
627 void
628 reload(Client *c, const Arg *arg) {
629         gboolean nocache = *(gboolean *)arg;
630         if(nocache)
631                  webkit_web_view_reload_bypass_cache(c->view);
632         else
633                  webkit_web_view_reload(c->view);
634 }
635
636 void
637 resize(GtkWidget *w, GtkAllocation *a, Client *c) {
638         double zoom;
639
640         if(c->zoomed)
641                 return;
642         zoom = webkit_web_view_get_zoom_level(c->view);
643         if(a->width * a->height < 300 * 400 && zoom != 0.2)
644                 webkit_web_view_set_zoom_level(c->view, 0.2);
645         else if(zoom != 1.0)
646                 webkit_web_view_set_zoom_level(c->view, 1.0);
647 }
648
649 void
650 scroll(Client *c, const Arg *arg) {
651         gdouble v;
652         GtkAdjustment *a;
653
654         a = gtk_scrolled_window_get_vadjustment(GTK_SCROLLED_WINDOW(c->scroll));
655         v = gtk_adjustment_get_value(a);
656         v += gtk_adjustment_get_step_increment(a) * arg->i;
657         v = MAX(v, 0.0);
658         v = MIN(v, gtk_adjustment_get_upper(a) - gtk_adjustment_get_page_size(a));
659         gtk_adjustment_set_value(a, v);
660 }
661
662 void
663 setatom(Client *c, Atom a, const char *v) {
664         XSync(dpy, False);
665         ignorexprop++;
666         XChangeProperty(dpy, GDK_WINDOW_XID(GTK_WIDGET(c->win)->window), a,
667                         XA_STRING, 8, PropModeReplace, (unsigned char *)v,
668                         strlen(v) + 1);
669 }
670
671 void
672 setup(void) {
673         char *proxy;
674         char *new_proxy;
675         SoupURI *puri;
676         SoupSession *s;
677
678         /* clean up any zombies immediately */
679         sigchld(0);
680         gtk_init(NULL, NULL);
681         if (!g_thread_supported())
682                 g_thread_init(NULL);
683
684         dpy = GDK_DISPLAY();
685         s = webkit_get_default_session();
686         uriprop = XInternAtom(dpy, "_SURF_URI", False);
687         findprop = XInternAtom(dpy, "_SURF_FIND", False);
688
689         /* dirs and files */
690         cookiefile = buildpath(cookiefile);
691         dldir = buildpath(dldir);
692         scriptfile = buildpath(scriptfile);
693         stylefile = buildpath(stylefile);
694
695         /* request handler */
696         s = webkit_get_default_session();
697         soup_session_remove_feature_by_type(s, soup_cookie_get_type());
698         soup_session_remove_feature_by_type(s, soup_cookie_jar_get_type());
699         g_signal_connect_after(G_OBJECT(s), "request-started", G_CALLBACK(newrequest), NULL);
700
701
702         /* proxy */
703         if((proxy = getenv("http_proxy")) && strcmp(proxy, "")) {
704                 new_proxy = g_strrstr(proxy, "http://") ? g_strdup(proxy) :
705                         g_strdup_printf("http://%s", proxy);
706
707                 puri = soup_uri_new(new_proxy);
708                 g_object_set(G_OBJECT(s), "proxy-uri", puri, NULL);
709                 soup_uri_free(puri);
710                 g_free(new_proxy);
711         }
712 }
713
714 void
715 sigchld(int unused) {
716         if(signal(SIGCHLD, sigchld) == SIG_ERR)
717                 die("Can't install SIGCHLD handler");
718         while(0 < waitpid(-1, NULL, WNOHANG));
719 }
720
721 void
722 source(Client *c, const Arg *arg) {
723         Arg a = { .b = FALSE };
724         gboolean s;
725
726         s = webkit_web_view_get_view_source_mode(c->view);
727         webkit_web_view_set_view_source_mode(c->view, !s);
728         reload(c, &a);
729 }
730
731 void
732 spawn(Client *c, const Arg *arg) {
733         if(fork() == 0) {
734                 if(dpy)
735                         close(ConnectionNumber(dpy));
736                 setsid();
737                 execvp(((char **)arg->v)[0], (char **)arg->v);
738                 fprintf(stderr, "surf: execvp %s", ((char **)arg->v)[0]);
739                 perror(" failed");
740                 exit(0);
741         }
742 }
743
744 void
745 stop(Client *c, const Arg *arg) {
746         if(c->download)
747                 webkit_download_cancel(c->download);
748         else
749                 webkit_web_view_stop_loading(c->view);
750         c->download = NULL;
751 }
752
753 void
754 titlechange(WebKitWebView *v, WebKitWebFrame *f, const char *t, Client *c) {
755         c->title = copystr(&c->title, t);
756         update(c);
757 }
758
759 void
760 update(Client *c) {
761         char *t;
762
763         if(c->progress != 100)
764                 t = g_strdup_printf("[%i%%] %s", c->progress, c->title);
765         else if(c->linkhover)
766                 t = g_strdup(c->linkhover);
767         else
768                 t = g_strdup(c->title);
769         drawindicator(c);
770         gtk_window_set_title(GTK_WINDOW(c->win), t);
771         g_free(t);
772 }
773
774 void
775 updatedownload(WebKitDownload *o, GParamSpec *pspec, Client *c) {
776         WebKitDownloadStatus status;
777
778         status = webkit_download_get_status(c->download);
779         if(status == WEBKIT_DOWNLOAD_STATUS_STARTED || status == WEBKIT_DOWNLOAD_STATUS_CREATED) {
780                 c->progress = (gint)(webkit_download_get_progress(c->download)*100);
781         }
782         update(c);
783 }
784
785 void
786 updatewinid(Client *c) {
787         snprintf(winid, LENGTH(winid), "%u",
788                         (int)GDK_WINDOW_XID(GTK_WIDGET(c->win)->window));
789 }
790
791 void
792 usage(void) {
793         fputs("surf - simple browser\n", stderr);
794         die("usage: surf [-e Window] [-x] [uri]\n");
795 }
796
797 void
798 windowobjectcleared(GtkWidget *w, WebKitWebFrame *frame, JSContextRef js, JSObjectRef win, Client *c) {
799         JSStringRef jsscript;
800         char *script;
801         JSValueRef exception = NULL;
802         GError *error;
803         
804         if(g_file_get_contents(scriptfile, &script, NULL, &error)) {
805                 jsscript = JSStringCreateWithUTF8CString(script);
806                 JSEvaluateScript(js, jsscript, JSContextGetGlobalObject(js), NULL, 0, &exception);
807         }
808 }
809
810 void
811 zoom(Client *c, const Arg *arg) {
812         c->zoomed = TRUE;
813         if(arg->i < 0)          /* zoom out */
814                 webkit_web_view_zoom_out(c->view);
815         else if(arg->i > 0)     /* zoom in */
816                 webkit_web_view_zoom_in(c->view);
817         else {                  /* reset */
818                 c->zoomed = FALSE;
819                 webkit_web_view_set_zoom_level(c->view, 1.0);
820         }
821 }
822
823 int main(int argc, char *argv[]) {
824         int i;
825         Arg arg;
826
827         progname = argv[0];
828         /* command line args */
829         for(i = 1, arg.v = NULL; i < argc && argv[i][0] == '-'; i++) {
830                 if(!strcmp(argv[i], "-x"))
831                         showxid = TRUE;
832                 else if(!strcmp(argv[i], "-e")) {
833                         if(++i < argc)
834                                 embed = atoi(argv[i]);
835                         else
836                                 usage();
837                 }
838                 else if(!strcmp(argv[i], "--")) {
839                         i++;
840                         break;
841                 }
842                 else if(!strcmp(argv[i], "-v"))
843                         die("surf-"VERSION", © 2009 surf engineers, see LICENSE for details\n");
844                 else
845                         usage();
846         }
847         if(i < argc)
848                 arg.v = argv[i];
849         setup();
850         newclient();
851         if(arg.v)
852                 loaduri(clients, &arg);
853         gtk_main();
854         cleanup();
855         return EXIT_SUCCESS;
856 }