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