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