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