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