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