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