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