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