Adding kiosk mode.
[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
581         if(strcmp(uri, "") == 0)
582                 return;
583
584         /* In case it's a file path. */
585         if(uri[0] == '/') {
586                 rp = realpath(uri, NULL);
587                 u = g_strdup_printf("file://%s", rp);
588                 free(rp);
589         } else {
590                 u = g_strrstr(uri, "://") ? g_strdup(uri)
591                         : g_strdup_printf("http://%s", uri);
592         }
593
594         /* prevents endless loop */
595         if(c->uri && strcmp(u, c->uri) == 0) {
596                 reload(c, &a);
597         } else {
598                 webkit_web_view_load_uri(c->view, u);
599                 c->progress = 0;
600                 c->title = copystr(&c->title, u);
601                 g_free(u);
602                 update(c);
603         }
604 }
605
606 static void
607 navigate(Client *c, const Arg *arg) {
608         int steps = *(int *)arg;
609         webkit_web_view_go_back_or_forward(c->view, steps);
610 }
611
612 static Client *
613 newclient(void) {
614         Client *c;
615         WebKitWebSettings *settings;
616         WebKitWebFrame *frame;
617         GdkGeometry hints = { 1, 1 };
618         char *uri, *ua;
619
620         if(!(c = calloc(1, sizeof(Client))))
621                 die("Cannot malloc!\n");
622
623         /* Window */
624         if(embed) {
625                 c->win = gtk_plug_new(embed);
626         } else {
627                 c->win = gtk_window_new(GTK_WINDOW_TOPLEVEL);
628
629                 /* TA:  20091214:  Despite what the GNOME docs say, the ICCCM
630                  * is always correct, so we should still call this function.
631                  * But when doing so, we *must* differentiate between a
632                  * WM_CLASS and a resource on the window.  By convention, the
633                  * window class (WM_CLASS) is capped, while the resource is in
634                  * lowercase.   Both these values come as a pair.
635                  */
636                 gtk_window_set_wmclass(GTK_WINDOW(c->win), "surf", "Surf");
637
638                 /* TA:  20091214:  And set the role here as well -- so that
639                  * sessions can pick this up.
640                  */
641                 gtk_window_set_role(GTK_WINDOW(c->win), "Surf");
642         }
643         gtk_window_set_default_size(GTK_WINDOW(c->win), 800, 600);
644         g_signal_connect(G_OBJECT(c->win),
645                         "destroy",
646                         G_CALLBACK(destroywin), c);
647         if(!kioskmode) {
648                 g_signal_connect(G_OBJECT(c->win),
649                                 "key-press-event",
650                                 G_CALLBACK(keypress), c);
651         }
652
653         /* Pane */
654         c->pane = gtk_vpaned_new();
655
656         /* VBox */
657         c->vbox = gtk_vbox_new(FALSE, 0);
658         gtk_paned_pack1(GTK_PANED(c->pane), c->vbox, TRUE, TRUE);
659
660         /* Webview */
661         c->view = WEBKIT_WEB_VIEW(webkit_web_view_new());
662
663         g_signal_connect(G_OBJECT(c->view),
664                         "title-changed",
665                         G_CALLBACK(titlechange), c);
666         g_signal_connect(G_OBJECT(c->view),
667                         "hovering-over-link",
668                         G_CALLBACK(linkhover), c);
669         g_signal_connect(G_OBJECT(c->view),
670                         "create-web-view",
671                         G_CALLBACK(createwindow), c);
672         g_signal_connect(G_OBJECT(c->view),
673                         "new-window-policy-decision-requested",
674                         G_CALLBACK(decidewindow), c);
675         g_signal_connect(G_OBJECT(c->view),
676                         "mime-type-policy-decision-requested",
677                         G_CALLBACK(decidedownload), c);
678         g_signal_connect(G_OBJECT(c->view),
679                         "window-object-cleared",
680                         G_CALLBACK(windowobjectcleared), c);
681         g_signal_connect(G_OBJECT(c->view),
682                         "notify::load-status",
683                         G_CALLBACK(loadstatuschange), c);
684         g_signal_connect(G_OBJECT(c->view),
685                         "notify::progress",
686                         G_CALLBACK(progresschange), c);
687         g_signal_connect(G_OBJECT(c->view),
688                         "download-requested",
689                         G_CALLBACK(initdownload), c);
690         g_signal_connect(G_OBJECT(c->view),
691                         "button-release-event",
692                         G_CALLBACK(buttonrelease), c);
693         g_signal_connect(G_OBJECT(c->view),
694                         "populate-popup",
695                         G_CALLBACK(populatepopup), c);
696         g_signal_connect(G_OBJECT(c->view),
697                         "resource-request-starting",
698                         G_CALLBACK(beforerequest), c);
699
700         /* Scrolled Window */
701         c->scroll = gtk_scrolled_window_new(NULL, NULL);
702
703         frame = webkit_web_view_get_main_frame(WEBKIT_WEB_VIEW(c->view));
704         g_signal_connect(G_OBJECT(frame), "scrollbars-policy-changed",
705                         G_CALLBACK(gtk_true), NULL);
706
707         if(!enablescrollbars) {
708                 gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(c->scroll),
709                                 GTK_POLICY_NEVER, GTK_POLICY_NEVER);
710         } else {
711                 gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(c->scroll),
712                                 GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);
713         }
714
715         /* Arranging */
716         gtk_container_add(GTK_CONTAINER(c->scroll), GTK_WIDGET(c->view));
717         gtk_container_add(GTK_CONTAINER(c->win), c->pane);
718         gtk_container_add(GTK_CONTAINER(c->vbox), c->scroll);
719
720         /* Setup */
721         gtk_box_set_child_packing(GTK_BOX(c->vbox), c->scroll, TRUE,
722                         TRUE, 0, GTK_PACK_START);
723         gtk_widget_grab_focus(GTK_WIDGET(c->view));
724         gtk_widget_show(c->pane);
725         gtk_widget_show(c->vbox);
726         gtk_widget_show(c->scroll);
727         gtk_widget_show(GTK_WIDGET(c->view));
728         gtk_widget_show(c->win);
729         gtk_window_set_geometry_hints(GTK_WINDOW(c->win), NULL, &hints,
730                         GDK_HINT_MIN_SIZE);
731         gdk_window_set_events(GTK_WIDGET(c->win)->window, GDK_ALL_EVENTS_MASK);
732         gdk_window_add_filter(GTK_WIDGET(c->win)->window, processx, c);
733         webkit_web_view_set_full_content_zoom(c->view, TRUE);
734
735         runscript(frame);
736
737         settings = webkit_web_view_get_settings(c->view);
738         if(!(ua = getenv("SURF_USERAGENT")))
739                 ua = useragent;
740         g_object_set(G_OBJECT(settings), "user-agent", ua, NULL);
741         uri = g_strconcat("file://", stylefile, NULL);
742         g_object_set(G_OBJECT(settings), "user-stylesheet-uri", uri, NULL);
743         g_object_set(G_OBJECT(settings), "auto-load-images", loadimages,
744                         NULL);
745         g_object_set(G_OBJECT(settings), "enable-plugins", enableplugins,
746                         NULL);
747         g_object_set(G_OBJECT(settings), "enable-scripts", enablescripts,
748                         NULL);
749         g_object_set(G_OBJECT(settings), "enable-spatial-navigation",
750                         enablespatialbrowsing, NULL);
751         g_object_set(G_OBJECT(settings), "enable-developer-extras",
752                         enableinspector, NULL);
753         g_object_set(G_OBJECT(settings), "enable-default-context-menu",
754                         kioskmode ^ 1, NULL);
755
756         if(enableinspector) {
757                 c->inspector = WEBKIT_WEB_INSPECTOR(
758                                 webkit_web_view_get_inspector(c->view));
759                 g_signal_connect(G_OBJECT(c->inspector), "inspect-web-view",
760                                 G_CALLBACK(inspector_new), c);
761                 g_signal_connect(G_OBJECT(c->inspector), "show-window",
762                                 G_CALLBACK(inspector_show), c);
763                 g_signal_connect(G_OBJECT(c->inspector), "close-window",
764                                 G_CALLBACK(inspector_close), c);
765                 g_signal_connect(G_OBJECT(c->inspector), "finished",
766                                 G_CALLBACK(inspector_finished), c);
767                 c->isinspecting = false;
768         }
769
770         g_free(uri);
771
772         setatom(c, AtomFind, "");
773         setatom(c, AtomUri, "about:blank");
774         if(hidebackground)
775                 webkit_web_view_set_transparent(c->view, TRUE);
776
777         c->title = NULL;
778         c->next = clients;
779         clients = c;
780
781         if(showxid) {
782                 gdk_display_sync(gtk_widget_get_display(c->win));
783                 printf("%u\n",
784                         (guint)GDK_WINDOW_XID(GTK_WIDGET(c->win)->window));
785                 fflush(NULL);
786                 if (fclose(stdout) != 0) {
787                         die("Error closing stdout");
788                 }
789         }
790
791         return c;
792 }
793
794 static void
795 newwindow(Client *c, const Arg *arg, gboolean noembed) {
796         guint i = 0;
797         const char *cmd[12], *uri;
798         const Arg a = { .v = (void *)cmd };
799         char tmp[64];
800
801         cmd[i++] = argv0;
802         if(!enablescrollbars)
803                 cmd[i++] = "-b";
804         if(embed && !noembed) {
805                 cmd[i++] = "-e";
806                 snprintf(tmp, LENGTH(tmp), "%u\n", (int)embed);
807                 cmd[i++] = tmp;
808         }
809         if(!loadimages)
810                 cmd[i++] = "-i";
811         if(!kioskmode)
812                 cmd[i++] = "-k";
813         if(!enableplugins)
814                 cmd[i++] = "-p";
815         if(!enablescripts)
816                 cmd[i++] = "-s";
817         if(showxid)
818                 cmd[i++] = "-x";
819         cmd[i++] = "--";
820         uri = arg->v ? (char *)arg->v : c->linkhover;
821         if(uri)
822                 cmd[i++] = uri;
823         cmd[i++] = NULL;
824         spawn(NULL, &a);
825 }
826
827 static void
828 populatepopup(WebKitWebView *web, GtkMenu *menu, Client *c) {
829         GList *items = gtk_container_get_children(GTK_CONTAINER(menu));
830
831         for(GList *l = items; l; l = l->next) {
832                 g_signal_connect(l->data, "activate", G_CALLBACK(popupactivate), c);
833         }
834
835         g_list_free(items);
836 }
837
838 static void
839 popupactivate(GtkMenuItem *menu, Client *c) {
840         /*
841          * context-menu-action-2000     open link
842          * context-menu-action-1        open link in window
843          * context-menu-action-2        download linked file
844          * context-menu-action-3        copy link location
845          * context-menu-action-13       reload
846          * context-menu-action-10       back
847          * context-menu-action-11       forward
848          * context-menu-action-12       stop
849          */
850
851         GtkAction *a = NULL;
852         const char *name;
853         GtkClipboard *prisel;
854
855         a = gtk_activatable_get_related_action(GTK_ACTIVATABLE(menu));
856         if(a == NULL)
857                 return;
858
859         name = gtk_action_get_name(a);
860         if(!g_strcmp0(name, "context-menu-action-3")) {
861                 prisel = gtk_clipboard_get(GDK_SELECTION_PRIMARY);
862                 gtk_clipboard_set_text(prisel, c->linkhover, -1);
863         }
864 }
865
866 static void
867 pasteuri(GtkClipboard *clipboard, const char *text, gpointer d) {
868         Arg arg = {.v = text };
869         if(text != NULL)
870                 loaduri((Client *) d, &arg);
871 }
872
873 static void
874 print(Client *c, const Arg *arg) {
875         webkit_web_frame_print(webkit_web_view_get_main_frame(c->view));
876 }
877
878 static GdkFilterReturn
879 processx(GdkXEvent *e, GdkEvent *event, gpointer d) {
880         Client *c = (Client *)d;
881         XPropertyEvent *ev;
882         Arg arg;
883
884         if(((XEvent *)e)->type == PropertyNotify) {
885                 ev = &((XEvent *)e)->xproperty;
886                 if(ev->state == PropertyNewValue) {
887                         if(ev->atom == atoms[AtomFind]) {
888                                 arg.b = TRUE;
889                                 find(c, &arg);
890                                 return GDK_FILTER_REMOVE;
891                         }
892                         else if(ev->atom == atoms[AtomGo]) {
893                                 arg.v = getatom(c, AtomGo);
894                                 loaduri(c, &arg);
895                                 return GDK_FILTER_REMOVE;
896                         }
897                 }
898         }
899         return GDK_FILTER_CONTINUE;
900 }
901
902 static void
903 progresschange(WebKitWebView *view, GParamSpec *pspec, Client *c) {
904         c->progress = webkit_web_view_get_progress(c->view) * 100;
905         update(c);
906 }
907
908 static void
909 reload(Client *c, const Arg *arg) {
910         gboolean nocache = *(gboolean *)arg;
911         if(nocache) {
912                  webkit_web_view_reload_bypass_cache(c->view);
913         } else {
914                  webkit_web_view_reload(c->view);
915         }
916 }
917
918 static void
919 scroll_h(Client *c, const Arg *arg) {
920         scroll(gtk_scrolled_window_get_hadjustment(
921                                 GTK_SCROLLED_WINDOW(c->scroll)), arg);
922 }
923
924 static void
925 scroll_v(Client *c, const Arg *arg) {
926         scroll(gtk_scrolled_window_get_vadjustment(
927                                 GTK_SCROLLED_WINDOW(c->scroll)), arg);
928 }
929
930 static void
931 scroll(GtkAdjustment *a, const Arg *arg) {
932         gdouble v;
933
934         v = gtk_adjustment_get_value(a);
935         switch (arg->i){
936         case +10000:
937         case -10000:
938                 v += gtk_adjustment_get_page_increment(a) *
939                         (arg->i / 10000);
940                 break;
941         case +20000:
942         case -20000:
943         default:
944                 v += gtk_adjustment_get_step_increment(a) * arg->i;
945         }
946
947         v = MAX(v, 0.0);
948         v = MIN(v, gtk_adjustment_get_upper(a) -
949                         gtk_adjustment_get_page_size(a));
950         gtk_adjustment_set_value(a, v);
951 }
952
953 static void
954 setatom(Client *c, int a, const char *v) {
955         XSync(dpy, False);
956         XChangeProperty(dpy, GDK_WINDOW_XID(GTK_WIDGET(c->win)->window),
957                         atoms[a], XA_STRING, 8, PropModeReplace,
958                         (unsigned char *)v, strlen(v) + 1);
959 }
960
961 static void
962 setup(void) {
963         char *proxy;
964         char *new_proxy;
965         SoupURI *puri;
966         SoupSession *s;
967
968         /* clean up any zombies immediately */
969         sigchld(0);
970         gtk_init(NULL, NULL);
971
972         dpy = GDK_DISPLAY();
973
974         /* atoms */
975         atoms[AtomFind] = XInternAtom(dpy, "_SURF_FIND", False);
976         atoms[AtomGo] = XInternAtom(dpy, "_SURF_GO", False);
977         atoms[AtomUri] = XInternAtom(dpy, "_SURF_URI", False);
978
979         /* dirs and files */
980         cookiefile = buildpath(cookiefile);
981         scriptfile = buildpath(scriptfile);
982         stylefile = buildpath(stylefile);
983
984         /* request handler */
985         s = webkit_get_default_session();
986
987         /* cookie jar */
988         soup_session_add_feature(s,
989                         SOUP_SESSION_FEATURE(cookiejar_new(cookiefile,
990                                         FALSE)));
991
992         /* ssl */
993         g_object_set(G_OBJECT(s), "ssl-ca-file", cafile, NULL);
994         g_object_set(G_OBJECT(s), "ssl-strict", strictssl, NULL);
995
996         /* proxy */
997         if((proxy = getenv("http_proxy")) && strcmp(proxy, "")) {
998                 new_proxy = g_strrstr(proxy, "http://") ? g_strdup(proxy) :
999                         g_strdup_printf("http://%s", proxy);
1000                 puri = soup_uri_new(new_proxy);
1001                 g_object_set(G_OBJECT(s), "proxy-uri", puri, NULL);
1002                 soup_uri_free(puri);
1003                 g_free(new_proxy);
1004                 usingproxy = 1;
1005         }
1006 }
1007
1008 static void
1009 sigchld(int unused) {
1010         if(signal(SIGCHLD, sigchld) == SIG_ERR)
1011                 die("Can't install SIGCHLD handler");
1012         while(0 < waitpid(-1, NULL, WNOHANG));
1013 }
1014
1015 static void
1016 source(Client *c, const Arg *arg) {
1017         Arg a = { .b = FALSE };
1018         gboolean s;
1019
1020         s = webkit_web_view_get_view_source_mode(c->view);
1021         webkit_web_view_set_view_source_mode(c->view, !s);
1022         reload(c, &a);
1023 }
1024
1025 static void
1026 spawn(Client *c, const Arg *arg) {
1027         if(fork() == 0) {
1028                 if(dpy)
1029                         close(ConnectionNumber(dpy));
1030                 setsid();
1031                 execvp(((char **)arg->v)[0], (char **)arg->v);
1032                 fprintf(stderr, "surf: execvp %s", ((char **)arg->v)[0]);
1033                 perror(" failed");
1034                 exit(0);
1035         }
1036 }
1037
1038 static void
1039 eval(Client *c, const Arg *arg) {
1040         WebKitWebFrame *frame = webkit_web_view_get_main_frame(c->view);
1041         evalscript(webkit_web_frame_get_global_context(frame),
1042                         ((char **)arg->v)[0], "");
1043 }
1044
1045 static void
1046 stop(Client *c, const Arg *arg) {
1047         webkit_web_view_stop_loading(c->view);
1048 }
1049
1050 static void
1051 titlechange(WebKitWebView *v, WebKitWebFrame *f, const char *t, Client *c) {
1052         c->title = copystr(&c->title, t);
1053         update(c);
1054 }
1055
1056 static void
1057 toggle(Client *c, const Arg *arg) {
1058         WebKitWebSettings *settings;
1059         char *name = (char *)arg->v;
1060         gboolean value;
1061         Arg a = { .b = FALSE };
1062
1063         settings = webkit_web_view_get_settings(c->view);
1064         g_object_get(G_OBJECT(settings), name, &value, NULL);
1065         g_object_set(G_OBJECT(settings), name, !value, NULL);
1066
1067         reload(c,&a);
1068 }
1069
1070 static void
1071 twitch(Client *c, const Arg *arg) {
1072         GtkAdjustment *a;
1073         gdouble v;
1074
1075         a = gtk_scrolled_window_get_vadjustment(
1076                         GTK_SCROLLED_WINDOW(c->scroll));
1077
1078         v = gtk_adjustment_get_value(a);
1079
1080         v += arg->i;
1081
1082         v = MAX(v, 0.0);
1083         v = MIN(v, gtk_adjustment_get_upper(a) -
1084                         gtk_adjustment_get_page_size(a));
1085         gtk_adjustment_set_value(a, v);
1086 }
1087
1088 static void
1089 togglescrollbars(Client *c, const Arg *arg) {
1090         GtkPolicyType vspolicy;
1091         Arg a;
1092
1093         gtk_scrolled_window_get_policy(GTK_SCROLLED_WINDOW(c->scroll), NULL, &vspolicy);
1094
1095         if(vspolicy == GTK_POLICY_AUTOMATIC) {
1096                 gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(c->scroll),
1097                                 GTK_POLICY_NEVER, GTK_POLICY_NEVER);
1098         } else {
1099                 gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(c->scroll),
1100                                 GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);
1101                 a.i = +1;
1102                 twitch(c, &a);
1103                 a.i = -1;
1104                 twitch(c, &a);
1105         }
1106 }
1107
1108 static void
1109 togglestyle(Client *c, const Arg *arg) {
1110         WebKitWebSettings *settings;
1111         char *uri;
1112
1113         settings = webkit_web_view_get_settings(c->view);
1114         g_object_get(G_OBJECT(settings), "user-stylesheet-uri", &uri, NULL);
1115         uri = uri[0] ? g_strdup("") : g_strconcat("file://", stylefile, NULL);
1116         g_object_set(G_OBJECT(settings), "user-stylesheet-uri", uri, NULL);
1117
1118         update(c);
1119 }
1120
1121 static void
1122 gettogglestat(Client *c){
1123         gboolean value;
1124         char *uri;
1125         WebKitWebSettings *settings = webkit_web_view_get_settings(c->view);
1126
1127         g_object_get(G_OBJECT(settings), "enable-caret-browsing",
1128                         &value, NULL);
1129         togglestat[0] = value? 'C': 'c';
1130
1131         g_object_get(G_OBJECT(settings), "auto-load-images", &value, NULL);
1132         togglestat[1] = value? 'I': 'i';
1133
1134         g_object_get(G_OBJECT(settings), "enable-scripts", &value, NULL);
1135         togglestat[2] = value? 'S': 's';
1136
1137         g_object_get(G_OBJECT(settings), "enable-plugins", &value, NULL);
1138         togglestat[3] = value? 'V': 'v';
1139
1140         g_object_get(G_OBJECT(settings), "user-stylesheet-uri", &uri, NULL);
1141         togglestat[4] = uri[0] ? 'M': 'm';
1142
1143         togglestat[5] = '\0';
1144 }
1145
1146 static void
1147 getpagestat(Client *c) {
1148         const char *uri = geturi(c);
1149
1150         if(strstr(uri, "https://") == uri) {
1151                 pagestat[0] = c->sslfailed ? 'U' : 'T';
1152         } else {
1153                 pagestat[0] = '-';
1154         }
1155
1156         pagestat[1] = usingproxy ? 'P' : '-';
1157         pagestat[2] = '\0';
1158
1159 }
1160
1161 static void
1162 update(Client *c) {
1163         char *t;
1164
1165         gettogglestat(c);
1166         getpagestat(c);
1167
1168         if(c->linkhover) {
1169                 t = g_strdup_printf("%s:%s | %s", togglestat, pagestat, c->linkhover);
1170         } else if(c->progress != 100) {
1171                 t = g_strdup_printf("[%i%%] %s:%s | %s", c->progress, togglestat,
1172                         pagestat, c->title);
1173         } else {
1174                 t = g_strdup_printf("%s:%s | %s", togglestat, pagestat, c->title);
1175         }
1176
1177         gtk_window_set_title(GTK_WINDOW(c->win), t);
1178         g_free(t);
1179 }
1180
1181 static void
1182 updatewinid(Client *c) {
1183         snprintf(winid, LENGTH(winid), "%u",
1184                         (int)GDK_WINDOW_XID(GTK_WIDGET(c->win)->window));
1185 }
1186
1187 static void
1188 usage(void) {
1189         die("usage: %s [-biknpsvx] [-c cookiefile] [-e xid] [-r scriptfile]"
1190                 " [-t stylefile] [-u useragent] [uri]\n", basename(argv0));
1191 }
1192
1193 static void
1194 windowobjectcleared(GtkWidget *w, WebKitWebFrame *frame, JSContextRef js,
1195                 JSObjectRef win, Client *c) {
1196         runscript(frame);
1197 }
1198
1199 static void
1200 zoom(Client *c, const Arg *arg) {
1201         c->zoomed = TRUE;
1202         if(arg->i < 0) {
1203                 /* zoom out */
1204                 webkit_web_view_zoom_out(c->view);
1205         } else if(arg->i > 0) {
1206                 /* zoom in */
1207                 webkit_web_view_zoom_in(c->view);
1208         } else {
1209                 /* reset */
1210                 c->zoomed = FALSE;
1211                 webkit_web_view_set_zoom_level(c->view, 1.0);
1212         }
1213 }
1214
1215 int
1216 main(int argc, char *argv[]) {
1217         Arg arg;
1218
1219         memset(&arg, 0, sizeof(arg));
1220
1221         /* command line args */
1222         ARGBEGIN {
1223         case 'b':
1224                 enablescrollbars = 0;
1225                 break;
1226         case 'c':
1227                 cookiefile = EARGF(usage());
1228                 break;
1229         case 'e':
1230                 embed = strtol(EARGF(usage()), NULL, 0);
1231                 break;
1232         case 'i':
1233                 loadimages = 0;
1234                 break;
1235         case 'k':
1236                 kioskmode = 1;
1237                 break;
1238         case 'n':
1239                 enableinspector = 0;
1240                 break;
1241         case 'p':
1242                 enableplugins = 0;
1243                 break;
1244         case 'r':
1245                 scriptfile = EARGF(usage());
1246                 break;
1247         case 's':
1248                 enablescripts = 0;
1249                 break;
1250         case 't':
1251                 stylefile = EARGF(usage());
1252                 break;
1253         case 'u':
1254                 useragent = EARGF(usage());
1255                 break;
1256         case 'v':
1257                 die("surf-"VERSION", ©2009-2012 surf engineers, "
1258                                 "see LICENSE for details\n");
1259         case 'x':
1260                 showxid = TRUE;
1261                 break;
1262         default:
1263                 usage();
1264         } ARGEND;
1265         if(argc > 0)
1266                 arg.v = argv[0];
1267
1268         setup();
1269         newclient();
1270         if(arg.v)
1271                 loaduri(clients, &arg);
1272
1273         gtk_main();
1274         cleanup();
1275
1276         return EXIT_SUCCESS;
1277 }
1278