bb9343bced7f18b6faa4bb7841dd553b9a373462
[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;
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         GtkWidget *w;
337         GdkGC *gc;
338         GdkColor fg;
339
340         uri = geturi(c);
341         w = c->indicator;
342         width = c->progress * w->allocation.width / 100;
343         gc = gdk_gc_new(w->window);
344         if(strstr(uri, "https://") == uri)
345                 gdk_color_parse(c->sslfailed ?
346                                 progress_untrust : progress_trust, &fg);
347         else
348                 gdk_color_parse(progress, &fg);
349         gdk_gc_set_rgb_fg_color(gc, &fg);
350         gdk_draw_rectangle(w->window,
351                         w->style->bg_gc[GTK_WIDGET_STATE(w)],
352                         TRUE, 0, 0, w->allocation.width, w->allocation.height);
353         gdk_draw_rectangle(w->window, gc, TRUE, 0, 0, width,
354                         w->allocation.height);
355         g_object_unref(gc);
356 }
357
358 gboolean
359 exposeindicator(GtkWidget *w, GdkEventExpose *e, Client *c) {
360         drawindicator(c);
361         return TRUE;
362 }
363
364 void
365 find(Client *c, const Arg *arg) {
366         const char *s;
367
368         s = getatom(c, AtomFind);
369         gboolean forward = *(gboolean *)arg;
370         webkit_web_view_search_text(c->view, s, FALSE, forward, TRUE);
371 }
372
373 const char *
374 getatom(Client *c, int a) {
375         static char buf[BUFSIZ];
376         Atom adummy;
377         int idummy;
378         unsigned long ldummy;
379         unsigned char *p = NULL;
380
381         XGetWindowProperty(dpy, GDK_WINDOW_XID(GTK_WIDGET(c->win)->window),
382                         atoms[a], 0L, BUFSIZ, False, XA_STRING,
383                         &adummy, &idummy, &ldummy, &ldummy, &p);
384         if(p)
385                 strncpy(buf, (char *)p, LENGTH(buf)-1);
386         else
387                 buf[0] = '\0';
388         XFree(p);
389         return buf;
390 }
391
392 char *
393 geturi(Client *c) {
394         char *uri;
395
396         if(!(uri = (char *)webkit_web_view_get_uri(c->view)))
397                 uri = "about:blank";
398         return uri;
399 }
400
401 gboolean
402 initdownload(WebKitWebView *view, WebKitDownload *o, Client *c) {
403         Arg arg;
404
405         updatewinid(c);
406         arg = (Arg)DOWNLOAD((char *)webkit_download_get_uri(o));
407         spawn(c, &arg);
408         return FALSE;
409 }
410
411 gboolean
412 keypress(GtkWidget* w, GdkEventKey *ev, Client *c) {
413         guint i;
414         gboolean processed = FALSE;
415
416         updatewinid(c);
417         for(i = 0; i < LENGTH(keys); i++) {
418                 if(gdk_keyval_to_lower(ev->keyval) == keys[i].keyval
419                                 && (ev->state & keys[i].mod) == keys[i].mod
420                                 && keys[i].func) {
421                         keys[i].func(c, &(keys[i].arg));
422                         processed = TRUE;
423                 }
424         }
425         return processed;
426 }
427
428 void
429 linkhover(WebKitWebView *v, const char* t, const char* l, Client *c) {
430         if(l) {
431                 c->linkhover = copystr(&c->linkhover, l);
432         }
433         else if(c->linkhover) {
434                 free(c->linkhover);
435                 c->linkhover = NULL;
436         }
437         update(c);
438 }
439
440 void
441 loadstatuschange(WebKitWebView *view, GParamSpec *pspec, Client *c) {
442         WebKitWebFrame *frame;
443         WebKitWebDataSource *src;
444         WebKitNetworkRequest *request;
445         SoupMessage *msg;
446         char *uri;
447
448         switch(webkit_web_view_get_load_status (c->view)) {
449         case WEBKIT_LOAD_COMMITTED:
450                 uri = geturi(c);
451                 if(strstr(uri, "https://") == uri) {
452                         frame = webkit_web_view_get_main_frame(c->view);
453                         src = webkit_web_frame_get_data_source(frame);
454                         request = webkit_web_data_source_get_request(src);
455                         msg = webkit_network_request_get_message(request);
456                         c->sslfailed = soup_message_get_flags(msg)
457                                        ^ SOUP_MESSAGE_CERTIFICATE_TRUSTED;
458                 }
459                 setatom(c, AtomUri, uri);
460                 break;
461         case WEBKIT_LOAD_FINISHED:
462                 c->progress = 100;
463                 update(c);
464                 break;
465         default:
466                 break;
467         }
468 }
469
470 void
471 loaduri(Client *c, const Arg *arg) {
472         char *u;
473         const char *uri = (char *)arg->v;
474         Arg a = { .b = FALSE };
475
476         if(strcmp(uri, "") == 0)
477                 return;
478         u = g_strrstr(uri, "://") ? g_strdup(uri)
479                 : g_strdup_printf("http://%s", uri);
480         /* prevents endless loop */
481         if(c->uri && strcmp(u, c->uri) == 0) {
482                 reload(c, &a);
483         }
484         else {
485                 webkit_web_view_load_uri(c->view, u);
486                 c->progress = 0;
487                 c->title = copystr(&c->title, u);
488                 g_free(u);
489                 update(c);
490         }
491 }
492
493 void
494 navigate(Client *c, const Arg *arg) {
495         int steps = *(int *)arg;
496         webkit_web_view_go_back_or_forward(c->view, steps);
497 }
498
499 Client *
500 newclient(void) {
501         Client *c;
502         WebKitWebSettings *settings;
503         WebKitWebFrame *frame;
504         GdkGeometry hints = { 1, 1 };
505         char *uri, *ua;
506
507         if(!(c = calloc(1, sizeof(Client))))
508                 die("Cannot malloc!\n");
509         /* Window */
510         if(embed) {
511                 c->win = gtk_plug_new(embed);
512         }
513         else {
514                 c->win = gtk_window_new(GTK_WINDOW_TOPLEVEL);
515                 /* TA:  20091214:  Despite what the GNOME docs say, the ICCCM
516                  * is always correct, so we should still call this function.
517                  * But when doing so, we *must* differentiate between a
518                  * WM_CLASS and a resource on the window.  By convention, the
519                  * window class (WM_CLASS) is capped, while the resource is in
520                  * lowercase.   Both these values come as a pair.
521                  */
522                 gtk_window_set_wmclass(GTK_WINDOW(c->win), "surf", "Surf");
523
524                 /* TA:  20091214:  And set the role here as well -- so that
525                  * sessions can pick this up.
526                  */
527                 gtk_window_set_role(GTK_WINDOW(c->win), "Surf");
528         }
529         gtk_window_set_default_size(GTK_WINDOW(c->win), 800, 600);
530         g_signal_connect(G_OBJECT(c->win), "destroy", G_CALLBACK(destroywin), c);
531         g_signal_connect(G_OBJECT(c->win), "key-press-event", G_CALLBACK(keypress), c);
532
533         /* VBox */
534         c->vbox = gtk_vbox_new(FALSE, 0);
535
536         /* Scrolled Window */
537         c->scroll = gtk_scrolled_window_new(NULL, NULL);
538         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(c->scroll),
539                         GTK_POLICY_NEVER, GTK_POLICY_NEVER);
540
541         /* Webview */
542         c->view = WEBKIT_WEB_VIEW(webkit_web_view_new());
543         g_signal_connect(G_OBJECT(c->view), "title-changed", G_CALLBACK(titlechange), c);
544         g_signal_connect(G_OBJECT(c->view), "hovering-over-link", G_CALLBACK(linkhover), c);
545         g_signal_connect(G_OBJECT(c->view), "create-web-view", G_CALLBACK(createwindow), c);
546         g_signal_connect(G_OBJECT(c->view), "new-window-policy-decision-requested", G_CALLBACK(decidewindow), c);
547         g_signal_connect(G_OBJECT(c->view), "mime-type-policy-decision-requested", G_CALLBACK(decidedownload), c);
548         g_signal_connect(G_OBJECT(c->view), "window-object-cleared", G_CALLBACK(windowobjectcleared), c);
549         g_signal_connect(G_OBJECT(c->view), "notify::load-status", G_CALLBACK(loadstatuschange), c);
550         g_signal_connect(G_OBJECT(c->view), "notify::progress", G_CALLBACK(progresschange), c);
551         g_signal_connect(G_OBJECT(c->view), "download-requested", G_CALLBACK(initdownload), c);
552         g_signal_connect(G_OBJECT(c->view), "button-release-event", G_CALLBACK(buttonrelease), c);
553         g_signal_connect(G_OBJECT(c->view), "populate-popup", G_CALLBACK(populatepopup), c);
554
555         /* Indicator */
556         c->indicator = gtk_drawing_area_new();
557         gtk_widget_set_size_request(c->indicator, 0, 2);
558         g_signal_connect (G_OBJECT (c->indicator), "expose_event",
559                         G_CALLBACK (exposeindicator), c);
560
561         /* Arranging */
562         gtk_container_add(GTK_CONTAINER(c->scroll), GTK_WIDGET(c->view));
563         gtk_container_add(GTK_CONTAINER(c->win), c->vbox);
564         gtk_container_add(GTK_CONTAINER(c->vbox), c->scroll);
565         gtk_container_add(GTK_CONTAINER(c->vbox), c->indicator);
566
567         /* Setup */
568         gtk_box_set_child_packing(GTK_BOX(c->vbox), c->indicator, FALSE, FALSE, 0, GTK_PACK_START);
569         gtk_box_set_child_packing(GTK_BOX(c->vbox), c->scroll, TRUE, TRUE, 0, GTK_PACK_START);
570         gtk_widget_grab_focus(GTK_WIDGET(c->view));
571         gtk_widget_show(c->vbox);
572         gtk_widget_show(c->indicator);
573         gtk_widget_show(c->scroll);
574         gtk_widget_show(GTK_WIDGET(c->view));
575         gtk_widget_show(c->win);
576         gtk_window_set_geometry_hints(GTK_WINDOW(c->win), NULL, &hints, GDK_HINT_MIN_SIZE);
577         gdk_window_set_events(GTK_WIDGET(c->win)->window, GDK_ALL_EVENTS_MASK);
578         gdk_window_add_filter(GTK_WIDGET(c->win)->window, processx, c);
579         webkit_web_view_set_full_content_zoom(c->view, TRUE);
580         frame = webkit_web_view_get_main_frame(c->view);
581         runscript(frame);
582         settings = webkit_web_view_get_settings(c->view);
583         if(!(ua = getenv("SURF_USERAGENT")))
584                 ua = useragent;
585         g_object_set(G_OBJECT(settings), "user-agent", ua, NULL);
586         uri = g_strconcat("file://", stylefile, NULL);
587         g_object_set(G_OBJECT(settings), "user-stylesheet-uri", uri, NULL);
588         g_object_set(G_OBJECT(settings), "auto-load-images", loadimage, NULL);
589         g_object_set(G_OBJECT(settings), "enable-plugins", plugin, NULL);
590         g_object_set(G_OBJECT(settings), "enable-scripts", script, NULL);
591         g_object_set(G_OBJECT(settings), "enable-spatial-navigation", SPATIAL_BROWSING, NULL);
592
593         g_free(uri);
594
595         setatom(c, AtomFind, "");
596         setatom(c, AtomUri, "about:blank");
597         if(HIDE_BACKGROUND)
598                 webkit_web_view_set_transparent(c->view, TRUE);
599
600         c->title = NULL;
601         c->next = clients;
602         clients = c;
603         if(showxid) {
604                 gdk_display_sync(gtk_widget_get_display(c->win));
605                 printf("%u\n", (guint)GDK_WINDOW_XID(GTK_WIDGET(c->win)->window));
606                 fflush(NULL);
607                 if (fclose(stdout) != 0) {
608                         die("Error closing stdout");
609                 }
610         }
611         return c;
612 }
613
614 void
615 newwindow(Client *c, const Arg *arg, gboolean noembed) {
616         guint i = 0;
617         const char *cmd[10], *uri;
618         const Arg a = { .v = (void *)cmd };
619         char tmp[64];
620
621         cmd[i++] = progname;
622         if(embed && !noembed) {
623                 cmd[i++] = "-e";
624                 snprintf(tmp, LENGTH(tmp), "%u\n", (int)embed);
625                 cmd[i++] = tmp;
626         }
627         if(!script)
628                 cmd[i++] = "-s";
629         if(!plugin)
630                 cmd[i++] = "-p";
631         if(!loadimage)
632                 cmd[i++] = "-i";
633         if(showxid)
634                 cmd[i++] = "-x";
635         cmd[i++] = "--";
636         uri = arg->v ? (char *)arg->v : c->linkhover;
637         if(uri)
638                 cmd[i++] = uri;
639         cmd[i++] = NULL;
640         spawn(NULL, &a);
641 }
642
643 static void
644 populatepopup(WebKitWebView *web, GtkMenu *menu, Client *c) {
645         GList *items = gtk_container_get_children(GTK_CONTAINER(menu));
646
647         for(GList *l = items; l; l = l->next) {
648                 g_signal_connect(l->data, "activate", G_CALLBACK(popupactivate), c);
649         }
650
651         g_list_free(items);
652 }
653
654 static void
655 popupactivate(GtkMenuItem *menu, Client *c) {
656         /*
657          * context-menu-action-2000     open link
658          * context-menu-action-1        open link in window
659          * context-menu-action-2        download linked file
660          * context-menu-action-3        copy link location
661          * context-menu-action-13       reload
662          * context-menu-action-10       back
663          * context-menu-action-11       forward
664          * context-menu-action-12       stop
665          */
666
667         GtkAction *a = NULL;
668         const char *name;
669         GtkClipboard *prisel;
670
671         a = gtk_activatable_get_related_action(GTK_ACTIVATABLE(menu));
672         if(a == NULL)
673                 return;
674
675         name = gtk_action_get_name(a);
676         if(!g_strcmp0(name, "context-menu-action-3")) {
677                 prisel = gtk_clipboard_get(GDK_SELECTION_PRIMARY);
678                 gtk_clipboard_set_text(prisel, c->linkhover, -1);
679         }
680 }
681
682 void
683 pasteuri(GtkClipboard *clipboard, const char *text, gpointer d) {
684         Arg arg = {.v = text };
685         if(text != NULL)
686                 loaduri((Client *) d, &arg);
687 }
688
689 void
690 print(Client *c, const Arg *arg) {
691         webkit_web_frame_print(webkit_web_view_get_main_frame(c->view));
692 }
693
694 GdkFilterReturn
695 processx(GdkXEvent *e, GdkEvent *event, gpointer d) {
696         Client *c = (Client *)d;
697         XPropertyEvent *ev;
698         Arg arg;
699
700         if(((XEvent *)e)->type == PropertyNotify) {
701                 ev = &((XEvent *)e)->xproperty;
702                 if(ev->state == PropertyNewValue) {
703                         if(ev->atom == atoms[AtomFind]) {
704                                 arg.b = TRUE;
705                                 find(c, &arg);
706                                 return GDK_FILTER_REMOVE;
707                         }
708                         else if(ev->atom == atoms[AtomGo]) {
709                                 arg.v = getatom(c, AtomGo);
710                                 loaduri(c, &arg);
711                                 return GDK_FILTER_REMOVE;
712                         }
713                 }
714         }
715         return GDK_FILTER_CONTINUE;
716 }
717
718 void
719 progresschange(WebKitWebView *view, GParamSpec *pspec, Client *c) {
720         c->progress = webkit_web_view_get_progress(c->view) * 100;
721         update(c);
722 }
723
724 void
725 reload(Client *c, const Arg *arg) {
726         gboolean nocache = *(gboolean *)arg;
727         if(nocache)
728                  webkit_web_view_reload_bypass_cache(c->view);
729         else
730                  webkit_web_view_reload(c->view);
731 }
732
733 void
734 scroll_h(Client *c, const Arg *arg) {
735         scroll(gtk_scrolled_window_get_hadjustment(
736                                 GTK_SCROLLED_WINDOW(c->scroll)), arg);
737 }
738
739 void
740 scroll_v(Client *c, const Arg *arg) {
741         scroll(gtk_scrolled_window_get_vadjustment(
742                                 GTK_SCROLLED_WINDOW(c->scroll)), arg);
743 }
744
745 void
746 scroll(GtkAdjustment *a, const Arg *arg) {
747         gdouble v;
748
749         v = gtk_adjustment_get_value(a);
750         switch (arg->i){
751         case +10000:
752         case -10000:
753                 v += gtk_adjustment_get_page_increment(a) *
754                         (arg->i / 10000);
755                 break;
756         case +20000:
757         case -20000:
758         default:
759                 v += gtk_adjustment_get_step_increment(a) * arg->i;
760         }
761
762         v = MAX(v, 0.0);
763         v = MIN(v, gtk_adjustment_get_upper(a) -
764                         gtk_adjustment_get_page_size(a));
765         gtk_adjustment_set_value(a, v);
766 }
767
768 void
769 setatom(Client *c, int a, const char *v) {
770         XSync(dpy, False);
771         XChangeProperty(dpy, GDK_WINDOW_XID(GTK_WIDGET(c->win)->window), atoms[a],
772                         XA_STRING, 8, PropModeReplace, (unsigned char *)v,
773                         strlen(v) + 1);
774 }
775
776 void
777 setup(void) {
778         char *proxy;
779         char *new_proxy;
780         SoupURI *puri;
781         SoupSession *s;
782
783         /* clean up any zombies immediately */
784         sigchld(0);
785         gtk_init(NULL, NULL);
786         if (!g_thread_supported())
787                 g_thread_init(NULL);
788
789         dpy = GDK_DISPLAY();
790
791         /* atoms */
792         atoms[AtomFind] = XInternAtom(dpy, "_SURF_FIND", False);
793         atoms[AtomGo] = XInternAtom(dpy, "_SURF_GO", False);
794         atoms[AtomUri] = XInternAtom(dpy, "_SURF_URI", False);
795
796         /* dirs and files */
797         cookiefile = buildpath(cookiefile);
798         scriptfile = buildpath(scriptfile);
799         stylefile = buildpath(stylefile);
800
801         /* request handler */
802         s = webkit_get_default_session();
803
804         /* cookie jar */
805         soup_session_add_feature(s, SOUP_SESSION_FEATURE(cookiejar_new(cookiefile, FALSE)));
806
807         /* ssl */
808         g_object_set(G_OBJECT(s), "ssl-ca-file", cafile, NULL);
809         g_object_set(G_OBJECT(s), "ssl-strict", strictssl, NULL);
810
811         /* proxy */
812         if((proxy = getenv("http_proxy")) && strcmp(proxy, "")) {
813                 new_proxy = g_strrstr(proxy, "http://") ? g_strdup(proxy) :
814                         g_strdup_printf("http://%s", proxy);
815                 puri = soup_uri_new(new_proxy);
816                 g_object_set(G_OBJECT(s), "proxy-uri", puri, NULL);
817                 soup_uri_free(puri);
818                 g_free(new_proxy);
819         }
820 }
821
822 void
823 sigchld(int unused) {
824         if(signal(SIGCHLD, sigchld) == SIG_ERR)
825                 die("Can't install SIGCHLD handler");
826         while(0 < waitpid(-1, NULL, WNOHANG));
827 }
828
829 void
830 source(Client *c, const Arg *arg) {
831         Arg a = { .b = FALSE };
832         gboolean s;
833
834         s = webkit_web_view_get_view_source_mode(c->view);
835         webkit_web_view_set_view_source_mode(c->view, !s);
836         reload(c, &a);
837 }
838
839 void
840 spawn(Client *c, const Arg *arg) {
841         if(fork() == 0) {
842                 if(dpy)
843                         close(ConnectionNumber(dpy));
844                 setsid();
845                 execvp(((char **)arg->v)[0], (char **)arg->v);
846                 fprintf(stderr, "surf: execvp %s", ((char **)arg->v)[0]);
847                 perror(" failed");
848                 exit(0);
849         }
850 }
851
852 void
853 eval(Client *c, const Arg *arg) {
854         WebKitWebFrame *frame = webkit_web_view_get_main_frame(c->view);
855         evalscript(webkit_web_frame_get_global_context(frame),
856                         ((char **)arg->v)[0], "");
857 }
858
859 void
860 stop(Client *c, const Arg *arg) {
861         webkit_web_view_stop_loading(c->view);
862 }
863
864 void
865 titlechange(WebKitWebView *v, WebKitWebFrame *f, const char *t, Client *c) {
866         c->title = copystr(&c->title, t);
867         update(c);
868 }
869
870 void
871 update(Client *c) {
872         char *t;
873
874         if(c->linkhover) {
875                 t = g_strdup(c->linkhover);
876         } else if(c->progress != 100) {
877                 drawindicator(c);
878                 gtk_widget_show(c->indicator);
879                 t = g_strdup_printf("[%i%%] %s", c->progress, c->title);
880         } else {
881                 gtk_widget_hide_all(c->indicator);
882                 t = g_strdup(c->title);
883         }
884         gtk_window_set_title(GTK_WINDOW(c->win), t);
885         g_free(t);
886 }
887
888 void
889 updatewinid(Client *c) {
890         snprintf(winid, LENGTH(winid), "%u",
891                         (int)GDK_WINDOW_XID(GTK_WIDGET(c->win)->window));
892 }
893
894 void
895 usage(void) {
896         fputs("surf - simple browser\n", stderr);
897         die("usage: surf [-e xid] [-i] [-p] [-s] [-v] [-x] [uri]\n");
898 }
899
900 void
901 windowobjectcleared(GtkWidget *w, WebKitWebFrame *frame, JSContextRef js, JSObjectRef win, Client *c) {
902         runscript(frame);
903 }
904
905 void
906 zoom(Client *c, const Arg *arg) {
907         c->zoomed = TRUE;
908         if(arg->i < 0)          /* zoom out */
909                 webkit_web_view_zoom_out(c->view);
910         else if(arg->i > 0)     /* zoom in */
911                 webkit_web_view_zoom_in(c->view);
912         else {                  /* reset */
913                 c->zoomed = FALSE;
914                 webkit_web_view_set_zoom_level(c->view, 1.0);
915         }
916 }
917
918 int
919 main(int argc, char *argv[]) {
920         int i;
921         Arg arg;
922
923         progname = argv[0];
924         /* command line args */
925         for(i = 1, arg.v = NULL; i < argc && argv[i][0] == '-' &&
926                         argv[i][1] != '\0' && argv[i][2] == '\0'; i++) {
927                 if(!strcmp(argv[i], "--")) {
928                         i++;
929                         break;
930                 }
931                 switch(argv[i][1]) {
932                 case 'e':
933                         if(++i < argc)
934                                 embed = strtol(argv[i], NULL, 0);
935                         else
936                                 usage();
937                         break;
938                 case 'i':
939                         loadimage = 0;
940                         break;
941                 case 'p':
942                         plugin = 0;
943                         break;
944                 case 's':
945                         script = 0;
946                         break;
947                 case 'x':
948                         showxid = TRUE;
949                         break;
950                 case 'v':
951                         die("surf-"VERSION", ©2009-2012 surf engineers, see LICENSE for details\n");
952                 default:
953                         usage();
954                 }
955         }
956         if(i < argc)
957                 arg.v = argv[i];
958         setup();
959         newclient();
960         if(arg.v)
961                 loaduri(clients, &arg);
962         gtk_main();
963         cleanup();
964         return EXIT_SUCCESS;
965 }