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