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