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