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