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