Add an option to disable the indicators.
[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 <limits.h>
17 #include <stdlib.h>
18 #include <stdio.h>
19 #include <webkit/webkit.h>
20 #include <glib/gstdio.h>
21 #include <JavaScriptCore/JavaScript.h>
22 #include <sys/file.h>
23 #include <libgen.h>
24 #include <stdarg.h>
25
26 #include "arg.h"
27
28 char *argv0;
29
30 #define LENGTH(x)               (sizeof x / sizeof x[0])
31 #define CLEANMASK(mask)         (mask & (MODKEY|GDK_SHIFT_MASK))
32 #define COOKIEJAR_TYPE          (cookiejar_get_type ())
33 #define COOKIEJAR(obj)          (G_TYPE_CHECK_INSTANCE_CAST ((obj), COOKIEJAR_TYPE, CookieJar))
34
35 enum { AtomFind, AtomGo, AtomUri, AtomLast };
36
37 typedef union Arg Arg;
38 union Arg {
39         gboolean b;
40         gint i;
41         const void *v;
42 };
43
44 typedef struct Client {
45         GtkWidget *win, *scroll, *vbox, *pane;
46         WebKitWebView *view;
47         WebKitWebInspector *inspector;
48         char *title, *linkhover;
49         const char *uri, *needle;
50         gint progress;
51         struct Client *next;
52         gboolean zoomed, fullscreen, isinspecting, sslfailed;
53 } Client;
54
55 typedef struct {
56         guint mod;
57         guint keyval;
58         void (*func)(Client *c, const Arg *arg);
59         const Arg arg;
60 } Key;
61
62 typedef struct {
63         SoupCookieJarText parent_instance;
64         int lock;
65 } CookieJar;
66
67 typedef struct {
68         SoupCookieJarTextClass parent_class;
69 } CookieJarClass;
70
71 G_DEFINE_TYPE(CookieJar, cookiejar, SOUP_TYPE_COOKIE_JAR_TEXT)
72
73 static Display *dpy;
74 static Atom atoms[AtomLast];
75 static Client *clients = NULL;
76 static GdkNativeWindow embed = 0;
77 static gboolean showxid = FALSE;
78 static char winid[64];
79 static gboolean usingproxy = 0;
80 static char togglestat[6];
81 static char pagestat[3];
82
83 static void addaccelgroup(Client *c);
84 static void beforerequest(WebKitWebView *w, WebKitWebFrame *f,
85                 WebKitWebResource *r, WebKitNetworkRequest *req,
86                 WebKitNetworkResponse *resp, gpointer d);
87 static char *buildpath(const char *path);
88 static gboolean buttonrelease(WebKitWebView *web, GdkEventButton *e,
89                 GList *gl);
90 static void cleanup(void);
91 static void clipboard(Client *c, const Arg *arg);
92
93 static void cookiejar_changed(SoupCookieJar *self, SoupCookie *old_cookie,
94                 SoupCookie *new_cookie);
95 static void cookiejar_finalize(GObject *self);
96 static SoupCookieJar *cookiejar_new(const char *filename, gboolean read_only);
97 static void cookiejar_set_property(GObject *self, guint prop_id,
98                 const GValue *value, GParamSpec *pspec);
99
100 static char *copystr(char **str, const char *src);
101 static WebKitWebView *createwindow(WebKitWebView *v, WebKitWebFrame *f,
102                 Client *c);
103 static gboolean decidedownload(WebKitWebView *v, WebKitWebFrame *f,
104                 WebKitNetworkRequest *r, gchar *m,  WebKitWebPolicyDecision *p,
105                 Client *c);
106 static gboolean decidewindow(WebKitWebView *v, WebKitWebFrame *f,
107                 WebKitNetworkRequest *r, WebKitWebNavigationAction *n,
108                 WebKitWebPolicyDecision *p, Client *c);
109 static void destroyclient(Client *c);
110 static void destroywin(GtkWidget* w, Client *c);
111 static void die(const char *errstr, ...);
112 static void eval(Client *c, const Arg *arg);
113 static void find(Client *c, const Arg *arg);
114 static void fullscreen(Client *c, const Arg *arg);
115 static const char *getatom(Client *c, int a);
116 static void gettogglestat(Client *c);
117 static void getpagestat(Client *c);
118 static char *geturi(Client *c);
119 static gboolean initdownload(WebKitWebView *v, WebKitDownload *o, Client *c);
120
121 static void inspector(Client *c, const Arg *arg);
122 static WebKitWebView *inspector_new(WebKitWebInspector *i, WebKitWebView *v,
123                 Client *c);
124 static gboolean inspector_show(WebKitWebInspector *i, Client *c);
125 static gboolean inspector_close(WebKitWebInspector *i, Client *c);
126 static void inspector_finished(WebKitWebInspector *i, Client *c);
127
128 static gboolean keypress(GtkAccelGroup *group,
129                 GObject *obj, guint key, GdkModifierType mods,
130                 Client *c);
131 static void linkhover(WebKitWebView *v, const char* t, const char* l,
132                 Client *c);
133 static void loadstatuschange(WebKitWebView *view, GParamSpec *pspec,
134                 Client *c);
135 static void loaduri(Client *c, const Arg *arg);
136 static void navigate(Client *c, const Arg *arg);
137 static Client *newclient(void);
138 static void newwindow(Client *c, const Arg *arg, gboolean noembed);
139 static void pasteuri(GtkClipboard *clipboard, const char *text, gpointer d);
140 static void populatepopup(WebKitWebView *web, GtkMenu *menu, Client *c);
141 static void popupactivate(GtkMenuItem *menu, Client *);
142 static void print(Client *c, const Arg *arg);
143 static GdkFilterReturn processx(GdkXEvent *xevent, GdkEvent *event,
144                 gpointer d);
145 static void progresschange(WebKitWebView *view, GParamSpec *pspec, Client *c);
146 static void reload(Client *c, const Arg *arg);
147 static void scroll_h(Client *c, const Arg *arg);
148 static void scroll_v(Client *c, const Arg *arg);
149 static void scroll(GtkAdjustment *a, const Arg *arg);
150 static void setatom(Client *c, int a, const char *v);
151 static void setup(void);
152 static void sigchld(int unused);
153 static void source(Client *c, const Arg *arg);
154 static void spawn(Client *c, const Arg *arg);
155 static void stop(Client *c, const Arg *arg);
156 static void titlechange(WebKitWebView *v, WebKitWebFrame *frame,
157                 const char *title, Client *c);
158 static void toggle(Client *c, const Arg *arg);
159 static void togglescrollbars(Client *c, const Arg *arg);
160 static void togglestyle(Client *c, const Arg *arg);
161 static void updatetitle(Client *c);
162 static void updatewinid(Client *c);
163 static void usage(void);
164 static void windowobjectcleared(GtkWidget *w, WebKitWebFrame *frame,
165                 JSContextRef js, JSObjectRef win, Client *c);
166 static void zoom(Client *c, const Arg *arg);
167
168 /* configuration, allows nested code to access above variables */
169 #include "config.h"
170
171 static void
172 addaccelgroup(Client *c) {
173         int i;
174         GtkAccelGroup *group = gtk_accel_group_new();
175         GClosure *closure;
176
177         for(i = 0; i < LENGTH(keys); i++) {
178                 closure = g_cclosure_new(G_CALLBACK(keypress), c, NULL);
179                 gtk_accel_group_connect(group, keys[i].keyval, keys[i].mod,
180                                 0, closure);
181         }
182         gtk_window_add_accel_group(GTK_WINDOW(c->win), group);
183 }
184
185 static void
186 beforerequest(WebKitWebView *w, WebKitWebFrame *f, WebKitWebResource *r,
187                 WebKitNetworkRequest *req, WebKitNetworkResponse *resp,
188                 gpointer d) {
189         const gchar *uri = webkit_network_request_get_uri(req);
190
191         if(g_str_has_suffix(uri, "/favicon.ico"))
192                 webkit_network_request_set_uri(req, "about:blank");
193 }
194
195 static char *
196 buildpath(const char *path) {
197         char *apath, *p;
198         FILE *f;
199
200         /* creating directory */
201         if(path[0] == '/') {
202                 apath = g_strdup(path);
203         } else if(path[0] == '~') {
204                 if(path[1] == '/') {
205                         apath = g_strconcat(g_get_home_dir(), &path[1], NULL);
206                 } else {
207                         apath = g_strconcat(g_get_home_dir(), "/",
208                                         &path[1], NULL);
209                 }
210         } else {
211                 apath = g_strconcat(g_get_current_dir(), "/", path, NULL);
212         }
213
214         if((p = strrchr(apath, '/'))) {
215                 *p = '\0';
216                 g_mkdir_with_parents(apath, 0700);
217                 g_chmod(apath, 0700); /* in case it existed */
218                 *p = '/';
219         }
220         /* creating file (gives error when apath ends with "/") */
221         if((f = fopen(apath, "a"))) {
222                 g_chmod(apath, 0600); /* always */
223                 fclose(f);
224         }
225
226         return apath;
227 }
228
229 static gboolean
230 buttonrelease(WebKitWebView *web, GdkEventButton *e, GList *gl) {
231         WebKitHitTestResultContext context;
232         WebKitHitTestResult *result = webkit_web_view_get_hit_test_result(web,
233                         e);
234         Arg arg;
235
236         g_object_get(result, "context", &context, NULL);
237         if(context & WEBKIT_HIT_TEST_RESULT_CONTEXT_LINK) {
238                 if(e->button == 2) {
239                         g_object_get(result, "link-uri", &arg.v, NULL);
240                         newwindow(NULL, &arg, e->state & GDK_CONTROL_MASK);
241                         return true;
242                 }
243         }
244         return false;
245 }
246
247 static void
248 cleanup(void) {
249         while(clients)
250                 destroyclient(clients);
251         g_free(cookiefile);
252         g_free(scriptfile);
253         g_free(stylefile);
254 }
255
256 static void
257 cookiejar_changed(SoupCookieJar *self, SoupCookie *old_cookie,
258                 SoupCookie *new_cookie) {
259         flock(COOKIEJAR(self)->lock, LOCK_EX);
260         if(new_cookie && !new_cookie->expires && sessiontime) {
261                 soup_cookie_set_expires(new_cookie,
262                                 soup_date_new_from_now(sessiontime));
263         }
264         SOUP_COOKIE_JAR_CLASS(cookiejar_parent_class)->changed(self,
265                         old_cookie, new_cookie);
266         flock(COOKIEJAR(self)->lock, LOCK_UN);
267 }
268
269 static void
270 cookiejar_class_init(CookieJarClass *klass) {
271         SOUP_COOKIE_JAR_CLASS(klass)->changed = cookiejar_changed;
272         G_OBJECT_CLASS(klass)->get_property =
273                 G_OBJECT_CLASS(cookiejar_parent_class)->get_property;
274         G_OBJECT_CLASS(klass)->set_property = cookiejar_set_property;
275         G_OBJECT_CLASS(klass)->finalize = cookiejar_finalize;
276         g_object_class_override_property(G_OBJECT_CLASS(klass), 1, "filename");
277 }
278
279 static void
280 cookiejar_finalize(GObject *self) {
281         close(COOKIEJAR(self)->lock);
282         G_OBJECT_CLASS(cookiejar_parent_class)->finalize(self);
283 }
284
285 static void
286 cookiejar_init(CookieJar *self) {
287         self->lock = open(cookiefile, 0);
288 }
289
290 static SoupCookieJar *
291 cookiejar_new(const char *filename, gboolean read_only) {
292         return g_object_new(COOKIEJAR_TYPE,
293                             SOUP_COOKIE_JAR_TEXT_FILENAME, filename,
294                             SOUP_COOKIE_JAR_READ_ONLY, read_only, NULL);
295 }
296
297 static void
298 cookiejar_set_property(GObject *self, guint prop_id, const GValue *value,
299                 GParamSpec *pspec) {
300         flock(COOKIEJAR(self)->lock, LOCK_SH);
301         G_OBJECT_CLASS(cookiejar_parent_class)->set_property(self, prop_id,
302                         value, pspec);
303         flock(COOKIEJAR(self)->lock, LOCK_UN);
304 }
305
306 static void
307 evalscript(JSContextRef js, char *script, char* scriptname) {
308         JSStringRef jsscript, jsscriptname;
309         JSValueRef exception = NULL;
310
311         jsscript = JSStringCreateWithUTF8CString(script);
312         jsscriptname = JSStringCreateWithUTF8CString(scriptname);
313         JSEvaluateScript(js, jsscript, JSContextGetGlobalObject(js),
314                         jsscriptname, 0, &exception);
315         JSStringRelease(jsscript);
316         JSStringRelease(jsscriptname);
317 }
318
319 static void
320 runscript(WebKitWebFrame *frame) {
321         char *script;
322         GError *error;
323
324         if(g_file_get_contents(scriptfile, &script, NULL, &error)) {
325                 evalscript(webkit_web_frame_get_global_context(frame),
326                                 script, scriptfile);
327         }
328 }
329
330 static void
331 clipboard(Client *c, const Arg *arg) {
332         gboolean paste = *(gboolean *)arg;
333
334         if(paste) {
335                 gtk_clipboard_request_text(
336                                 gtk_clipboard_get(GDK_SELECTION_PRIMARY),
337                                 pasteuri, c);
338         } else {
339                 gtk_clipboard_set_text(
340                                 gtk_clipboard_get(GDK_SELECTION_PRIMARY),
341                                 c->linkhover ? c->linkhover : geturi(c), -1);
342         }
343 }
344
345 static char *
346 copystr(char **str, const char *src) {
347         char *tmp;
348         tmp = g_strdup(src);
349
350         if(str && *str) {
351                 g_free(*str);
352                 *str = tmp;
353         }
354         return tmp;
355 }
356
357 static WebKitWebView *
358 createwindow(WebKitWebView  *v, WebKitWebFrame *f, Client *c) {
359         Client *n = newclient();
360         return n->view;
361 }
362
363 static gboolean
364 decidedownload(WebKitWebView *v, WebKitWebFrame *f, WebKitNetworkRequest *r,
365                 gchar *m,  WebKitWebPolicyDecision *p, Client *c) {
366         if(!webkit_web_view_can_show_mime_type(v, m)) {
367                 webkit_web_policy_decision_download(p);
368                 return TRUE;
369         }
370         return FALSE;
371 }
372
373 static gboolean
374 decidewindow(WebKitWebView *view, WebKitWebFrame *f, WebKitNetworkRequest *r,
375                 WebKitWebNavigationAction *n, WebKitWebPolicyDecision *p,
376                 Client *c) {
377         Arg arg;
378
379         if(webkit_web_navigation_action_get_reason(n) ==
380                         WEBKIT_WEB_NAVIGATION_REASON_LINK_CLICKED) {
381                 webkit_web_policy_decision_ignore(p);
382                 arg.v = (void *)webkit_network_request_get_uri(r);
383                 newwindow(NULL, &arg, 0);
384                 return TRUE;
385         }
386         return FALSE;
387 }
388
389 static void
390 destroyclient(Client *c) {
391         Client *p;
392
393         webkit_web_view_stop_loading(c->view);
394         gtk_widget_destroy(GTK_WIDGET(c->view));
395         gtk_widget_destroy(c->scroll);
396         gtk_widget_destroy(c->vbox);
397         gtk_widget_destroy(c->win);
398
399         for(p = clients; p && p->next != c; p = p->next);
400         if(p) {
401                 p->next = c->next;
402         } else {
403                 clients = c->next;
404         }
405         free(c);
406         if(clients == NULL)
407                 gtk_main_quit();
408 }
409
410 static void
411 destroywin(GtkWidget* w, Client *c) {
412         destroyclient(c);
413 }
414
415 static void
416 die(const char *errstr, ...) {
417         va_list ap;
418
419         va_start(ap, errstr);
420         vfprintf(stderr, errstr, ap);
421         va_end(ap);
422         exit(EXIT_FAILURE);
423 }
424
425 static void
426 find(Client *c, const Arg *arg) {
427         const char *s;
428
429         s = getatom(c, AtomFind);
430         gboolean forward = *(gboolean *)arg;
431         webkit_web_view_search_text(c->view, s, FALSE, forward, TRUE);
432 }
433
434 static void
435 fullscreen(Client *c, const Arg *arg) {
436         if(c->fullscreen) {
437                 gtk_window_unfullscreen(GTK_WINDOW(c->win));
438         } else {
439                 gtk_window_fullscreen(GTK_WINDOW(c->win));
440         }
441         c->fullscreen = !c->fullscreen;
442 }
443
444 static const char *
445 getatom(Client *c, int a) {
446         static char buf[BUFSIZ];
447         Atom adummy;
448         int idummy;
449         unsigned long ldummy;
450         unsigned char *p = NULL;
451
452         XGetWindowProperty(dpy, GDK_WINDOW_XID(GTK_WIDGET(c->win)->window),
453                         atoms[a], 0L, BUFSIZ, False, XA_STRING,
454                         &adummy, &idummy, &ldummy, &ldummy, &p);
455         if(p) {
456                 strncpy(buf, (char *)p, LENGTH(buf)-1);
457         } else {
458                 buf[0] = '\0';
459         }
460         XFree(p);
461
462         return buf;
463 }
464
465 static char *
466 geturi(Client *c) {
467         char *uri;
468
469         if(!(uri = (char *)webkit_web_view_get_uri(c->view)))
470                 uri = "about:blank";
471         return uri;
472 }
473
474 static gboolean
475 initdownload(WebKitWebView *view, WebKitDownload *o, Client *c) {
476         Arg arg;
477
478         updatewinid(c);
479         arg = (Arg)DOWNLOAD((char *)webkit_download_get_uri(o), geturi(c));
480         spawn(c, &arg);
481         return FALSE;
482 }
483
484 static void
485 inspector(Client *c, const Arg *arg) {
486         if(c->isinspecting) {
487                 webkit_web_inspector_close(c->inspector);
488         } else {
489                 webkit_web_inspector_show(c->inspector);
490         }
491 }
492
493 static WebKitWebView *
494 inspector_new(WebKitWebInspector *i, WebKitWebView *v, Client *c) {
495         return WEBKIT_WEB_VIEW(webkit_web_view_new());
496 }
497
498 static gboolean
499 inspector_show(WebKitWebInspector *i, Client *c) {
500         WebKitWebView *w;
501
502         if(c->isinspecting)
503                 return false;
504
505         w = webkit_web_inspector_get_web_view(i);
506         gtk_paned_pack2(GTK_PANED(c->pane), GTK_WIDGET(w), TRUE, TRUE);
507         gtk_widget_show(GTK_WIDGET(w));
508         c->isinspecting = true;
509
510         return true;
511 }
512
513 static gboolean
514 inspector_close(WebKitWebInspector *i, Client *c) {
515         GtkWidget *w;
516
517         if(!c->isinspecting)
518                 return false;
519
520         w = GTK_WIDGET(webkit_web_inspector_get_web_view(i));
521         gtk_widget_hide(w);
522         gtk_widget_destroy(w);
523         c->isinspecting = false;
524
525         return true;
526 }
527
528 static void
529 inspector_finished(WebKitWebInspector *i, Client *c) {
530         g_free(c->inspector);
531 }
532
533 static gboolean
534 keypress(GtkAccelGroup *group, GObject *obj,
535                 guint key, GdkModifierType mods, Client *c) {
536         guint i;
537         gboolean processed = FALSE;
538
539         mods = CLEANMASK(mods);
540         key = gdk_keyval_to_lower(key);
541         updatewinid(c);
542         for(i = 0; i < LENGTH(keys); i++) {
543                 if(key == keys[i].keyval
544                                 && mods == keys[i].mod
545                                 && keys[i].func) {
546                         keys[i].func(c, &(keys[i].arg));
547                         processed = TRUE;
548                 }
549         }
550
551         return processed;
552 }
553
554 static void
555 linkhover(WebKitWebView *v, const char* t, const char* l, Client *c) {
556         if(l) {
557                 c->linkhover = copystr(&c->linkhover, l);
558         } else if(c->linkhover) {
559                 free(c->linkhover);
560                 c->linkhover = NULL;
561         }
562         updatetitle(c);
563 }
564
565 static void
566 loadstatuschange(WebKitWebView *view, GParamSpec *pspec, Client *c) {
567         WebKitWebFrame *frame;
568         WebKitWebDataSource *src;
569         WebKitNetworkRequest *request;
570         SoupMessage *msg;
571         char *uri;
572
573         switch(webkit_web_view_get_load_status (c->view)) {
574         case WEBKIT_LOAD_COMMITTED:
575                 uri = geturi(c);
576                 if(strstr(uri, "https://") == uri) {
577                         frame = webkit_web_view_get_main_frame(c->view);
578                         src = webkit_web_frame_get_data_source(frame);
579                         request = webkit_web_data_source_get_request(src);
580                         msg = webkit_network_request_get_message(request);
581                         c->sslfailed = soup_message_get_flags(msg)
582                                        ^ SOUP_MESSAGE_CERTIFICATE_TRUSTED;
583                 }
584                 setatom(c, AtomUri, uri);
585                 break;
586         case WEBKIT_LOAD_FINISHED:
587                 c->progress = 100;
588                 updatetitle(c);
589                 break;
590         default:
591                 break;
592         }
593 }
594
595 static void
596 loaduri(Client *c, const Arg *arg) {
597         char *u, *rp;
598         const char *uri = (char *)arg->v;
599         Arg a = { .b = FALSE };
600         struct stat st;
601
602         if(strcmp(uri, "") == 0)
603                 return;
604
605         /* In case it's a file path. */
606         if(stat(uri, &st) == 0) {
607                 rp = realpath(uri, NULL);
608                 u = g_strdup_printf("file://%s", rp);
609                 free(rp);
610         } else {
611                 u = g_strrstr(uri, "://") ? g_strdup(uri)
612                         : g_strdup_printf("http://%s", uri);
613         }
614
615         /* prevents endless loop */
616         if(c->uri && strcmp(u, c->uri) == 0) {
617                 reload(c, &a);
618         } else {
619                 webkit_web_view_load_uri(c->view, u);
620                 c->progress = 0;
621                 c->title = copystr(&c->title, u);
622                 g_free(u);
623                 updatetitle(c);
624         }
625 }
626
627 static void
628 navigate(Client *c, const Arg *arg) {
629         int steps = *(int *)arg;
630         webkit_web_view_go_back_or_forward(c->view, steps);
631 }
632
633 static Client *
634 newclient(void) {
635         Client *c;
636         WebKitWebSettings *settings;
637         WebKitWebFrame *frame;
638         GdkGeometry hints = { 1, 1 };
639         char *uri, *ua;
640
641         if(!(c = calloc(1, sizeof(Client))))
642                 die("Cannot malloc!\n");
643
644         /* Window */
645         if(embed) {
646                 c->win = gtk_plug_new(embed);
647         } else {
648                 c->win = gtk_window_new(GTK_WINDOW_TOPLEVEL);
649
650                 /* TA:  20091214:  Despite what the GNOME docs say, the ICCCM
651                  * is always correct, so we should still call this function.
652                  * But when doing so, we *must* differentiate between a
653                  * WM_CLASS and a resource on the window.  By convention, the
654                  * window class (WM_CLASS) is capped, while the resource is in
655                  * lowercase.   Both these values come as a pair.
656                  */
657                 gtk_window_set_wmclass(GTK_WINDOW(c->win), "surf", "Surf");
658
659                 /* TA:  20091214:  And set the role here as well -- so that
660                  * sessions can pick this up.
661                  */
662                 gtk_window_set_role(GTK_WINDOW(c->win), "Surf");
663         }
664         gtk_window_set_default_size(GTK_WINDOW(c->win), 800, 600);
665         g_signal_connect(G_OBJECT(c->win),
666                         "destroy",
667                         G_CALLBACK(destroywin), c);
668
669         if(!kioskmode)
670                 addaccelgroup(c);
671
672         /* Pane */
673         c->pane = gtk_vpaned_new();
674
675         /* VBox */
676         c->vbox = gtk_vbox_new(FALSE, 0);
677         gtk_paned_pack1(GTK_PANED(c->pane), c->vbox, TRUE, TRUE);
678
679         /* Webview */
680         c->view = WEBKIT_WEB_VIEW(webkit_web_view_new());
681
682         g_signal_connect(G_OBJECT(c->view),
683                         "title-changed",
684                         G_CALLBACK(titlechange), c);
685         g_signal_connect(G_OBJECT(c->view),
686                         "hovering-over-link",
687                         G_CALLBACK(linkhover), c);
688         g_signal_connect(G_OBJECT(c->view),
689                         "create-web-view",
690                         G_CALLBACK(createwindow), c);
691         g_signal_connect(G_OBJECT(c->view),
692                         "new-window-policy-decision-requested",
693                         G_CALLBACK(decidewindow), c);
694         g_signal_connect(G_OBJECT(c->view),
695                         "mime-type-policy-decision-requested",
696                         G_CALLBACK(decidedownload), c);
697         g_signal_connect(G_OBJECT(c->view),
698                         "window-object-cleared",
699                         G_CALLBACK(windowobjectcleared), c);
700         g_signal_connect(G_OBJECT(c->view),
701                         "notify::load-status",
702                         G_CALLBACK(loadstatuschange), c);
703         g_signal_connect(G_OBJECT(c->view),
704                         "notify::progress",
705                         G_CALLBACK(progresschange), c);
706         g_signal_connect(G_OBJECT(c->view),
707                         "download-requested",
708                         G_CALLBACK(initdownload), c);
709         g_signal_connect(G_OBJECT(c->view),
710                         "button-release-event",
711                         G_CALLBACK(buttonrelease), c);
712         g_signal_connect(G_OBJECT(c->view),
713                         "populate-popup",
714                         G_CALLBACK(populatepopup), c);
715         g_signal_connect(G_OBJECT(c->view),
716                         "resource-request-starting",
717                         G_CALLBACK(beforerequest), c);
718
719         /* Scrolled Window */
720         c->scroll = gtk_scrolled_window_new(NULL, NULL);
721
722         frame = webkit_web_view_get_main_frame(WEBKIT_WEB_VIEW(c->view));
723         g_signal_connect(G_OBJECT(frame), "scrollbars-policy-changed",
724                         G_CALLBACK(gtk_true), NULL);
725
726         if(!enablescrollbars) {
727                 gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(c->scroll),
728                                 GTK_POLICY_NEVER, GTK_POLICY_NEVER);
729         } else {
730                 gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(c->scroll),
731                                 GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);
732         }
733
734         /* Arranging */
735         gtk_container_add(GTK_CONTAINER(c->scroll), GTK_WIDGET(c->view));
736         gtk_container_add(GTK_CONTAINER(c->win), c->pane);
737         gtk_container_add(GTK_CONTAINER(c->vbox), c->scroll);
738
739         /* Setup */
740         gtk_box_set_child_packing(GTK_BOX(c->vbox), c->scroll, TRUE,
741                         TRUE, 0, GTK_PACK_START);
742         gtk_widget_grab_focus(GTK_WIDGET(c->view));
743         gtk_widget_show(c->pane);
744         gtk_widget_show(c->vbox);
745         gtk_widget_show(c->scroll);
746         gtk_widget_show(GTK_WIDGET(c->view));
747         gtk_widget_show(c->win);
748         gtk_window_set_geometry_hints(GTK_WINDOW(c->win), NULL, &hints,
749                         GDK_HINT_MIN_SIZE);
750         gdk_window_set_events(GTK_WIDGET(c->win)->window, GDK_ALL_EVENTS_MASK);
751         gdk_window_add_filter(GTK_WIDGET(c->win)->window, processx, c);
752         webkit_web_view_set_full_content_zoom(c->view, TRUE);
753
754         runscript(frame);
755
756         settings = webkit_web_view_get_settings(c->view);
757         if(!(ua = getenv("SURF_USERAGENT")))
758                 ua = useragent;
759         g_object_set(G_OBJECT(settings), "user-agent", ua, NULL);
760         uri = g_strconcat("file://", stylefile, NULL);
761         g_object_set(G_OBJECT(settings), "user-stylesheet-uri", uri, NULL);
762         g_object_set(G_OBJECT(settings), "auto-load-images", loadimages,
763                         NULL);
764         g_object_set(G_OBJECT(settings), "enable-plugins", enableplugins,
765                         NULL);
766         g_object_set(G_OBJECT(settings), "enable-scripts", enablescripts,
767                         NULL);
768         g_object_set(G_OBJECT(settings), "enable-spatial-navigation",
769                         enablespatialbrowsing, NULL);
770         g_object_set(G_OBJECT(settings), "enable-developer-extras",
771                         enableinspector, NULL);
772         g_object_set(G_OBJECT(settings), "enable-default-context-menu",
773                         kioskmode ^ 1, NULL);
774         g_object_set(G_OBJECT(settings), "default-font-size",
775                         defaultfontsize, NULL);
776
777         if(enableinspector) {
778                 c->inspector = WEBKIT_WEB_INSPECTOR(
779                                 webkit_web_view_get_inspector(c->view));
780                 g_signal_connect(G_OBJECT(c->inspector), "inspect-web-view",
781                                 G_CALLBACK(inspector_new), c);
782                 g_signal_connect(G_OBJECT(c->inspector), "show-window",
783                                 G_CALLBACK(inspector_show), c);
784                 g_signal_connect(G_OBJECT(c->inspector), "close-window",
785                                 G_CALLBACK(inspector_close), c);
786                 g_signal_connect(G_OBJECT(c->inspector), "finished",
787                                 G_CALLBACK(inspector_finished), c);
788                 c->isinspecting = false;
789         }
790
791         g_free(uri);
792
793         setatom(c, AtomFind, "");
794         setatom(c, AtomUri, "about:blank");
795         if(hidebackground)
796                 webkit_web_view_set_transparent(c->view, TRUE);
797
798         c->title = NULL;
799         c->next = clients;
800         clients = c;
801
802         if(showxid) {
803                 gdk_display_sync(gtk_widget_get_display(c->win));
804                 printf("%u\n",
805                         (guint)GDK_WINDOW_XID(GTK_WIDGET(c->win)->window));
806                 fflush(NULL);
807                 if (fclose(stdout) != 0) {
808                         die("Error closing stdout");
809                 }
810         }
811
812         return c;
813 }
814
815 static void
816 newwindow(Client *c, const Arg *arg, gboolean noembed) {
817         guint i = 0;
818         const char *cmd[12], *uri;
819         const Arg a = { .v = (void *)cmd };
820         char tmp[64];
821
822         cmd[i++] = argv0;
823         if(!enablescrollbars)
824                 cmd[i++] = "-b";
825         if(embed && !noembed) {
826                 cmd[i++] = "-e";
827                 snprintf(tmp, LENGTH(tmp), "%u\n", (int)embed);
828                 cmd[i++] = tmp;
829         }
830         if(!loadimages)
831                 cmd[i++] = "-i";
832         if(kioskmode)
833                 cmd[i++] = "-k";
834         if(!enableplugins)
835                 cmd[i++] = "-p";
836         if(!enablescripts)
837                 cmd[i++] = "-s";
838         if(showxid)
839                 cmd[i++] = "-x";
840         cmd[i++] = "--";
841         uri = arg->v ? (char *)arg->v : c->linkhover;
842         if(uri)
843                 cmd[i++] = uri;
844         cmd[i++] = NULL;
845         spawn(NULL, &a);
846 }
847
848 static void
849 populatepopup(WebKitWebView *web, GtkMenu *menu, Client *c) {
850         GList *items = gtk_container_get_children(GTK_CONTAINER(menu));
851
852         for(GList *l = items; l; l = l->next) {
853                 g_signal_connect(l->data, "activate", G_CALLBACK(popupactivate), c);
854         }
855
856         g_list_free(items);
857 }
858
859 static void
860 popupactivate(GtkMenuItem *menu, Client *c) {
861         /*
862          * context-menu-action-2000     open link
863          * context-menu-action-1        open link in window
864          * context-menu-action-2        download linked file
865          * context-menu-action-3        copy link location
866          * context-menu-action-13       reload
867          * context-menu-action-10       back
868          * context-menu-action-11       forward
869          * context-menu-action-12       stop
870          */
871
872         GtkAction *a = NULL;
873         const char *name;
874         GtkClipboard *prisel;
875
876         a = gtk_activatable_get_related_action(GTK_ACTIVATABLE(menu));
877         if(a == NULL)
878                 return;
879
880         name = gtk_action_get_name(a);
881         if(!g_strcmp0(name, "context-menu-action-3")) {
882                 prisel = gtk_clipboard_get(GDK_SELECTION_PRIMARY);
883                 gtk_clipboard_set_text(prisel, c->linkhover, -1);
884         }
885 }
886
887 static void
888 pasteuri(GtkClipboard *clipboard, const char *text, gpointer d) {
889         Arg arg = {.v = text };
890         if(text != NULL)
891                 loaduri((Client *) d, &arg);
892 }
893
894 static void
895 print(Client *c, const Arg *arg) {
896         webkit_web_frame_print(webkit_web_view_get_main_frame(c->view));
897 }
898
899 static GdkFilterReturn
900 processx(GdkXEvent *e, GdkEvent *event, gpointer d) {
901         Client *c = (Client *)d;
902         XPropertyEvent *ev;
903         Arg arg;
904
905         if(((XEvent *)e)->type == PropertyNotify) {
906                 ev = &((XEvent *)e)->xproperty;
907                 if(ev->state == PropertyNewValue) {
908                         if(ev->atom == atoms[AtomFind]) {
909                                 arg.b = TRUE;
910                                 find(c, &arg);
911
912                                 return GDK_FILTER_REMOVE;
913                         } else if(ev->atom == atoms[AtomGo]) {
914                                 arg.v = getatom(c, AtomGo);
915                                 loaduri(c, &arg);
916
917                                 return GDK_FILTER_REMOVE;
918                         }
919                 }
920         }
921         return GDK_FILTER_CONTINUE;
922 }
923
924 static void
925 progresschange(WebKitWebView *view, GParamSpec *pspec, Client *c) {
926         c->progress = webkit_web_view_get_progress(c->view) * 100;
927         updatetitle(c);
928 }
929
930 static void
931 reload(Client *c, const Arg *arg) {
932         gboolean nocache = *(gboolean *)arg;
933         if(nocache) {
934                  webkit_web_view_reload_bypass_cache(c->view);
935         } else {
936                  webkit_web_view_reload(c->view);
937         }
938 }
939
940 static void
941 scroll_h(Client *c, const Arg *arg) {
942         scroll(gtk_scrolled_window_get_hadjustment(
943                                 GTK_SCROLLED_WINDOW(c->scroll)), arg);
944 }
945
946 static void
947 scroll_v(Client *c, const Arg *arg) {
948         scroll(gtk_scrolled_window_get_vadjustment(
949                                 GTK_SCROLLED_WINDOW(c->scroll)), arg);
950 }
951
952 static void
953 scroll(GtkAdjustment *a, const Arg *arg) {
954         gdouble v;
955
956         v = gtk_adjustment_get_value(a);
957         switch (arg->i){
958         case +10000:
959         case -10000:
960                 v += gtk_adjustment_get_page_increment(a) *
961                         (arg->i / 10000);
962                 break;
963         case +20000:
964         case -20000:
965         default:
966                 v += gtk_adjustment_get_step_increment(a) * arg->i;
967         }
968
969         v = MAX(v, 0.0);
970         v = MIN(v, gtk_adjustment_get_upper(a) -
971                         gtk_adjustment_get_page_size(a));
972         gtk_adjustment_set_value(a, v);
973 }
974
975 static void
976 setatom(Client *c, int a, const char *v) {
977         XSync(dpy, False);
978         XChangeProperty(dpy, GDK_WINDOW_XID(GTK_WIDGET(c->win)->window),
979                         atoms[a], XA_STRING, 8, PropModeReplace,
980                         (unsigned char *)v, strlen(v) + 1);
981 }
982
983 static void
984 setup(void) {
985         char *proxy;
986         char *new_proxy;
987         SoupURI *puri;
988         SoupSession *s;
989
990         /* clean up any zombies immediately */
991         sigchld(0);
992         gtk_init(NULL, NULL);
993
994         dpy = GDK_DISPLAY();
995
996         /* atoms */
997         atoms[AtomFind] = XInternAtom(dpy, "_SURF_FIND", False);
998         atoms[AtomGo] = XInternAtom(dpy, "_SURF_GO", False);
999         atoms[AtomUri] = XInternAtom(dpy, "_SURF_URI", False);
1000
1001         /* dirs and files */
1002         cookiefile = buildpath(cookiefile);
1003         scriptfile = buildpath(scriptfile);
1004         stylefile = buildpath(stylefile);
1005
1006         /* request handler */
1007         s = webkit_get_default_session();
1008
1009         /* cookie jar */
1010         soup_session_add_feature(s,
1011                         SOUP_SESSION_FEATURE(cookiejar_new(cookiefile,
1012                                         FALSE)));
1013
1014         /* ssl */
1015         g_object_set(G_OBJECT(s), "ssl-ca-file", cafile, NULL);
1016         g_object_set(G_OBJECT(s), "ssl-strict", strictssl, NULL);
1017
1018         /* proxy */
1019         if((proxy = getenv("http_proxy")) && strcmp(proxy, "")) {
1020                 new_proxy = g_strrstr(proxy, "http://") ? g_strdup(proxy) :
1021                         g_strdup_printf("http://%s", proxy);
1022                 puri = soup_uri_new(new_proxy);
1023                 g_object_set(G_OBJECT(s), "proxy-uri", puri, NULL);
1024                 soup_uri_free(puri);
1025                 g_free(new_proxy);
1026                 usingproxy = 1;
1027         }
1028 }
1029
1030 static void
1031 sigchld(int unused) {
1032         if(signal(SIGCHLD, sigchld) == SIG_ERR)
1033                 die("Can't install SIGCHLD handler");
1034         while(0 < waitpid(-1, NULL, WNOHANG));
1035 }
1036
1037 static void
1038 source(Client *c, const Arg *arg) {
1039         Arg a = { .b = FALSE };
1040         gboolean s;
1041
1042         s = webkit_web_view_get_view_source_mode(c->view);
1043         webkit_web_view_set_view_source_mode(c->view, !s);
1044         reload(c, &a);
1045 }
1046
1047 static void
1048 spawn(Client *c, const Arg *arg) {
1049         if(fork() == 0) {
1050                 if(dpy)
1051                         close(ConnectionNumber(dpy));
1052                 setsid();
1053                 execvp(((char **)arg->v)[0], (char **)arg->v);
1054                 fprintf(stderr, "surf: execvp %s", ((char **)arg->v)[0]);
1055                 perror(" failed");
1056                 exit(0);
1057         }
1058 }
1059
1060 static void
1061 eval(Client *c, const Arg *arg) {
1062         WebKitWebFrame *frame = webkit_web_view_get_main_frame(c->view);
1063         evalscript(webkit_web_frame_get_global_context(frame),
1064                         ((char **)arg->v)[0], "");
1065 }
1066
1067 static void
1068 stop(Client *c, const Arg *arg) {
1069         webkit_web_view_stop_loading(c->view);
1070 }
1071
1072 static void
1073 titlechange(WebKitWebView *v, WebKitWebFrame *f, const char *t, Client *c) {
1074         c->title = copystr(&c->title, t);
1075         updatetitle(c);
1076 }
1077
1078 static void
1079 toggle(Client *c, const Arg *arg) {
1080         WebKitWebSettings *settings;
1081         char *name = (char *)arg->v;
1082         gboolean value;
1083         Arg a = { .b = FALSE };
1084
1085         settings = webkit_web_view_get_settings(c->view);
1086         g_object_get(G_OBJECT(settings), name, &value, NULL);
1087         g_object_set(G_OBJECT(settings), name, !value, NULL);
1088
1089         reload(c,&a);
1090 }
1091
1092 static void
1093 twitch(Client *c, const Arg *arg) {
1094         GtkAdjustment *a;
1095         gdouble v;
1096
1097         a = gtk_scrolled_window_get_vadjustment(
1098                         GTK_SCROLLED_WINDOW(c->scroll));
1099
1100         v = gtk_adjustment_get_value(a);
1101
1102         v += arg->i;
1103
1104         v = MAX(v, 0.0);
1105         v = MIN(v, gtk_adjustment_get_upper(a) -
1106                         gtk_adjustment_get_page_size(a));
1107         gtk_adjustment_set_value(a, v);
1108 }
1109
1110 static void
1111 togglescrollbars(Client *c, const Arg *arg) {
1112         GtkPolicyType vspolicy;
1113         Arg a;
1114
1115         gtk_scrolled_window_get_policy(GTK_SCROLLED_WINDOW(c->scroll), NULL, &vspolicy);
1116
1117         if(vspolicy == GTK_POLICY_AUTOMATIC) {
1118                 gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(c->scroll),
1119                                 GTK_POLICY_NEVER, GTK_POLICY_NEVER);
1120         } else {
1121                 gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(c->scroll),
1122                                 GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);
1123                 a.i = +1;
1124                 twitch(c, &a);
1125                 a.i = -1;
1126                 twitch(c, &a);
1127         }
1128 }
1129
1130 static void
1131 togglestyle(Client *c, const Arg *arg) {
1132         WebKitWebSettings *settings;
1133         char *uri;
1134
1135         settings = webkit_web_view_get_settings(c->view);
1136         g_object_get(G_OBJECT(settings), "user-stylesheet-uri", &uri, NULL);
1137         uri = uri[0] ? g_strdup("") : g_strconcat("file://", stylefile, NULL);
1138         g_object_set(G_OBJECT(settings), "user-stylesheet-uri", uri, NULL);
1139
1140         updatetitle(c);
1141 }
1142
1143 static void
1144 gettogglestat(Client *c){
1145         gboolean value;
1146         char *uri;
1147         WebKitWebSettings *settings = webkit_web_view_get_settings(c->view);
1148
1149         g_object_get(G_OBJECT(settings), "enable-caret-browsing",
1150                         &value, NULL);
1151         togglestat[0] = value? 'C': 'c';
1152
1153         g_object_get(G_OBJECT(settings), "auto-load-images", &value, NULL);
1154         togglestat[1] = value? 'I': 'i';
1155
1156         g_object_get(G_OBJECT(settings), "enable-scripts", &value, NULL);
1157         togglestat[2] = value? 'S': 's';
1158
1159         g_object_get(G_OBJECT(settings), "enable-plugins", &value, NULL);
1160         togglestat[3] = value? 'V': 'v';
1161
1162         g_object_get(G_OBJECT(settings), "user-stylesheet-uri", &uri, NULL);
1163         togglestat[4] = uri[0] ? 'M': 'm';
1164
1165         togglestat[5] = '\0';
1166 }
1167
1168 static void
1169 getpagestat(Client *c) {
1170         const char *uri = geturi(c);
1171
1172         if(strstr(uri, "https://") == uri) {
1173                 pagestat[0] = c->sslfailed ? 'U' : 'T';
1174         } else {
1175                 pagestat[0] = '-';
1176         }
1177
1178         pagestat[1] = usingproxy ? 'P' : '-';
1179         pagestat[2] = '\0';
1180
1181 }
1182
1183 static void
1184 updatetitle(Client *c) {
1185         char *t;
1186
1187         if(showindicators) {
1188                 gettogglestat(c);
1189                 getpagestat(c);
1190
1191                 if(c->linkhover) {
1192                         t = g_strdup_printf("%s:%s | %s", togglestat,
1193                                         pagestat, c->linkhover);
1194                 } else if(c->progress != 100) {
1195                         t = g_strdup_printf("[%i%%] %s:%s | %s", c->progress,
1196                                         togglestat, pagestat, c->title);
1197                 } else {
1198                         t = g_strdup_printf("%s:%s | %s", togglestat, pagestat,
1199                                         c->title);
1200                 }
1201
1202                 gtk_window_set_title(GTK_WINDOW(c->win), t);
1203                 g_free(t);
1204         } else {
1205                 gtk_window_set_title(GTK_WINDOW(c->win), c->title);
1206         }
1207 }
1208
1209 static void
1210 updatewinid(Client *c) {
1211         snprintf(winid, LENGTH(winid), "%u",
1212                         (int)GDK_WINDOW_XID(GTK_WIDGET(c->win)->window));
1213 }
1214
1215 static void
1216 usage(void) {
1217         die("usage: %s [-biknpsvx] [-c cookiefile] [-e xid] [-r scriptfile]"
1218                 " [-t stylefile] [-u useragent] [uri]\n", basename(argv0));
1219 }
1220
1221 static void
1222 windowobjectcleared(GtkWidget *w, WebKitWebFrame *frame, JSContextRef js,
1223                 JSObjectRef win, Client *c) {
1224         runscript(frame);
1225 }
1226
1227 static void
1228 zoom(Client *c, const Arg *arg) {
1229         c->zoomed = TRUE;
1230         if(arg->i < 0) {
1231                 /* zoom out */
1232                 webkit_web_view_zoom_out(c->view);
1233         } else if(arg->i > 0) {
1234                 /* zoom in */
1235                 webkit_web_view_zoom_in(c->view);
1236         } else {
1237                 /* reset */
1238                 c->zoomed = FALSE;
1239                 webkit_web_view_set_zoom_level(c->view, 1.0);
1240         }
1241 }
1242
1243 int
1244 main(int argc, char *argv[]) {
1245         Arg arg;
1246
1247         memset(&arg, 0, sizeof(arg));
1248
1249         /* command line args */
1250         ARGBEGIN {
1251         case 'b':
1252                 enablescrollbars = 0;
1253                 break;
1254         case 'c':
1255                 cookiefile = EARGF(usage());
1256                 break;
1257         case 'e':
1258                 embed = strtol(EARGF(usage()), NULL, 0);
1259                 break;
1260         case 'i':
1261                 loadimages = 0;
1262                 break;
1263         case 'k':
1264                 kioskmode = 1;
1265                 break;
1266         case 'n':
1267                 enableinspector = 0;
1268                 break;
1269         case 'p':
1270                 enableplugins = 0;
1271                 break;
1272         case 'r':
1273                 scriptfile = EARGF(usage());
1274                 break;
1275         case 's':
1276                 enablescripts = 0;
1277                 break;
1278         case 't':
1279                 stylefile = EARGF(usage());
1280                 break;
1281         case 'u':
1282                 useragent = EARGF(usage());
1283                 break;
1284         case 'v':
1285                 die("surf-"VERSION", ©2009-2012 surf engineers, "
1286                                 "see LICENSE for details\n");
1287         case 'x':
1288                 showxid = TRUE;
1289                 break;
1290         default:
1291                 usage();
1292         } ARGEND;
1293         if(argc > 0)
1294                 arg.v = argv[0];
1295
1296         setup();
1297         newclient();
1298         if(arg.v)
1299                 loaduri(clients, &arg);
1300
1301         gtk_main();
1302         cleanup();
1303
1304         return EXIT_SUCCESS;
1305 }
1306