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