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