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