enabling spatial-navigation
[surf.git] / surf.c
1 /* See LICENSE file for copyright and license details.
2  *
3  * To understand surf, start reading main().
4  */
5 #include <signal.h>
6 #include <X11/X.h>
7 #include <X11/Xatom.h>
8 #include <gtk/gtk.h>
9 #include <gdk/gdkx.h>
10 #include <gdk/gdk.h>
11 #include <gdk/gdkkeysyms.h>
12 #include <string.h>
13 #include <sys/types.h>
14 #include <sys/wait.h>
15 #include <unistd.h>
16 #include <stdlib.h>
17 #include <stdio.h>
18 #include <webkit/webkit.h>
19 #include <glib/gstdio.h>
20 #include <JavaScriptCore/JavaScript.h>
21 #include <sys/file.h>
22
23 #define LENGTH(x)               (sizeof x / sizeof x[0])
24 #define CLEANMASK(mask)         (mask & ~(GDK_MOD2_MASK))
25
26 enum { AtomFind, AtomGo, AtomUri, AtomHiLight, AtomLast };
27
28 typedef union Arg Arg;
29 union Arg {
30         gboolean b;
31         gint i;
32         const void *v;
33 };
34
35 typedef struct Client {
36         GtkWidget *win, *scroll, *vbox, *indicator;
37         WebKitWebView *view;
38         char *title, *linkhover;
39         const char *uri, *needle;
40         gint progress;
41         struct Client *next;
42         gboolean zoomed;
43 } Client;
44
45 typedef struct {
46         char *label;
47         void (*func)(Client *c, const Arg *arg);
48         const Arg arg;
49 } Item;
50
51 typedef struct {
52         guint mod;
53         guint keyval;
54         void (*func)(Client *c, const Arg *arg);
55         const Arg arg;
56 } Key;
57
58 static Display *dpy;
59 static Atom atoms[AtomLast];
60 static Client *clients = NULL;
61 static GdkNativeWindow embed = 0;
62 static gboolean showxid = FALSE;
63 static char winid[64];
64 static char *progname;
65 static gboolean loadimage = 1, plugin = 1, script = 1;
66
67 static char *buildpath(const char *path);
68 static void cleanup(void);
69 static void clipboard(Client *c, const Arg *arg);
70 static char *copystr(char **str, const char *src);
71 static WebKitWebView *createwindow(WebKitWebView *v, WebKitWebFrame *f, Client *c);
72 static gboolean decidedownload(WebKitWebView *v, WebKitWebFrame *f, WebKitNetworkRequest *r, gchar *m,  WebKitWebPolicyDecision *p, Client *c);
73 static gboolean decidewindow(WebKitWebView *v, WebKitWebFrame *f, WebKitNetworkRequest *r, WebKitWebNavigationAction *n, WebKitWebPolicyDecision *p, Client *c);
74 static void destroyclient(Client *c);
75 static void destroywin(GtkWidget* w, Client *c);
76 static void die(char *str);
77 static void drawindicator(Client *c);
78 static gboolean exposeindicator(GtkWidget *w, GdkEventExpose *e, Client *c);
79 static void find(Client *c, const Arg *arg);
80 static const char *getatom(Client *c, int a);
81 static const char *getcookies(SoupURI *uri);
82 static char *geturi(Client *c);
83 void gotheaders(SoupMessage *msg, gpointer user_data);
84 static gboolean keypress(GtkWidget *w, GdkEventKey *ev, Client *c);
85 static void linkhover(WebKitWebView *v, const char* t, const char* l, Client *c);
86 static void loadstatuschange(WebKitWebView *view, GParamSpec *pspec, Client *c);
87 static void loaduri(Client *c, const Arg *arg);
88 static void mousemove(GtkWidget *w, GdkEventMotion *e, Client *c);
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 keypress(GtkWidget* w, GdkEventKey *ev, Client *c) {
334         guint i;
335         gboolean processed = FALSE;
336
337         updatewinid(c);
338         for(i = 0; i < LENGTH(keys); i++) {
339                 if(gdk_keyval_to_lower(ev->keyval) == keys[i].keyval
340                                 && CLEANMASK(ev->state) == keys[i].mod
341                                 && keys[i].func) {
342                         keys[i].func(c, &(keys[i].arg));
343                         processed = TRUE;
344                 }
345         }
346         return processed;
347 }
348
349 void
350 linkhover(WebKitWebView *v, const char* t, const char* l, Client *c) {
351         if(l) {
352                 c->linkhover = copystr(&c->linkhover, l);
353         }
354         else if(c->linkhover) {
355                 free(c->linkhover);
356                 c->linkhover = NULL;
357         }
358         update(c);
359 }
360
361 void
362 loadstatuschange(WebKitWebView *view, GParamSpec *pspec, Client *c) {
363         switch(webkit_web_view_get_load_status (c->view)) {
364         case WEBKIT_LOAD_COMMITTED:
365                 setatom(c, AtomUri, geturi(c));
366                 break;
367         case WEBKIT_LOAD_FINISHED:
368                 c->progress = 0;
369                 update(c);
370                 break;
371         default:
372                 break;
373         }
374 }
375
376 void
377 loaduri(Client *c, const Arg *arg) {
378         char *u;
379         const char *uri = (char *)arg->v;
380         Arg a = { .b = FALSE };
381
382         if(strcmp(uri, "") == 0)
383                 return;
384         u = g_strrstr(uri, "://") ? g_strdup(uri)
385                 : g_strdup_printf("http://%s", uri);
386         /* prevents endless loop */
387         if(c->uri && strcmp(u, c->uri) == 0) {
388                 reload(c, &a);
389         }
390         else {
391                 webkit_web_view_load_uri(c->view, u);
392                 c->progress = 0;
393                 c->title = copystr(&c->title, u);
394                 g_free(u);
395                 update(c);
396         }
397 }
398
399 void
400 mousemove(GtkWidget *w, GdkEventMotion *e, Client *c) {
401         int result;
402         GdkEventButton coord;
403         WebKitHitTestResult *hit;
404
405         coord.x = e->x;
406         coord.y = e->y;
407         hit = webkit_web_view_get_hit_test_result(c->view, &coord);
408         g_object_get(hit, "context", &result, NULL);
409         if(result & WEBKIT_HIT_TEST_RESULT_CONTEXT_IMAGE && !c->linkhover) {
410                 puts("Picture");
411         }
412 }
413
414 void
415 navigate(Client *c, const Arg *arg) {
416         int steps = *(int *)arg;
417         webkit_web_view_go_back_or_forward(c->view, steps);
418 }
419
420 Client *
421 newclient(void) {
422         Client *c;
423         WebKitWebSettings *settings;
424         WebKitWebFrame *frame;
425         GdkGeometry hints = { 1, 1 };
426         char *uri, *ua;
427
428         if(!(c = calloc(1, sizeof(Client))))
429                 die("Cannot malloc!\n");
430         /* Window */
431         if(embed) {
432                 c->win = gtk_plug_new(embed);
433         }
434         else {
435                 c->win = gtk_window_new(GTK_WINDOW_TOPLEVEL);
436                 /* TA:  20091214:  Despite what the GNOME docs say, the ICCCM
437                  * is always correct, so we should still call this function.
438                  * But when doing so, we *must* differentiate between a
439                  * WM_CLASS and a resource on the window.  By convention, the
440                  * window class (WM_CLASS) is capped, while the resource is in
441                  * lowercase.   Both these values come as a pair.
442                  */
443                 gtk_window_set_wmclass(GTK_WINDOW(c->win), "surf", "surf");
444
445                 /* TA:  20091214:  And set the role here as well -- so that
446                  * sessions can pick this up.
447                  */
448                 gtk_window_set_role(GTK_WINDOW(c->win), "Surf");
449         }
450         gtk_window_set_default_size(GTK_WINDOW(c->win), 800, 600);
451         g_signal_connect(G_OBJECT(c->win), "destroy", G_CALLBACK(destroywin), c);
452         g_signal_connect(G_OBJECT(c->win), "key-press-event", G_CALLBACK(keypress), c);
453         g_signal_connect(G_OBJECT(c->win), "size-allocate", G_CALLBACK(resize), c);
454
455         /* VBox */
456         c->vbox = gtk_vbox_new(FALSE, 0);
457
458         /* Scrolled Window */
459         c->scroll = gtk_scrolled_window_new(NULL, NULL);
460         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(c->scroll),
461                         GTK_POLICY_NEVER, GTK_POLICY_NEVER);
462
463         /* Webview */
464         c->view = WEBKIT_WEB_VIEW(webkit_web_view_new());
465         g_signal_connect(G_OBJECT(c->view), "title-changed", G_CALLBACK(titlechange), c);
466         g_signal_connect(G_OBJECT(c->view), "hovering-over-link", G_CALLBACK(linkhover), c);
467         g_signal_connect(G_OBJECT(c->view), "create-web-view", G_CALLBACK(createwindow), c);
468         g_signal_connect(G_OBJECT(c->view), "new-window-policy-decision-requested", G_CALLBACK(decidewindow), c);
469         g_signal_connect(G_OBJECT(c->view), "mime-type-policy-decision-requested", G_CALLBACK(decidedownload), c);
470         g_signal_connect(G_OBJECT(c->view), "window-object-cleared", G_CALLBACK(windowobjectcleared), c);
471         g_signal_connect(G_OBJECT(c->view), "notify::load-status", G_CALLBACK(loadstatuschange), c);
472         g_signal_connect(G_OBJECT(c->view), "notify::progress", G_CALLBACK(progresschange), c);
473         g_signal_connect(G_OBJECT(c->view), "motion-notify-event", G_CALLBACK(mousemove), c);
474
475         /* Indicator */
476         c->indicator = gtk_drawing_area_new();
477         gtk_widget_set_size_request(c->indicator, 0, 2);
478         g_signal_connect (G_OBJECT (c->indicator), "expose_event",
479                         G_CALLBACK (exposeindicator), c);
480
481         /* Arranging */
482         gtk_container_add(GTK_CONTAINER(c->scroll), GTK_WIDGET(c->view));
483         gtk_container_add(GTK_CONTAINER(c->win), c->vbox);
484         gtk_container_add(GTK_CONTAINER(c->vbox), c->scroll);
485         gtk_container_add(GTK_CONTAINER(c->vbox), c->indicator);
486
487         /* Setup */
488         gtk_box_set_child_packing(GTK_BOX(c->vbox), c->indicator, FALSE, FALSE, 0, GTK_PACK_START);
489         gtk_box_set_child_packing(GTK_BOX(c->vbox), c->scroll, TRUE, TRUE, 0, GTK_PACK_START);
490         gtk_widget_grab_focus(GTK_WIDGET(c->view));
491         gtk_widget_show(c->vbox);
492         gtk_widget_show(c->indicator);
493         gtk_widget_show(c->scroll);
494         gtk_widget_show(GTK_WIDGET(c->view));
495         gtk_widget_show(c->win);
496         gtk_window_set_geometry_hints(GTK_WINDOW(c->win), NULL, &hints, GDK_HINT_MIN_SIZE);
497         gdk_window_set_events(GTK_WIDGET(c->win)->window, GDK_ALL_EVENTS_MASK);
498         gdk_window_add_filter(GTK_WIDGET(c->win)->window, processx, c);
499         webkit_web_view_set_full_content_zoom(c->view, TRUE);
500         frame = webkit_web_view_get_main_frame(c->view);
501         runscript(frame, webkit_web_frame_get_global_context(frame));
502         settings = webkit_web_view_get_settings(c->view);
503         if(!(ua = getenv("SURF_USERAGENT")))
504                 ua = useragent;
505         g_object_set(G_OBJECT(settings), "user-agent", ua, NULL);
506         uri = g_strconcat("file://", stylefile, NULL);
507         g_object_set(G_OBJECT(settings), "user-stylesheet-uri", uri, NULL);
508         g_object_set(G_OBJECT(settings), "auto-load-images", loadimage, NULL);
509         g_object_set(G_OBJECT(settings), "enable-plugins", plugin, NULL);
510         g_object_set(G_OBJECT(settings), "enable-scripts", script, NULL);
511         g_object_set(G_OBJECT(settings), "enable-spatial-navigation", true, NULL);
512         g_free(uri);
513
514         setatom(c, AtomFind, "");
515         setatom(c, AtomUri, "about:blank");
516         setatom(c, AtomHiLight, "about:blank");
517         if(NOBACKGROUND)
518                 webkit_web_view_set_transparent(c->view, TRUE);
519
520         c->title = NULL;
521         c->next = clients;
522         clients = c;
523         if(showxid) {
524                 gdk_display_sync(gtk_widget_get_display(c->win));
525                 printf("%u\n", (guint)GDK_WINDOW_XID(GTK_WIDGET(c->win)->window));
526                 fflush(NULL);
527         }
528         return c;
529 }
530
531 void
532 newrequest(SoupSession *s, SoupMessage *msg, gpointer v) {
533         SoupMessageHeaders *h = msg->request_headers;
534         SoupURI *uri;
535         const char *c;
536
537         soup_message_headers_remove(h, "Cookie");
538         uri = soup_message_get_uri(msg);
539         if((c = getcookies(uri)))
540                 soup_message_headers_append(h, "Cookie", c);
541         g_signal_connect_after(G_OBJECT(msg), "got-headers", G_CALLBACK(gotheaders), NULL);
542 }
543
544 void
545 newwindow(Client *c, const Arg *arg) {
546         guint i = 0;
547         const char *cmd[10], *uri;
548         const Arg a = { .v = (void *)cmd };
549         char tmp[64];
550
551         cmd[i++] = progname;
552         if(embed) {
553                 cmd[i++] = "-e";
554                 snprintf(tmp, LENGTH(tmp), "%u\n", (int)embed);
555                 cmd[i++] = tmp;
556         }
557         if(!script)
558                 cmd[i++] = "-s";
559         if(!plugin)
560                 cmd[i++] = "-p";
561         if(!loadimage)
562                 cmd[i++] = "-i";
563         if(showxid)
564                 cmd[i++] = "-x";
565         cmd[i++] = "--";
566         uri = arg->v ? (char *)arg->v : c->linkhover;
567         if(uri)
568                 cmd[i++] = uri;
569         cmd[i++] = NULL;
570         spawn(NULL, &a);
571 }
572
573 void
574 pasteuri(GtkClipboard *clipboard, const char *text, gpointer d) {
575         Arg arg = {.v = text };
576         if(text != NULL)
577                 loaduri((Client *) d, &arg);
578 }
579
580 void
581 print(Client *c, const Arg *arg) {
582         webkit_web_frame_print(webkit_web_view_get_main_frame(c->view));
583 }
584
585 GdkFilterReturn
586 processx(GdkXEvent *e, GdkEvent *event, gpointer d) {
587         Client *c = (Client *)d;
588         XPropertyEvent *ev;
589         Arg arg;
590
591         if(((XEvent *)e)->type == PropertyNotify) {
592                 ev = &((XEvent *)e)->xproperty;
593                 if(ev->state == PropertyNewValue) {
594                         if(ev->atom == atoms[AtomFind]) {
595                                 arg.b = TRUE;
596                                 find(c, &arg);
597                                 return GDK_FILTER_REMOVE;
598                         }
599                         else if(ev->atom == atoms[AtomGo]) {
600                                 arg.v = getatom(c, AtomGo);
601                                 loaduri(c, &arg);
602                                 return GDK_FILTER_REMOVE;
603                         }
604                 }
605         }
606         return GDK_FILTER_CONTINUE;
607 }
608
609 void
610 progresschange(WebKitWebView *view, GParamSpec *pspec, Client *c) {
611         c->progress = webkit_web_view_get_progress(c->view) * 100;
612         update(c);
613 }
614
615 void
616 reload(Client *c, const Arg *arg) {
617         gboolean nocache = *(gboolean *)arg;
618         if(nocache)
619                  webkit_web_view_reload_bypass_cache(c->view);
620         else
621                  webkit_web_view_reload(c->view);
622 }
623
624 void
625 resize(GtkWidget *w, GtkAllocation *a, Client *c) {
626         double zoom;
627
628         if(c->zoomed)
629                 return;
630         zoom = webkit_web_view_get_zoom_level(c->view);
631         if(a->width * a->height < 300 * 400 && zoom != 0.2)
632                 webkit_web_view_set_zoom_level(c->view, 0.2);
633         else if(zoom != 1.0)
634                 webkit_web_view_set_zoom_level(c->view, 1.0);
635 }
636
637 void
638 scroll(Client *c, const Arg *arg) {
639         gdouble v;
640         GtkAdjustment *a;
641
642         a = gtk_scrolled_window_get_vadjustment(GTK_SCROLLED_WINDOW(c->scroll));
643         v = gtk_adjustment_get_value(a);
644         v += gtk_adjustment_get_step_increment(a) * arg->i;
645         v = MAX(v, 0.0);
646         v = MIN(v, gtk_adjustment_get_upper(a) - gtk_adjustment_get_page_size(a));
647         gtk_adjustment_set_value(a, v);
648 }
649
650 void
651 setcookie(SoupCookie *c) {
652         int lock;
653
654         lock = open(cookiefile, 0);
655         flock(lock, LOCK_EX);
656         SoupDate *e;
657         SoupCookieJar *j = soup_cookie_jar_text_new(cookiefile, FALSE);
658         c = soup_cookie_copy(c);
659         if(c->expires == NULL && sessiontime) {
660                 e = soup_date_new_from_time_t(time(NULL) + sessiontime);
661                 soup_cookie_set_expires(c, e);
662         }
663         soup_cookie_jar_add_cookie(j, c);
664         g_object_unref(j);
665         flock(lock, LOCK_UN);
666         close(lock);
667 }
668
669 void
670 setatom(Client *c, int a, const char *v) {
671         XSync(dpy, False);
672         XChangeProperty(dpy, GDK_WINDOW_XID(GTK_WIDGET(c->win)->window), atoms[a],
673                         XA_STRING, 8, PropModeReplace, (unsigned char *)v,
674                         strlen(v) + 1);
675 }
676
677 void
678 setup(void) {
679         char *proxy;
680         char *new_proxy;
681         SoupURI *puri;
682         SoupSession *s;
683
684         /* clean up any zombies immediately */
685         sigchld(0);
686         gtk_init(NULL, NULL);
687         if (!g_thread_supported())
688                 g_thread_init(NULL);
689
690         dpy = GDK_DISPLAY();
691         s = webkit_get_default_session();
692
693         /* atoms */
694         atoms[AtomFind] = XInternAtom(dpy, "_SURF_FIND", False);
695         atoms[AtomGo] = XInternAtom(dpy, "_SURF_GO", False);
696         atoms[AtomUri] = XInternAtom(dpy, "_SURF_URI", False);
697         atoms[AtomHiLight] = XInternAtom(dpy, "_SURF_HILIGHT", False);
698
699         /* dirs and files */
700         cookiefile = buildpath(cookiefile);
701         scriptfile = buildpath(scriptfile);
702         stylefile = buildpath(stylefile);
703
704         /* request handler */
705         s = webkit_get_default_session();
706         soup_session_remove_feature_by_type(s, soup_cookie_get_type());
707         soup_session_remove_feature_by_type(s, soup_cookie_jar_get_type());
708         g_signal_connect_after(G_OBJECT(s), "request-started", G_CALLBACK(newrequest), NULL);
709
710         /* proxy */
711         if((proxy = getenv("http_proxy")) && strcmp(proxy, "")) {
712                 new_proxy = g_strrstr(proxy, "http://") ? g_strdup(proxy) :
713                         g_strdup_printf("http://%s", proxy);
714                 puri = soup_uri_new(new_proxy);
715                 g_object_set(G_OBJECT(s), "proxy-uri", puri, NULL);
716                 soup_uri_free(puri);
717                 g_free(new_proxy);
718         }
719 }
720
721 void
722 sigchld(int unused) {
723         if(signal(SIGCHLD, sigchld) == SIG_ERR)
724                 die("Can't install SIGCHLD handler");
725         while(0 < waitpid(-1, NULL, WNOHANG));
726 }
727
728 void
729 source(Client *c, const Arg *arg) {
730         Arg a = { .b = FALSE };
731         gboolean s;
732
733         s = webkit_web_view_get_view_source_mode(c->view);
734         webkit_web_view_set_view_source_mode(c->view, !s);
735         reload(c, &a);
736 }
737
738 void
739 spawn(Client *c, const Arg *arg) {
740         if(fork() == 0) {
741                 if(dpy)
742                         close(ConnectionNumber(dpy));
743                 setsid();
744                 execvp(((char **)arg->v)[0], (char **)arg->v);
745                 fprintf(stderr, "surf: execvp %s", ((char **)arg->v)[0]);
746                 perror(" failed");
747                 exit(0);
748         }
749 }
750
751 void
752 stop(Client *c, const Arg *arg) {
753         webkit_web_view_stop_loading(c->view);
754 }
755
756 void
757 titlechange(WebKitWebView *v, WebKitWebFrame *f, const char *t, Client *c) {
758         c->title = copystr(&c->title, t);
759         update(c);
760 }
761
762 void
763 update(Client *c) {
764         char *t;
765
766         if(c->progress != 100) {
767                 t = g_strdup_printf("[%i%%] %s", c->progress, c->title);
768         }
769         else if(c->linkhover)
770                 t = g_strdup(c->linkhover);
771         else
772                 t = g_strdup(c->title);
773         setatom(c, AtomHiLight, c->linkhover ? c->linkhover : geturi(c));
774         drawindicator(c);
775         gtk_window_set_title(GTK_WINDOW(c->win), t);
776         g_free(t);
777 }
778
779 void
780 updatewinid(Client *c) {
781         snprintf(winid, LENGTH(winid), "%u",
782                         (int)GDK_WINDOW_XID(GTK_WIDGET(c->win)->window));
783 }
784
785 void
786 usage(void) {
787         fputs("surf - simple browser\n", stderr);
788         die("usage: surf [-e xid] [-i] [-p] [-s] [-v] [-x] [uri]\n");
789 }
790
791 void
792 windowobjectcleared(GtkWidget *w, WebKitWebFrame *frame, JSContextRef js, JSObjectRef win, Client *c) {
793         runscript(frame, js);
794 }
795
796 void
797 zoom(Client *c, const Arg *arg) {
798         c->zoomed = TRUE;
799         if(arg->i < 0)          /* zoom out */
800                 webkit_web_view_zoom_out(c->view);
801         else if(arg->i > 0)     /* zoom in */
802                 webkit_web_view_zoom_in(c->view);
803         else {                  /* reset */
804                 c->zoomed = FALSE;
805                 webkit_web_view_set_zoom_level(c->view, 1.0);
806         }
807 }
808
809 int
810 main(int argc, char *argv[]) {
811         int i;
812         Arg arg;
813
814         progname = argv[0];
815         /* command line args */
816         for(i = 1, arg.v = NULL; i < argc && argv[i][0] == '-' &&
817                         argv[i][1] != '\0' && argv[i][2] == '\0'; i++) {
818                 if(!strcmp(argv[i], "--")) {
819                         i++;
820                         break;
821                 }
822                 switch(argv[i][1]) {
823                 case 'e':
824                         if(++i < argc)
825                                 embed = atoi(argv[i]);
826                         else
827                                 usage();
828                         break;
829                 case 'i':
830                         loadimage = 0;
831                         break;
832                 case 'p':
833                         plugin = 0;
834                         break;
835                 case 's':
836                         script = 0;
837                         break;
838                 case 'x':
839                         showxid = TRUE;
840                         break;
841                 case 'v':
842                         die("surf-"VERSION", © 2009 surf engineers, see LICENSE for details\n");
843                 default:
844                         usage();
845                 }
846         }
847         if(i < argc)
848                 arg.v = argv[i];
849         setup();
850         newclient();
851         if(arg.v)
852                 loaduri(clients, &arg);
853         gtk_main();
854         cleanup();
855         return EXIT_SUCCESS;
856 }