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