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