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