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