27cc4e945a6d531c56fbf2333630ec3c6bf59bca
[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, 0700);
131                 g_chmod(apath, 0700); /* in case it existed */
132                 *p = '/';
133         }
134         /* creating file (gives error when apath ends with "/") */
135         if((f = fopen(apath, "a"))) {
136                 g_chmod(apath, 0600); /* always */
137                 fclose(f);
138         }
139         return apath;
140 }
141
142 void
143 cleanup(void) {
144         while(clients)
145                 destroyclient(clients);
146         g_free(cookiefile);
147         g_free(scriptfile);
148         g_free(stylefile);
149 }
150
151 void
152 evalscript(WebKitWebFrame *frame, JSContextRef js, char *script, char* scriptname) {
153         JSStringRef jsscript, jsscriptname;
154         JSValueRef exception = NULL;
155
156         jsscript = JSStringCreateWithUTF8CString(script);
157         jsscriptname = JSStringCreateWithUTF8CString(scriptname);
158         JSEvaluateScript(js, jsscript, JSContextGetGlobalObject(js), jsscriptname, 0, &exception);
159         JSStringRelease(jsscript);
160         JSStringRelease(jsscriptname);
161 }
162
163 void
164 runscript(WebKitWebFrame *frame, JSContextRef js) {
165         char *script;
166         GError *error;
167
168         if(g_file_get_contents(scriptfile, &script, NULL, &error)) {
169                 evalscript(frame, webkit_web_frame_get_global_context(frame), script, scriptfile);
170         }
171 }
172
173 void
174 clipboard(Client *c, const Arg *arg) {
175         gboolean paste = *(gboolean *)arg;
176
177         if(paste)
178                 gtk_clipboard_request_text(gtk_clipboard_get(GDK_SELECTION_PRIMARY), pasteuri, c);
179         else
180                 gtk_clipboard_set_text(gtk_clipboard_get(GDK_SELECTION_PRIMARY), c->linkhover ? c->linkhover : geturi(c), -1);
181 }
182
183 char *
184 copystr(char **str, const char *src) {
185         char *tmp;
186         tmp = g_strdup(src);
187
188         if(str && *str) {
189                 g_free(*str);
190                 *str = tmp;
191         }
192         return tmp;
193 }
194
195 WebKitWebView *
196 createwindow(WebKitWebView  *v, WebKitWebFrame *f, Client *c) {
197         Client *n = newclient();
198         return n->view;
199 }
200
201 gboolean
202 decidedownload(WebKitWebView *v, WebKitWebFrame *f, WebKitNetworkRequest *r, gchar *m,  WebKitWebPolicyDecision *p, Client *c) {
203         if(!webkit_web_view_can_show_mime_type(v, m)) {
204                 webkit_web_policy_decision_download(p);
205                 return TRUE;
206         }
207         return FALSE;
208 }
209
210 gboolean
211 decidewindow(WebKitWebView *view, WebKitWebFrame *f, WebKitNetworkRequest *r, WebKitWebNavigationAction *n, WebKitWebPolicyDecision *p, Client *c) {
212         Arg arg;
213
214         if(webkit_web_navigation_action_get_reason(n) == WEBKIT_WEB_NAVIGATION_REASON_LINK_CLICKED) {
215                 webkit_web_policy_decision_ignore(p);
216                 arg.v = (void *)webkit_network_request_get_uri(r);
217                 newwindow(NULL, &arg);
218                 return TRUE;
219         }
220         return FALSE;
221 }
222
223 void
224 destroyclient(Client *c) {
225         Client *p;
226
227         webkit_web_view_stop_loading(c->view);
228         gtk_widget_destroy(c->indicator);
229         gtk_widget_destroy(GTK_WIDGET(c->view));
230         gtk_widget_destroy(c->scroll);
231         gtk_widget_destroy(c->vbox);
232         gtk_widget_destroy(c->win);
233
234         for(p = clients; p && p->next != c; p = p->next);
235         if(p)
236                 p->next = c->next;
237         else
238                 clients = c->next;
239         free(c);
240         if(clients == NULL)
241                 gtk_main_quit();
242 }
243
244 void
245 destroywin(GtkWidget* w, Client *c) {
246         destroyclient(c);
247 }
248
249 void
250 die(char *str) {
251         fputs(str, stderr);
252         exit(EXIT_FAILURE);
253 }
254
255 void
256 drawindicator(Client *c) {
257         gint width;
258         const char *uri;
259         GtkWidget *w;
260         GdkGC *gc;
261         GdkColor fg;
262
263         uri = geturi(c);
264         w = c->indicator;
265         width = c->progress * w->allocation.width / 100;
266         gc = gdk_gc_new(w->window);
267         if(strstr(uri, "https://") == uri)
268                 gdk_color_parse(c->sslfailed ?
269                                 progress_untrust : progress_trust, &fg);
270         else
271                 gdk_color_parse(progress, &fg);
272         gdk_gc_set_rgb_fg_color(gc, &fg);
273         gdk_draw_rectangle(w->window,
274                         w->style->bg_gc[GTK_WIDGET_STATE(w)],
275                         TRUE, 0, 0, w->allocation.width, w->allocation.height);
276         gdk_draw_rectangle(w->window, gc, TRUE, 0, 0, width,
277                         w->allocation.height);
278         g_object_unref(gc);
279 }
280
281 gboolean
282 exposeindicator(GtkWidget *w, GdkEventExpose *e, Client *c) {
283         drawindicator(c);
284         return TRUE;
285 }
286
287 void
288 find(Client *c, const Arg *arg) {
289         const char *s;
290
291         s = getatom(c, AtomFind);
292         gboolean forward = *(gboolean *)arg;
293         webkit_web_view_search_text(c->view, s, FALSE, forward, TRUE);
294 }
295
296 const char *
297 getcookies(SoupURI *uri) {
298         const char *c;
299         SoupCookieJar *j = soup_cookie_jar_text_new(cookiefile, TRUE);
300         c = soup_cookie_jar_get_cookies(j, uri, TRUE);
301         g_object_unref(j);
302         return c;
303 }
304
305 const char *
306 getatom(Client *c, int a) {
307         static char buf[BUFSIZ];
308         Atom adummy;
309         int idummy;
310         unsigned long ldummy;
311         unsigned char *p = NULL;
312
313         XGetWindowProperty(dpy, GDK_WINDOW_XID(GTK_WIDGET(c->win)->window),
314                         atoms[a], 0L, BUFSIZ, False, XA_STRING,
315                         &adummy, &idummy, &ldummy, &ldummy, &p);
316         if(p)
317                 strncpy(buf, (char *)p, LENGTH(buf)-1);
318         else
319                 buf[0] = '\0';
320         XFree(p);
321         return buf;
322 }
323
324 char *
325 geturi(Client *c) {
326         char *uri;
327
328         if(!(uri = (char *)webkit_web_view_get_uri(c->view)))
329                 uri = "about:blank";
330         return uri;
331 }
332
333 void
334 gotheaders(SoupMessage *msg, gpointer v) {
335         SoupURI *uri;
336         GSList *l, *p;
337
338         uri = soup_message_get_uri(msg);
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                                 && (ev->state & keys[i].mod) == keys[i].mod
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         g_signal_connect(G_OBJECT(c->win), "size-allocate", G_CALLBACK(resize), c);
478
479         /* VBox */
480         c->vbox = gtk_vbox_new(FALSE, 0);
481
482         /* Scrolled Window */
483         c->scroll = gtk_scrolled_window_new(NULL, NULL);
484         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(c->scroll),
485                         GTK_POLICY_NEVER, GTK_POLICY_NEVER);
486
487         /* Webview */
488         c->view = WEBKIT_WEB_VIEW(webkit_web_view_new());
489         g_signal_connect(G_OBJECT(c->view), "title-changed", G_CALLBACK(titlechange), c);
490         g_signal_connect(G_OBJECT(c->view), "hovering-over-link", G_CALLBACK(linkhover), c);
491         g_signal_connect(G_OBJECT(c->view), "create-web-view", G_CALLBACK(createwindow), c);
492         g_signal_connect(G_OBJECT(c->view), "new-window-policy-decision-requested", G_CALLBACK(decidewindow), c);
493         g_signal_connect(G_OBJECT(c->view), "mime-type-policy-decision-requested", G_CALLBACK(decidedownload), c);
494         g_signal_connect(G_OBJECT(c->view), "window-object-cleared", G_CALLBACK(windowobjectcleared), c);
495         g_signal_connect(G_OBJECT(c->view), "notify::load-status", G_CALLBACK(loadstatuschange), c);
496         g_signal_connect(G_OBJECT(c->view), "notify::progress", G_CALLBACK(progresschange), c);
497         g_signal_connect(G_OBJECT(c->view), "download-requested", G_CALLBACK(initdownload), c);
498
499         /* Indicator */
500         c->indicator = gtk_drawing_area_new();
501         gtk_widget_set_size_request(c->indicator, 0, 2);
502         g_signal_connect (G_OBJECT (c->indicator), "expose_event",
503                         G_CALLBACK (exposeindicator), c);
504
505         /* Arranging */
506         gtk_container_add(GTK_CONTAINER(c->scroll), GTK_WIDGET(c->view));
507         gtk_container_add(GTK_CONTAINER(c->win), c->vbox);
508         gtk_container_add(GTK_CONTAINER(c->vbox), c->scroll);
509         gtk_container_add(GTK_CONTAINER(c->vbox), c->indicator);
510
511         /* Setup */
512         gtk_box_set_child_packing(GTK_BOX(c->vbox), c->indicator, FALSE, FALSE, 0, GTK_PACK_START);
513         gtk_box_set_child_packing(GTK_BOX(c->vbox), c->scroll, TRUE, TRUE, 0, GTK_PACK_START);
514         gtk_widget_grab_focus(GTK_WIDGET(c->view));
515         gtk_widget_show(c->vbox);
516         gtk_widget_show(c->indicator);
517         gtk_widget_show(c->scroll);
518         gtk_widget_show(GTK_WIDGET(c->view));
519         gtk_widget_show(c->win);
520         gtk_window_set_geometry_hints(GTK_WINDOW(c->win), NULL, &hints, GDK_HINT_MIN_SIZE);
521         gdk_window_set_events(GTK_WIDGET(c->win)->window, GDK_ALL_EVENTS_MASK);
522         gdk_window_add_filter(GTK_WIDGET(c->win)->window, processx, c);
523         webkit_web_view_set_full_content_zoom(c->view, TRUE);
524         frame = webkit_web_view_get_main_frame(c->view);
525         runscript(frame, webkit_web_frame_get_global_context(frame));
526         settings = webkit_web_view_get_settings(c->view);
527         if(!(ua = getenv("SURF_USERAGENT")))
528                 ua = useragent;
529         g_object_set(G_OBJECT(settings), "user-agent", ua, NULL);
530         uri = g_strconcat("file://", stylefile, NULL);
531         g_object_set(G_OBJECT(settings), "user-stylesheet-uri", uri, NULL);
532         g_object_set(G_OBJECT(settings), "auto-load-images", loadimage, NULL);
533         g_object_set(G_OBJECT(settings), "enable-plugins", plugin, NULL);
534         g_object_set(G_OBJECT(settings), "enable-scripts", script, NULL);
535         g_object_set(G_OBJECT(settings), "enable-spatial-navigation", SPATIAL_BROWSING, NULL);
536
537         g_free(uri);
538
539         setatom(c, AtomFind, "");
540         setatom(c, AtomUri, "about:blank");
541         if(HIDE_BACKGROUND)
542                 webkit_web_view_set_transparent(c->view, TRUE);
543
544         c->title = NULL;
545         c->next = clients;
546         clients = c;
547         if(showxid) {
548                 gdk_display_sync(gtk_widget_get_display(c->win));
549                 printf("%u\n", (guint)GDK_WINDOW_XID(GTK_WIDGET(c->win)->window));
550                 fflush(NULL);
551                 if (fclose(stdout) != 0) {
552                         die("Error closing stdout");
553                 }
554         }
555         return c;
556 }
557
558 void
559 newrequest(SoupSession *s, SoupMessage *msg, gpointer v) {
560         SoupMessageHeaders *h = msg->request_headers;
561         SoupURI *uri;
562         const char *c;
563
564         soup_message_headers_remove(h, "Cookie");
565         uri = soup_message_get_uri(msg);
566         if((c = getcookies(uri)))
567                 soup_message_headers_append(h, "Cookie", c);
568         g_signal_connect_after(G_OBJECT(msg), "got-headers", G_CALLBACK(gotheaders), NULL);
569 }
570
571 void
572 newwindow(Client *c, const Arg *arg) {
573         guint i = 0;
574         const char *cmd[10], *uri;
575         const Arg a = { .v = (void *)cmd };
576         char tmp[64];
577
578         cmd[i++] = progname;
579         if(embed) {
580                 cmd[i++] = "-e";
581                 snprintf(tmp, LENGTH(tmp), "%u\n", (int)embed);
582                 cmd[i++] = tmp;
583         }
584         if(!script)
585                 cmd[i++] = "-s";
586         if(!plugin)
587                 cmd[i++] = "-p";
588         if(!loadimage)
589                 cmd[i++] = "-i";
590         if(showxid)
591                 cmd[i++] = "-x";
592         cmd[i++] = "--";
593         uri = arg->v ? (char *)arg->v : c->linkhover;
594         if(uri)
595                 cmd[i++] = uri;
596         cmd[i++] = NULL;
597         spawn(NULL, &a);
598 }
599
600 void
601 pasteuri(GtkClipboard *clipboard, const char *text, gpointer d) {
602         Arg arg = {.v = text };
603         if(text != NULL)
604                 loaduri((Client *) d, &arg);
605 }
606
607 void
608 print(Client *c, const Arg *arg) {
609         webkit_web_frame_print(webkit_web_view_get_main_frame(c->view));
610 }
611
612 GdkFilterReturn
613 processx(GdkXEvent *e, GdkEvent *event, gpointer d) {
614         Client *c = (Client *)d;
615         XPropertyEvent *ev;
616         Arg arg;
617
618         if(((XEvent *)e)->type == PropertyNotify) {
619                 ev = &((XEvent *)e)->xproperty;
620                 if(ev->state == PropertyNewValue) {
621                         if(ev->atom == atoms[AtomFind]) {
622                                 arg.b = TRUE;
623                                 find(c, &arg);
624                                 return GDK_FILTER_REMOVE;
625                         }
626                         else if(ev->atom == atoms[AtomGo]) {
627                                 arg.v = getatom(c, AtomGo);
628                                 loaduri(c, &arg);
629                                 return GDK_FILTER_REMOVE;
630                         }
631                 }
632         }
633         return GDK_FILTER_CONTINUE;
634 }
635
636 void
637 progresschange(WebKitWebView *view, GParamSpec *pspec, Client *c) {
638         c->progress = webkit_web_view_get_progress(c->view) * 100;
639         update(c);
640 }
641
642 void
643 reload(Client *c, const Arg *arg) {
644         gboolean nocache = *(gboolean *)arg;
645         if(nocache)
646                  webkit_web_view_reload_bypass_cache(c->view);
647         else
648                  webkit_web_view_reload(c->view);
649 }
650
651 void
652 resize(GtkWidget *w, GtkAllocation *a, Client *c) {
653         double zoom;
654
655         if(c->zoomed)
656                 return;
657         zoom = webkit_web_view_get_zoom_level(c->view);
658         if(a->width * a->height < 300 * 400 && zoom != 0.2)
659                 webkit_web_view_set_zoom_level(c->view, 0.2);
660         else if(zoom != 1.0)
661                 webkit_web_view_set_zoom_level(c->view, 1.0);
662 }
663
664 void
665 scroll(Client *c, const Arg *arg) {
666         gdouble v;
667         GtkAdjustment *a;
668
669         a = gtk_scrolled_window_get_vadjustment(GTK_SCROLLED_WINDOW(c->scroll));
670         v = gtk_adjustment_get_value(a);
671         v += gtk_adjustment_get_step_increment(a) * arg->i;
672         v = MAX(v, 0.0);
673         v = MIN(v, gtk_adjustment_get_upper(a) - gtk_adjustment_get_page_size(a));
674         gtk_adjustment_set_value(a, v);
675 }
676
677 void
678 setcookie(SoupCookie *c) {
679         int lock;
680
681         lock = open(cookiefile, 0);
682         flock(lock, LOCK_EX);
683         SoupDate *e;
684         SoupCookieJar *j = soup_cookie_jar_text_new(cookiefile, FALSE);
685         c = soup_cookie_copy(c);
686         if(c->expires == NULL && sessiontime) {
687                 e = soup_date_new_from_time_t(time(NULL) + sessiontime);
688                 soup_cookie_set_expires(c, e);
689         }
690         soup_cookie_jar_add_cookie(j, c);
691         g_object_unref(j);
692         flock(lock, LOCK_UN);
693         close(lock);
694 }
695
696 void
697 setatom(Client *c, int a, const char *v) {
698         XSync(dpy, False);
699         XChangeProperty(dpy, GDK_WINDOW_XID(GTK_WIDGET(c->win)->window), atoms[a],
700                         XA_STRING, 8, PropModeReplace, (unsigned char *)v,
701                         strlen(v) + 1);
702 }
703
704 void
705 setup(void) {
706         char *proxy;
707         char *new_proxy;
708         SoupURI *puri;
709         SoupSession *s;
710
711         /* clean up any zombies immediately */
712         sigchld(0);
713         gtk_init(NULL, NULL);
714         if (!g_thread_supported())
715                 g_thread_init(NULL);
716
717         dpy = GDK_DISPLAY();
718         s = webkit_get_default_session();
719
720         /* atoms */
721         atoms[AtomFind] = XInternAtom(dpy, "_SURF_FIND", False);
722         atoms[AtomGo] = XInternAtom(dpy, "_SURF_GO", False);
723         atoms[AtomUri] = XInternAtom(dpy, "_SURF_URI", False);
724
725         /* dirs and files */
726         cookiefile = buildpath(cookiefile);
727         scriptfile = buildpath(scriptfile);
728         stylefile = buildpath(stylefile);
729
730         /* request handler */
731         s = webkit_get_default_session();
732         soup_session_remove_feature_by_type(s, soup_cookie_get_type());
733         soup_session_remove_feature_by_type(s, soup_cookie_jar_get_type());
734         g_signal_connect_after(G_OBJECT(s), "request-started", G_CALLBACK(newrequest), NULL);
735
736         /* ssl */
737         g_object_set(G_OBJECT(s), "ssl-ca-file", cafile, NULL);
738         g_object_set(G_OBJECT(s), "ssl-strict", strictssl, NULL);
739
740         /* proxy */
741         if((proxy = getenv("http_proxy")) && strcmp(proxy, "")) {
742                 new_proxy = g_strrstr(proxy, "http://") ? g_strdup(proxy) :
743                         g_strdup_printf("http://%s", proxy);
744                 puri = soup_uri_new(new_proxy);
745                 g_object_set(G_OBJECT(s), "proxy-uri", puri, NULL);
746                 soup_uri_free(puri);
747                 g_free(new_proxy);
748         }
749 }
750
751 void
752 sigchld(int unused) {
753         if(signal(SIGCHLD, sigchld) == SIG_ERR)
754                 die("Can't install SIGCHLD handler");
755         while(0 < waitpid(-1, NULL, WNOHANG));
756 }
757
758 void
759 source(Client *c, const Arg *arg) {
760         Arg a = { .b = FALSE };
761         gboolean s;
762
763         s = webkit_web_view_get_view_source_mode(c->view);
764         webkit_web_view_set_view_source_mode(c->view, !s);
765         reload(c, &a);
766 }
767
768 void
769 spawn(Client *c, const Arg *arg) {
770         if(fork() == 0) {
771                 if(dpy)
772                         close(ConnectionNumber(dpy));
773                 setsid();
774                 execvp(((char **)arg->v)[0], (char **)arg->v);
775                 fprintf(stderr, "surf: execvp %s", ((char **)arg->v)[0]);
776                 perror(" failed");
777                 exit(0);
778         }
779 }
780
781 void
782 eval(Client *c, const Arg *arg) {
783         WebKitWebFrame *frame = webkit_web_view_get_main_frame(c->view);
784         evalscript(frame, webkit_web_frame_get_global_context(frame), ((char **)arg->v)[0], "");
785 }
786
787 void
788 stop(Client *c, const Arg *arg) {
789         webkit_web_view_stop_loading(c->view);
790 }
791
792 void
793 titlechange(WebKitWebView *v, WebKitWebFrame *f, const char *t, Client *c) {
794         c->title = copystr(&c->title, t);
795         update(c);
796 }
797
798 void
799 update(Client *c) {
800         char *t;
801
802         if(c->linkhover)
803                 t = g_strdup(c->linkhover);
804         else if(c->progress != 100)
805                 t = g_strdup_printf("[%i%%] %s", c->progress, c->title);
806         else
807                 t = g_strdup(c->title);
808         drawindicator(c);
809         gtk_window_set_title(GTK_WINDOW(c->win), t);
810         g_free(t);
811 }
812
813 void
814 updatewinid(Client *c) {
815         snprintf(winid, LENGTH(winid), "%u",
816                         (int)GDK_WINDOW_XID(GTK_WIDGET(c->win)->window));
817 }
818
819 void
820 usage(void) {
821         fputs("surf - simple browser\n", stderr);
822         die("usage: surf [-e xid] [-i] [-p] [-s] [-v] [-x] [uri]\n");
823 }
824
825 void
826 windowobjectcleared(GtkWidget *w, WebKitWebFrame *frame, JSContextRef js, JSObjectRef win, Client *c) {
827         runscript(frame, js);
828 }
829
830 void
831 zoom(Client *c, const Arg *arg) {
832         c->zoomed = TRUE;
833         if(arg->i < 0)          /* zoom out */
834                 webkit_web_view_zoom_out(c->view);
835         else if(arg->i > 0)     /* zoom in */
836                 webkit_web_view_zoom_in(c->view);
837         else {                  /* reset */
838                 c->zoomed = FALSE;
839                 webkit_web_view_set_zoom_level(c->view, 1.0);
840         }
841 }
842
843 int
844 main(int argc, char *argv[]) {
845         int i;
846         Arg arg;
847
848         progname = argv[0];
849         /* command line args */
850         for(i = 1, arg.v = NULL; i < argc && argv[i][0] == '-' &&
851                         argv[i][1] != '\0' && argv[i][2] == '\0'; i++) {
852                 if(!strcmp(argv[i], "--")) {
853                         i++;
854                         break;
855                 }
856                 switch(argv[i][1]) {
857                 case 'e':
858                         if(++i < argc)
859                                 embed = atoi(argv[i]);
860                         else
861                                 usage();
862                         break;
863                 case 'i':
864                         loadimage = 0;
865                         break;
866                 case 'p':
867                         plugin = 0;
868                         break;
869                 case 's':
870                         script = 0;
871                         break;
872                 case 'x':
873                         showxid = TRUE;
874                         break;
875                 case 'v':
876                         die("surf-"VERSION", ©2009-2012 surf engineers, see LICENSE for details\n");
877                 default:
878                         usage();
879                 }
880         }
881         if(i < argc)
882                 arg.v = argv[i];
883         setup();
884         newclient();
885         if(arg.v)
886                 loaduri(clients, &arg);
887         gtk_main();
888         cleanup();
889         return EXIT_SUCCESS;
890 }