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