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