Fixing the shift key mask and cleaning up the scrolling code.
[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 & (ShiftMask|ControlMask|Mod1Mask|Mod2Mask|Mod3Mask|Mod4Mask|Mod5Mask))
25
26 enum { AtomFind, AtomGo, AtomUri, AtomLast };
27
28 typedef union Arg Arg;
29 union Arg {
30         gboolean b;
31         gint i;
32         const void *v;
33 };
34
35 typedef struct Client {
36         GtkWidget *win, *scroll, *vbox, *indicator;
37         WebKitWebView *view;
38         char *title, *linkhover;
39         const char *uri, *needle;
40         gint progress;
41         gboolean sslfailed;
42         struct Client *next;
43         gboolean zoomed;
44 } Client;
45
46 typedef struct {
47         char *label;
48         void (*func)(Client *c, const Arg *arg);
49         const Arg arg;
50 } Item;
51
52 typedef struct {
53         guint mod;
54         guint keyval;
55         void (*func)(Client *c, const Arg *arg);
56         const Arg arg;
57 } Key;
58
59 static Display *dpy;
60 static Atom atoms[AtomLast];
61 static Client *clients = NULL;
62 static GdkNativeWindow embed = 0;
63 static gboolean showxid = FALSE;
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 char *copystr(char **str, const char *src);
72 static WebKitWebView *createwindow(WebKitWebView *v, WebKitWebFrame *f, Client *c);
73 static gboolean decidedownload(WebKitWebView *v, WebKitWebFrame *f, WebKitNetworkRequest *r, gchar *m,  WebKitWebPolicyDecision *p, Client *c);
74 static gboolean decidewindow(WebKitWebView *v, WebKitWebFrame *f, WebKitNetworkRequest *r, WebKitWebNavigationAction *n, WebKitWebPolicyDecision *p, Client *c);
75 static void destroyclient(Client *c);
76 static void destroywin(GtkWidget* w, Client *c);
77 static void die(char *str);
78 static void drawindicator(Client *c);
79 static gboolean exposeindicator(GtkWidget *w, GdkEventExpose *e, Client *c);
80 static void find(Client *c, const Arg *arg);
81 static const char *getatom(Client *c, int a);
82 static const char *getcookies(SoupURI *uri);
83 static char *geturi(Client *c);
84 void gotheaders(SoupMessage *msg, gpointer user_data);
85 static gboolean initdownload(WebKitWebView *v, WebKitDownload *o, Client *c);
86 static gboolean keypress(GtkWidget *w, GdkEventKey *ev, Client *c);
87 static void linkhover(WebKitWebView *v, const char* t, const char* l, Client *c);
88 static void loadstatuschange(WebKitWebView *view, GParamSpec *pspec, Client *c);
89 static void loaduri(Client *c, const Arg *arg);
90 static void navigate(Client *c, const Arg *arg);
91 static Client *newclient(void);
92 static void newwindow(Client *c, const Arg *arg);
93 static void newrequest(SoupSession *s, SoupMessage *msg, gpointer v);
94 static void pasteuri(GtkClipboard *clipboard, const char *text, gpointer d);
95 static void print(Client *c, const Arg *arg);
96 static GdkFilterReturn processx(GdkXEvent *xevent, GdkEvent *event, gpointer d);
97 static void progresschange(WebKitWebView *view, GParamSpec *pspec, Client *c);
98 static void reload(Client *c, const Arg *arg);
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(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) {
167         char *script;
168         GError *error;
169
170         if(g_file_get_contents(scriptfile, &script, NULL, &error)) {
171                 evalscript(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         GSList *l, *p;
338
339         for(p = l = soup_cookies_from_response(msg); p;
340                 p = g_slist_next(p))  {
341                 setcookie((SoupCookie *)p->data);
342         }
343         soup_cookies_free(l);
344 }
345
346 gboolean
347 initdownload(WebKitWebView *view, WebKitDownload *o, Client *c) {
348         Arg arg;
349
350         updatewinid(c);
351         arg = (Arg)DOWNLOAD((char *)webkit_download_get_uri(o));
352         spawn(c, &arg);
353         return FALSE;
354 }
355
356 gboolean
357 keypress(GtkWidget* w, GdkEventKey *ev, Client *c) {
358         guint i;
359         gboolean processed = FALSE;
360
361         updatewinid(c);
362         for(i = 0; i < LENGTH(keys); i++) {
363                 if(gdk_keyval_to_lower(ev->keyval) == keys[i].keyval
364                                 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state)
365                                 && keys[i].func) {
366                         keys[i].func(c, &(keys[i].arg));
367                         processed = TRUE;
368                 }
369         }
370         return processed;
371 }
372
373 void
374 linkhover(WebKitWebView *v, const char* t, const char* l, Client *c) {
375         if(l) {
376                 c->linkhover = copystr(&c->linkhover, l);
377         }
378         else if(c->linkhover) {
379                 free(c->linkhover);
380                 c->linkhover = NULL;
381         }
382         update(c);
383 }
384
385 void
386 loadstatuschange(WebKitWebView *view, GParamSpec *pspec, Client *c) {
387         WebKitWebFrame *frame;
388         WebKitWebDataSource *src;
389         WebKitNetworkRequest *request;
390         SoupMessage *msg;
391         char *uri;
392
393         switch(webkit_web_view_get_load_status (c->view)) {
394         case WEBKIT_LOAD_COMMITTED:
395                 uri = geturi(c);
396                 if(strstr(uri, "https://") == uri) {
397                         frame = webkit_web_view_get_main_frame(c->view);
398                         src = webkit_web_frame_get_data_source(frame);
399                         request = webkit_web_data_source_get_request(src);
400                         msg = webkit_network_request_get_message(request);
401                         c->sslfailed = soup_message_get_flags(msg)
402                                        ^ SOUP_MESSAGE_CERTIFICATE_TRUSTED;
403                 }
404                 setatom(c, AtomUri, uri);
405                 break;
406         case WEBKIT_LOAD_FINISHED:
407                 c->progress = 0;
408                 update(c);
409                 break;
410         default:
411                 break;
412         }
413 }
414
415 void
416 loaduri(Client *c, const Arg *arg) {
417         char *u;
418         const char *uri = (char *)arg->v;
419         Arg a = { .b = FALSE };
420
421         if(strcmp(uri, "") == 0)
422                 return;
423         u = g_strrstr(uri, "://") ? g_strdup(uri)
424                 : g_strdup_printf("http://%s", uri);
425         /* prevents endless loop */
426         if(c->uri && strcmp(u, c->uri) == 0) {
427                 reload(c, &a);
428         }
429         else {
430                 webkit_web_view_load_uri(c->view, u);
431                 c->progress = 0;
432                 c->title = copystr(&c->title, u);
433                 g_free(u);
434                 update(c);
435         }
436 }
437
438 void
439 navigate(Client *c, const Arg *arg) {
440         int steps = *(int *)arg;
441         webkit_web_view_go_back_or_forward(c->view, steps);
442 }
443
444 Client *
445 newclient(void) {
446         Client *c;
447         WebKitWebSettings *settings;
448         WebKitWebFrame *frame;
449         GdkGeometry hints = { 1, 1 };
450         char *uri, *ua;
451
452         if(!(c = calloc(1, sizeof(Client))))
453                 die("Cannot malloc!\n");
454         /* Window */
455         if(embed) {
456                 c->win = gtk_plug_new(embed);
457         }
458         else {
459                 c->win = gtk_window_new(GTK_WINDOW_TOPLEVEL);
460                 /* TA:  20091214:  Despite what the GNOME docs say, the ICCCM
461                  * is always correct, so we should still call this function.
462                  * But when doing so, we *must* differentiate between a
463                  * WM_CLASS and a resource on the window.  By convention, the
464                  * window class (WM_CLASS) is capped, while the resource is in
465                  * lowercase.   Both these values come as a pair.
466                  */
467                 gtk_window_set_wmclass(GTK_WINDOW(c->win), "surf", "Surf");
468
469                 /* TA:  20091214:  And set the role here as well -- so that
470                  * sessions can pick this up.
471                  */
472                 gtk_window_set_role(GTK_WINDOW(c->win), "Surf");
473         }
474         gtk_window_set_default_size(GTK_WINDOW(c->win), 800, 600);
475         g_signal_connect(G_OBJECT(c->win), "destroy", G_CALLBACK(destroywin), c);
476         g_signal_connect(G_OBJECT(c->win), "key-press-event", G_CALLBACK(keypress), c);
477
478         /* VBox */
479         c->vbox = gtk_vbox_new(FALSE, 0);
480
481         /* Scrolled Window */
482         c->scroll = gtk_scrolled_window_new(NULL, NULL);
483         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(c->scroll),
484                         GTK_POLICY_NEVER, GTK_POLICY_NEVER);
485
486         /* Webview */
487         c->view = WEBKIT_WEB_VIEW(webkit_web_view_new());
488         g_signal_connect(G_OBJECT(c->view), "title-changed", G_CALLBACK(titlechange), c);
489         g_signal_connect(G_OBJECT(c->view), "hovering-over-link", G_CALLBACK(linkhover), c);
490         g_signal_connect(G_OBJECT(c->view), "create-web-view", G_CALLBACK(createwindow), c);
491         g_signal_connect(G_OBJECT(c->view), "new-window-policy-decision-requested", G_CALLBACK(decidewindow), c);
492         g_signal_connect(G_OBJECT(c->view), "mime-type-policy-decision-requested", G_CALLBACK(decidedownload), c);
493         g_signal_connect(G_OBJECT(c->view), "window-object-cleared", G_CALLBACK(windowobjectcleared), c);
494         g_signal_connect(G_OBJECT(c->view), "notify::load-status", G_CALLBACK(loadstatuschange), c);
495         g_signal_connect(G_OBJECT(c->view), "notify::progress", G_CALLBACK(progresschange), c);
496         g_signal_connect(G_OBJECT(c->view), "download-requested", G_CALLBACK(initdownload), c);
497
498         /* Indicator */
499         c->indicator = gtk_drawing_area_new();
500         gtk_widget_set_size_request(c->indicator, 0, 2);
501         g_signal_connect (G_OBJECT (c->indicator), "expose_event",
502                         G_CALLBACK (exposeindicator), c);
503
504         /* Arranging */
505         gtk_container_add(GTK_CONTAINER(c->scroll), GTK_WIDGET(c->view));
506         gtk_container_add(GTK_CONTAINER(c->win), c->vbox);
507         gtk_container_add(GTK_CONTAINER(c->vbox), c->scroll);
508         gtk_container_add(GTK_CONTAINER(c->vbox), c->indicator);
509
510         /* Setup */
511         gtk_box_set_child_packing(GTK_BOX(c->vbox), c->indicator, FALSE, FALSE, 0, GTK_PACK_START);
512         gtk_box_set_child_packing(GTK_BOX(c->vbox), c->scroll, TRUE, TRUE, 0, GTK_PACK_START);
513         gtk_widget_grab_focus(GTK_WIDGET(c->view));
514         gtk_widget_show(c->vbox);
515         gtk_widget_show(c->indicator);
516         gtk_widget_show(c->scroll);
517         gtk_widget_show(GTK_WIDGET(c->view));
518         gtk_widget_show(c->win);
519         gtk_window_set_geometry_hints(GTK_WINDOW(c->win), NULL, &hints, GDK_HINT_MIN_SIZE);
520         gdk_window_set_events(GTK_WIDGET(c->win)->window, GDK_ALL_EVENTS_MASK);
521         gdk_window_add_filter(GTK_WIDGET(c->win)->window, processx, c);
522         webkit_web_view_set_full_content_zoom(c->view, TRUE);
523         frame = webkit_web_view_get_main_frame(c->view);
524         runscript(frame);
525         settings = webkit_web_view_get_settings(c->view);
526         if(!(ua = getenv("SURF_USERAGENT")))
527                 ua = useragent;
528         g_object_set(G_OBJECT(settings), "user-agent", ua, NULL);
529         uri = g_strconcat("file://", stylefile, NULL);
530         g_object_set(G_OBJECT(settings), "user-stylesheet-uri", uri, NULL);
531         g_object_set(G_OBJECT(settings), "auto-load-images", loadimage, NULL);
532         g_object_set(G_OBJECT(settings), "enable-plugins", plugin, NULL);
533         g_object_set(G_OBJECT(settings), "enable-scripts", script, NULL);
534         g_object_set(G_OBJECT(settings), "enable-spatial-navigation", SPATIAL_BROWSING, NULL);
535
536         g_free(uri);
537
538         setatom(c, AtomFind, "");
539         setatom(c, AtomUri, "about:blank");
540         if(HIDE_BACKGROUND)
541                 webkit_web_view_set_transparent(c->view, TRUE);
542
543         c->title = NULL;
544         c->next = clients;
545         clients = c;
546         if(showxid) {
547                 gdk_display_sync(gtk_widget_get_display(c->win));
548                 printf("%u\n", (guint)GDK_WINDOW_XID(GTK_WIDGET(c->win)->window));
549                 fflush(NULL);
550                 if (fclose(stdout) != 0) {
551                         die("Error closing stdout");
552                 }
553         }
554         return c;
555 }
556
557 void
558 newrequest(SoupSession *s, SoupMessage *msg, gpointer v) {
559         SoupMessageHeaders *h = msg->request_headers;
560         SoupURI *uri;
561         const char *c;
562
563         soup_message_headers_remove(h, "Cookie");
564         uri = soup_message_get_uri(msg);
565         if((c = getcookies(uri)))
566                 soup_message_headers_append(h, "Cookie", c);
567         g_signal_connect_after(G_OBJECT(msg), "got-headers", G_CALLBACK(gotheaders), NULL);
568 }
569
570 void
571 newwindow(Client *c, const Arg *arg) {
572         guint i = 0;
573         const char *cmd[10], *uri;
574         const Arg a = { .v = (void *)cmd };
575         char tmp[64];
576
577         cmd[i++] = progname;
578         if(embed) {
579                 cmd[i++] = "-e";
580                 snprintf(tmp, LENGTH(tmp), "%u\n", (int)embed);
581                 cmd[i++] = tmp;
582         }
583         if(!script)
584                 cmd[i++] = "-s";
585         if(!plugin)
586                 cmd[i++] = "-p";
587         if(!loadimage)
588                 cmd[i++] = "-i";
589         if(showxid)
590                 cmd[i++] = "-x";
591         cmd[i++] = "--";
592         uri = arg->v ? (char *)arg->v : c->linkhover;
593         if(uri)
594                 cmd[i++] = uri;
595         cmd[i++] = NULL;
596         spawn(NULL, &a);
597 }
598
599 void
600 pasteuri(GtkClipboard *clipboard, const char *text, gpointer d) {
601         Arg arg = {.v = text };
602         if(text != NULL)
603                 loaduri((Client *) d, &arg);
604 }
605
606 void
607 print(Client *c, const Arg *arg) {
608         webkit_web_frame_print(webkit_web_view_get_main_frame(c->view));
609 }
610
611 GdkFilterReturn
612 processx(GdkXEvent *e, GdkEvent *event, gpointer d) {
613         Client *c = (Client *)d;
614         XPropertyEvent *ev;
615         Arg arg;
616
617         if(((XEvent *)e)->type == PropertyNotify) {
618                 ev = &((XEvent *)e)->xproperty;
619                 if(ev->state == PropertyNewValue) {
620                         if(ev->atom == atoms[AtomFind]) {
621                                 arg.b = TRUE;
622                                 find(c, &arg);
623                                 return GDK_FILTER_REMOVE;
624                         }
625                         else if(ev->atom == atoms[AtomGo]) {
626                                 arg.v = getatom(c, AtomGo);
627                                 loaduri(c, &arg);
628                                 return GDK_FILTER_REMOVE;
629                         }
630                 }
631         }
632         return GDK_FILTER_CONTINUE;
633 }
634
635 void
636 progresschange(WebKitWebView *view, GParamSpec *pspec, Client *c) {
637         c->progress = webkit_web_view_get_progress(c->view) * 100;
638         update(c);
639 }
640
641 void
642 reload(Client *c, const Arg *arg) {
643         gboolean nocache = *(gboolean *)arg;
644         if(nocache)
645                  webkit_web_view_reload_bypass_cache(c->view);
646         else
647                  webkit_web_view_reload(c->view);
648 }
649
650 void
651 scroll_h(Client *c, const Arg *arg) {
652         scroll(gtk_scrolled_window_get_hadjustment(
653                                 GTK_SCROLLED_WINDOW(c->scroll)), arg);
654 }
655
656 void
657 scroll_v(Client *c, const Arg *arg) {
658         scroll(gtk_scrolled_window_get_vadjustment(
659                                 GTK_SCROLLED_WINDOW(c->scroll)), arg);
660 }
661
662 void
663 scroll(GtkAdjustment *a, const Arg *arg) {
664         gdouble v;
665
666         v = gtk_adjustment_get_value(a);
667         switch (arg->i){
668         case +10000:
669         case -10000:
670                 v += gtk_adjustment_get_page_increment(a) *
671                         (arg->i / 10000);
672                 break;
673         case +20000:
674         case -20000:
675         default:
676                 v += gtk_adjustment_get_step_increment(a) * arg->i;
677         }
678
679         v = MAX(v, 0.0);
680         v = MIN(v, gtk_adjustment_get_upper(a) -
681                         gtk_adjustment_get_page_size(a));
682         gtk_adjustment_set_value(a, v);
683 }
684
685 void
686 setcookie(SoupCookie *c) {
687         int lock;
688
689         lock = open(cookiefile, 0);
690         flock(lock, LOCK_EX);
691         SoupDate *e;
692         SoupCookieJar *j = soup_cookie_jar_text_new(cookiefile, FALSE);
693         c = soup_cookie_copy(c);
694         if(c->expires == NULL && sessiontime) {
695                 e = soup_date_new_from_time_t(time(NULL) + sessiontime);
696                 soup_cookie_set_expires(c, e);
697         }
698         soup_cookie_jar_add_cookie(j, c);
699         g_object_unref(j);
700         flock(lock, LOCK_UN);
701         close(lock);
702 }
703
704 void
705 setatom(Client *c, int a, const char *v) {
706         XSync(dpy, False);
707         XChangeProperty(dpy, GDK_WINDOW_XID(GTK_WIDGET(c->win)->window), atoms[a],
708                         XA_STRING, 8, PropModeReplace, (unsigned char *)v,
709                         strlen(v) + 1);
710 }
711
712 void
713 setup(void) {
714         char *proxy;
715         char *new_proxy;
716         SoupURI *puri;
717         SoupSession *s;
718
719         /* clean up any zombies immediately */
720         sigchld(0);
721         gtk_init(NULL, NULL);
722         if (!g_thread_supported())
723                 g_thread_init(NULL);
724
725         dpy = GDK_DISPLAY();
726         s = webkit_get_default_session();
727
728         /* atoms */
729         atoms[AtomFind] = XInternAtom(dpy, "_SURF_FIND", False);
730         atoms[AtomGo] = XInternAtom(dpy, "_SURF_GO", False);
731         atoms[AtomUri] = XInternAtom(dpy, "_SURF_URI", False);
732
733         /* dirs and files */
734         cookiefile = buildpath(cookiefile);
735         scriptfile = buildpath(scriptfile);
736         stylefile = buildpath(stylefile);
737
738         /* request handler */
739         s = webkit_get_default_session();
740         soup_session_remove_feature_by_type(s, soup_cookie_get_type());
741         soup_session_remove_feature_by_type(s, soup_cookie_jar_get_type());
742         g_signal_connect_after(G_OBJECT(s), "request-started", G_CALLBACK(newrequest), NULL);
743
744         /* ssl */
745         g_object_set(G_OBJECT(s), "ssl-ca-file", cafile, NULL);
746         g_object_set(G_OBJECT(s), "ssl-strict", strictssl, NULL);
747
748         /* proxy */
749         if((proxy = getenv("http_proxy")) && strcmp(proxy, "")) {
750                 new_proxy = g_strrstr(proxy, "http://") ? g_strdup(proxy) :
751                         g_strdup_printf("http://%s", proxy);
752                 puri = soup_uri_new(new_proxy);
753                 g_object_set(G_OBJECT(s), "proxy-uri", puri, NULL);
754                 soup_uri_free(puri);
755                 g_free(new_proxy);
756         }
757 }
758
759 void
760 sigchld(int unused) {
761         if(signal(SIGCHLD, sigchld) == SIG_ERR)
762                 die("Can't install SIGCHLD handler");
763         while(0 < waitpid(-1, NULL, WNOHANG));
764 }
765
766 void
767 source(Client *c, const Arg *arg) {
768         Arg a = { .b = FALSE };
769         gboolean s;
770
771         s = webkit_web_view_get_view_source_mode(c->view);
772         webkit_web_view_set_view_source_mode(c->view, !s);
773         reload(c, &a);
774 }
775
776 void
777 spawn(Client *c, const Arg *arg) {
778         if(fork() == 0) {
779                 if(dpy)
780                         close(ConnectionNumber(dpy));
781                 setsid();
782                 execvp(((char **)arg->v)[0], (char **)arg->v);
783                 fprintf(stderr, "surf: execvp %s", ((char **)arg->v)[0]);
784                 perror(" failed");
785                 exit(0);
786         }
787 }
788
789 void
790 eval(Client *c, const Arg *arg) {
791         WebKitWebFrame *frame = webkit_web_view_get_main_frame(c->view);
792         evalscript(webkit_web_frame_get_global_context(frame),
793                         ((char **)arg->v)[0], "");
794 }
795
796 void
797 stop(Client *c, const Arg *arg) {
798         webkit_web_view_stop_loading(c->view);
799 }
800
801 void
802 titlechange(WebKitWebView *v, WebKitWebFrame *f, const char *t, Client *c) {
803         c->title = copystr(&c->title, t);
804         update(c);
805 }
806
807 void
808 update(Client *c) {
809         char *t;
810
811         if(c->linkhover)
812                 t = g_strdup(c->linkhover);
813         else if(c->progress != 100)
814                 t = g_strdup_printf("[%i%%] %s", c->progress, c->title);
815         else
816                 t = g_strdup(c->title);
817         drawindicator(c);
818         gtk_window_set_title(GTK_WINDOW(c->win), t);
819         g_free(t);
820 }
821
822 void
823 updatewinid(Client *c) {
824         snprintf(winid, LENGTH(winid), "%u",
825                         (int)GDK_WINDOW_XID(GTK_WIDGET(c->win)->window));
826 }
827
828 void
829 usage(void) {
830         fputs("surf - simple browser\n", stderr);
831         die("usage: surf [-e xid] [-i] [-p] [-s] [-v] [-x] [uri]\n");
832 }
833
834 void
835 windowobjectcleared(GtkWidget *w, WebKitWebFrame *frame, JSContextRef js, JSObjectRef win, Client *c) {
836         runscript(frame);
837 }
838
839 void
840 zoom(Client *c, const Arg *arg) {
841         c->zoomed = TRUE;
842         if(arg->i < 0)          /* zoom out */
843                 webkit_web_view_zoom_out(c->view);
844         else if(arg->i > 0)     /* zoom in */
845                 webkit_web_view_zoom_in(c->view);
846         else {                  /* reset */
847                 c->zoomed = FALSE;
848                 webkit_web_view_set_zoom_level(c->view, 1.0);
849         }
850 }
851
852 int
853 main(int argc, char *argv[]) {
854         int i;
855         Arg arg;
856
857         progname = argv[0];
858         /* command line args */
859         for(i = 1, arg.v = NULL; i < argc && argv[i][0] == '-' &&
860                         argv[i][1] != '\0' && argv[i][2] == '\0'; i++) {
861                 if(!strcmp(argv[i], "--")) {
862                         i++;
863                         break;
864                 }
865                 switch(argv[i][1]) {
866                 case 'e':
867                         if(++i < argc)
868                                 embed = strtol(argv[i], NULL, 0);
869                         else
870                                 usage();
871                         break;
872                 case 'i':
873                         loadimage = 0;
874                         break;
875                 case 'p':
876                         plugin = 0;
877                         break;
878                 case 's':
879                         script = 0;
880                         break;
881                 case 'x':
882                         showxid = TRUE;
883                         break;
884                 case 'v':
885                         die("surf-"VERSION", ©2009-2012 surf engineers, see LICENSE for details\n");
886                 default:
887                         usage();
888                 }
889         }
890         if(i < argc)
891                 arg.v = argv[i];
892         setup();
893         newclient();
894         if(arg.v)
895                 loaduri(clients, &arg);
896         gtk_main();
897         cleanup();
898         return EXIT_SUCCESS;
899 }