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