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