merge
[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 enum { AtomFind, AtomGo, AtomUri, AtomHiLight, AtomLast };
27
28 typedef union Arg Arg;
29 union Arg {
30         gboolean b;
31         gint i;
32         const void *v;
33 };
34
35 typedef struct Client {
36         GtkWidget *win, *scroll, *vbox, *indicator;
37         WebKitWebView *view;
38         char *title, *linkhover;
39         const char *uri, *needle;
40         gint progress;
41         struct Client *next;
42         gboolean zoomed;
43 } Client;
44
45 typedef struct {
46         char *label;
47         void (*func)(Client *c, const Arg *arg);
48         const Arg arg;
49 } Item;
50
51 typedef struct {
52         guint mod;
53         guint keyval;
54         void (*func)(Client *c, const Arg *arg);
55         const Arg arg;
56 } Key;
57
58 static Display *dpy;
59 static Atom atoms[AtomLast];
60 static Client *clients = NULL;
61 static GdkNativeWindow embed = 0;
62 static gboolean showxid = FALSE;
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 char *copystr(char **str, const char *src);
71 static WebKitWebView *createwindow(WebKitWebView *v, WebKitWebFrame *f, Client *c);
72 static gboolean decidedownload(WebKitWebView *v, WebKitWebFrame *f, WebKitNetworkRequest *r, gchar *m,  WebKitWebPolicyDecision *p, Client *c);
73 static gboolean decidewindow(WebKitWebView *v, WebKitWebFrame *f, WebKitNetworkRequest *r, WebKitWebNavigationAction *n, WebKitWebPolicyDecision *p, Client *c);
74 static void destroyclient(Client *c);
75 static void destroywin(GtkWidget* w, Client *c);
76 static void die(char *str);
77 static void drawindicator(Client *c);
78 static gboolean exposeindicator(GtkWidget *w, GdkEventExpose *e, Client *c);
79 static void find(Client *c, const Arg *arg);
80 static const char *getatom(Client *c, int a);
81 static const char *getcookies(SoupURI *uri);
82 static char *geturi(Client *c);
83 void gotheaders(SoupMessage *msg, gpointer user_data);
84 static gboolean keypress(GtkWidget *w, GdkEventKey *ev, Client *c);
85 static void linkhover(WebKitWebView *v, const char* t, const char* l, Client *c);
86 static void loadstatuschange(WebKitWebView *view, GParamSpec *pspec, Client *c);
87 static void loaduri(Client *c, const Arg *arg);
88 static void navigate(Client *c, const Arg *arg);
89 static Client *newclient(void);
90 static void newwindow(Client *c, const Arg *arg);
91 static void newrequest(SoupSession *s, SoupMessage *msg, gpointer v);
92 static void pasteuri(GtkClipboard *clipboard, const char *text, gpointer d);
93 static void print(Client *c, const Arg *arg);
94 static GdkFilterReturn processx(GdkXEvent *xevent, GdkEvent *event, gpointer d);
95 static void progresschange(WebKitWebView *view, GParamSpec *pspec, Client *c);
96 static void reload(Client *c, const Arg *arg);
97 static void resize(GtkWidget *w, GtkAllocation *a, Client *c);
98 static void scroll(Client *c, const Arg *arg);
99 static void setatom(Client *c, int a, const char *v);
100 static void setcookie(SoupCookie *c);
101 static void setup(void);
102 static void sigchld(int unused);
103 static void source(Client *c, const Arg *arg);
104 static void spawn(Client *c, const Arg *arg);
105 static void stop(Client *c, const Arg *arg);
106 static void titlechange(WebKitWebView *v, WebKitWebFrame* frame, const char* title, Client *c);
107 static void update(Client *c);
108 static void updatewinid(Client *c);
109 static void usage(void);
110 static void windowobjectcleared(GtkWidget *w, WebKitWebFrame *frame, JSContextRef js, JSObjectRef win, Client *c);
111 static void zoom(Client *c, const Arg *arg);
112
113 /* configuration, allows nested code to access above variables */
114 #include "config.h"
115
116 char *
117 buildpath(const char *path) {
118         char *apath, *p;
119         FILE *f;
120
121         /* creating directory */
122         if(path[0] == '/')
123                 apath = g_strdup(path);
124         else
125                 apath = g_strconcat(g_get_home_dir(), "/", path, NULL);
126         if((p = strrchr(apath, '/'))) {
127                 *p = '\0';
128                 g_mkdir_with_parents(apath, 0755);
129                 *p = '/';
130         }
131         /* creating file (gives error when apath ends with "/") */
132         if((f = fopen(apath, "a")))
133                 fclose(f);
134         return apath;
135 }
136
137 void
138 cleanup(void) {
139         while(clients)
140                 destroyclient(clients);
141         g_free(cookiefile);
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 = geturi(c);
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, AtomFind);
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, int 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                         atoms[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, AtomUri, 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
496         setatom(c, AtomFind, "");
497         setatom(c, AtomUri, "about:blank");
498         if(NOBACKGROUND)
499                 webkit_web_view_set_transparent(c->view, TRUE);
500
501         c->title = NULL;
502         c->next = clients;
503         clients = c;
504         if(showxid) {
505                 gdk_display_sync(gtk_widget_get_display(c->win));
506                 printf("%u\n", (guint)GDK_WINDOW_XID(GTK_WIDGET(c->win)->window));
507                 fflush(NULL);
508         }
509         return c;
510 }
511
512 void
513 newrequest(SoupSession *s, SoupMessage *msg, gpointer v) {
514         SoupMessageHeaders *h = msg->request_headers;
515         SoupURI *uri;
516         const char *c;
517
518         soup_message_headers_remove(h, "Cookie");
519         uri = soup_message_get_uri(msg);
520         if((c = getcookies(uri)))
521                 soup_message_headers_append(h, "Cookie", c);
522         g_signal_connect_after(G_OBJECT(msg), "got-headers", G_CALLBACK(gotheaders), NULL);
523 }
524
525 void
526 newwindow(Client *c, const Arg *arg) {
527         guint i = 0;
528         const char *cmd[10], *uri;
529         const Arg a = { .v = (void *)cmd };
530         char tmp[64];
531
532         cmd[i++] = progname;
533         if(embed) {
534                 cmd[i++] = "-e";
535                 snprintf(tmp, LENGTH(tmp), "%u\n", (int)embed);
536                 cmd[i++] = tmp;
537         }
538         if(!script)
539                 cmd[i++] = "-s";
540         if(!plugin)
541                 cmd[i++] = "-p";
542         if(!loadimage)
543                 cmd[i++] = "-i";
544         if(showxid)
545                 cmd[i++] = "-x";
546         cmd[i++] = "--";
547         uri = arg->v ? (char *)arg->v : c->linkhover;
548         if(uri)
549                 cmd[i++] = uri;
550         cmd[i++] = NULL;
551         spawn(NULL, &a);
552 }
553
554 void
555 pasteuri(GtkClipboard *clipboard, const char *text, gpointer d) {
556         Arg arg = {.v = text };
557         if(text != NULL)
558                 loaduri((Client *) d, &arg);
559 }
560
561 void
562 print(Client *c, const Arg *arg) {
563         webkit_web_frame_print(webkit_web_view_get_main_frame(c->view));
564 }
565
566 GdkFilterReturn
567 processx(GdkXEvent *e, GdkEvent *event, gpointer d) {
568         Client *c = (Client *)d;
569         XPropertyEvent *ev;
570         Arg arg;
571
572         if(((XEvent *)e)->type == PropertyNotify) {
573                 ev = &((XEvent *)e)->xproperty;
574                 if(ev->state == PropertyNewValue) {
575                         if(ev->atom == atoms[AtomFind]) {
576                                 arg.b = TRUE;
577                                 find(c, &arg);
578                                 return GDK_FILTER_REMOVE;
579                         }
580                         else if(ev->atom == atoms[AtomGo]) {
581                                 arg.v = getatom(c, AtomGo);
582                                 loaduri(c, &arg);
583                                 return GDK_FILTER_REMOVE;
584                         }
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, int a, const char *v) {
652         XSync(dpy, False);
653         XChangeProperty(dpy, GDK_WINDOW_XID(GTK_WIDGET(c->win)->window), atoms[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
674         /* atoms */
675         atoms[AtomFind] = XInternAtom(dpy, "_SURF_FIND", False);
676         atoms[AtomGo] = XInternAtom(dpy, "_SURF_GO", False);
677         atoms[AtomUri] = XInternAtom(dpy, "_SURF_URI", False);
678         atoms[AtomHiLight] = XInternAtom(dpy, "_SURF_HILIGHT", False);
679
680         /* dirs and files */
681         cookiefile = buildpath(cookiefile);
682         scriptfile = buildpath(scriptfile);
683         stylefile = buildpath(stylefile);
684
685         /* request handler */
686         s = webkit_get_default_session();
687         soup_session_remove_feature_by_type(s, soup_cookie_get_type());
688         soup_session_remove_feature_by_type(s, soup_cookie_jar_get_type());
689         g_signal_connect_after(G_OBJECT(s), "request-started", G_CALLBACK(newrequest), NULL);
690
691         /* proxy */
692         if((proxy = getenv("http_proxy")) && strcmp(proxy, "")) {
693                 new_proxy = g_strrstr(proxy, "http://") ? g_strdup(proxy) :
694                         g_strdup_printf("http://%s", proxy);
695                 puri = soup_uri_new(new_proxy);
696                 g_object_set(G_OBJECT(s), "proxy-uri", puri, NULL);
697                 soup_uri_free(puri);
698                 g_free(new_proxy);
699         }
700 }
701
702 void
703 sigchld(int unused) {
704         if(signal(SIGCHLD, sigchld) == SIG_ERR)
705                 die("Can't install SIGCHLD handler");
706         while(0 < waitpid(-1, NULL, WNOHANG));
707 }
708
709 void
710 source(Client *c, const Arg *arg) {
711         Arg a = { .b = FALSE };
712         gboolean s;
713
714         s = webkit_web_view_get_view_source_mode(c->view);
715         webkit_web_view_set_view_source_mode(c->view, !s);
716         reload(c, &a);
717 }
718
719 void
720 spawn(Client *c, const Arg *arg) {
721         if(fork() == 0) {
722                 if(dpy)
723                         close(ConnectionNumber(dpy));
724                 setsid();
725                 execvp(((char **)arg->v)[0], (char **)arg->v);
726                 fprintf(stderr, "surf: execvp %s", ((char **)arg->v)[0]);
727                 perror(" failed");
728                 exit(0);
729         }
730 }
731
732 void
733 stop(Client *c, const Arg *arg) {
734         webkit_web_view_stop_loading(c->view);
735 }
736
737 void
738 titlechange(WebKitWebView *v, WebKitWebFrame *f, const char *t, Client *c) {
739         c->title = copystr(&c->title, t);
740         update(c);
741 }
742
743 void
744 update(Client *c) {
745         char *t;
746
747         if(c->progress != 100)
748                 t = g_strdup_printf("[%i%%] %s", c->progress, c->title);
749         else if(c->linkhover)
750                 t = g_strdup(c->linkhover);
751         else
752                 t = g_strdup(c->title);
753         drawindicator(c);
754         gtk_window_set_title(GTK_WINDOW(c->win), t);
755         g_free(t);
756 }
757
758 void
759 updatewinid(Client *c) {
760         snprintf(winid, LENGTH(winid), "%u",
761                         (int)GDK_WINDOW_XID(GTK_WIDGET(c->win)->window));
762 }
763
764 void
765 usage(void) {
766         fputs("surf - simple browser\n", stderr);
767         die("usage: surf [-e xid] [-i] [-p] [-s] [-v] [-x] [uri]\n");
768 }
769
770 void
771 windowobjectcleared(GtkWidget *w, WebKitWebFrame *frame, JSContextRef js, JSObjectRef win, Client *c) {
772         runscript(frame, js);
773 }
774
775 void
776 zoom(Client *c, const Arg *arg) {
777         c->zoomed = TRUE;
778         if(arg->i < 0)          /* zoom out */
779                 webkit_web_view_zoom_out(c->view);
780         else if(arg->i > 0)     /* zoom in */
781                 webkit_web_view_zoom_in(c->view);
782         else {                  /* reset */
783                 c->zoomed = FALSE;
784                 webkit_web_view_set_zoom_level(c->view, 1.0);
785         }
786 }
787
788 int
789 main(int argc, char *argv[]) {
790         int i;
791         Arg arg;
792
793         progname = argv[0];
794         /* command line args */
795         for(i = 1, arg.v = NULL; i < argc && argv[i][0] == '-' &&
796                         argv[i][1] != '\0' && argv[i][2] == '\0'; i++) {
797                 if(!strcmp(argv[i], "--")) {
798                         i++;
799                         break;
800                 }
801                 switch(argv[i][1]) {
802                 case 'e':
803                         if(++i < argc)
804                                 embed = atoi(argv[i]);
805                         else
806                                 usage();
807                         break;
808                 case 'i':
809                         loadimage = 0;
810                         break;
811                 case 'p':
812                         plugin = 0;
813                         break;
814                 case 's':
815                         script = 0;
816                         break;
817                 case 'x':
818                         showxid = TRUE;
819                         break;
820                 case 'v':
821                         die("surf-"VERSION", © 2009 surf engineers, see LICENSE for details\n");
822                 default:
823                         usage();
824                 }
825         }
826         if(i < argc)
827                 arg.v = argv[i];
828         setup();
829         newclient();
830         if(arg.v)
831                 loaduri(clients, &arg);
832         gtk_main();
833         cleanup();
834         return EXIT_SUCCESS;
835 }