Scrolling is now handled through WebKit
[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/gtkx.h>
9 #include <gtk/gtk.h>
10 #include <gdk/gdkx.h>
11 #include <gdk/gdk.h>
12 #include <gdk/gdkkeysyms.h>
13 #include <string.h>
14 #include <sys/types.h>
15 #include <sys/wait.h>
16 #include <unistd.h>
17 #include <limits.h>
18 #include <stdlib.h>
19 #include <stdio.h>
20 #include <webkit2/webkit2.h>
21 #include <glib/gstdio.h>
22 #include <JavaScriptCore/JavaScript.h>
23 #include <sys/file.h>
24 #include <libgen.h>
25 #include <stdarg.h>
26 #include <regex.h>
27 #include <pwd.h>
28 #include <string.h>
29
30 #include "arg.h"
31
32 char *argv0;
33
34 #define LENGTH(x)               (sizeof(x) / sizeof(x[0]))
35 #define CLEANMASK(mask)         (mask & (MODKEY|GDK_SHIFT_MASK))
36
37 enum { AtomFind, AtomGo, AtomUri, AtomLast };
38 enum {
39         ClkDoc   = WEBKIT_HIT_TEST_RESULT_CONTEXT_DOCUMENT,
40         ClkLink  = WEBKIT_HIT_TEST_RESULT_CONTEXT_LINK,
41         ClkImg   = WEBKIT_HIT_TEST_RESULT_CONTEXT_IMAGE,
42         ClkMedia = WEBKIT_HIT_TEST_RESULT_CONTEXT_MEDIA,
43         ClkSel   = WEBKIT_HIT_TEST_RESULT_CONTEXT_SELECTION,
44         ClkEdit  = WEBKIT_HIT_TEST_RESULT_CONTEXT_EDITABLE,
45         ClkAny   = ClkDoc | ClkLink | ClkImg | ClkMedia | ClkSel | ClkEdit,
46 };
47
48 typedef union Arg Arg;
49 union Arg {
50         gboolean b;
51         gint i;
52         const void *v;
53 };
54
55 typedef struct Client {
56         GtkWidget *win;
57         Window xid;
58         WebKitWebView *view;
59         WebKitWebInspector *inspector;
60         char *title, *linkhover;
61         const char *needle;
62         gint progress;
63         struct Client *next;
64         gboolean zoomed, fullscreen, isinspecting, sslfailed;
65 } Client;
66
67 typedef struct {
68         guint mod;
69         guint keyval;
70         void (*func)(Client *c, const Arg *arg);
71         const Arg arg;
72 } Key;
73
74 typedef struct {
75         unsigned int click;
76         unsigned int mask;
77         guint button;
78         void (*func)(Client *c, const Arg *arg);
79         const Arg arg;
80 } Button;
81
82 typedef struct {
83         char *regex;
84         char *style;
85         regex_t re;
86 } SiteStyle;
87
88 static Display *dpy;
89 static Atom atoms[AtomLast];
90 static Client *clients = NULL;
91 static Window embed = 0;
92 static gboolean showxid = FALSE;
93 static char winid[64];
94 static char togglestat[9];
95 static char pagestat[3];
96 static GTlsDatabase *tlsdb;
97 static int cookiepolicy;
98 static char *stylefile = NULL;
99
100 static void addaccelgroup(Client *c);
101 static void beforerequest(WebKitWebView *w, WebKitWebFrame *f,
102                           WebKitWebResource *r, WebKitNetworkRequest *req,
103                           WebKitNetworkResponse *resp, Client *c);
104 static char *buildfile(const char *path);
105 static char *buildpath(const char *path);
106 static gboolean buttonrelease(WebKitWebView *web, GdkEventButton *e, Client *c);
107 static void cleanup(void);
108 static void clipboard(Client *c, const Arg *arg);
109
110 static WebKitCookieAcceptPolicy cookiepolicy_get(void);
111 static char cookiepolicy_set(const WebKitCookieAcceptPolicy p);
112
113 static char *copystr(char **str, const char *src);
114 static WebKitWebView *createwindow(WebKitWebView *v, WebKitWebFrame *f,
115                                    Client *c);
116 static gboolean decidedownload(WebKitWebView *v, WebKitWebFrame *f,
117                                WebKitNetworkRequest *r, gchar *m,
118                                WebKitWebPolicyDecision *p, Client *c);
119 static gboolean decidewindow(WebKitWebView *v, WebKitWebFrame *f,
120                              WebKitNetworkRequest *r, WebKitWebNavigationAction
121                              *n, WebKitWebPolicyDecision *p, Client *c);
122 static gboolean deletion_interface(WebKitWebView *view,
123                                    WebKitDOMHTMLElement *arg1, Client *c);
124 static void destroyclient(Client *c);
125 static void destroywin(GtkWidget* w, Client *c);
126 static void die(const char *errstr, ...);
127 static void eval(Client *c, const Arg *arg);
128 static void find(Client *c, const Arg *arg);
129 static void fullscreen(Client *c, const Arg *arg);
130 static void geopolicyrequested(WebKitWebView *v, WebKitWebFrame *f,
131                                WebKitGeolocationPolicyDecision *d, Client *c);
132 static const char *getatom(Client *c, int a);
133 static void gettogglestat(Client *c);
134 static void getpagestat(Client *c);
135 static char *geturi(Client *c);
136 static const gchar *getstyle(const char *uri);
137 static void setstyle(Client *c, const char *style);
138
139 static void handleplumb(Client *c, WebKitWebView *w, const gchar *uri);
140
141 static gboolean initdownload(WebKitWebView *v, WebKitDownload *o, Client *c);
142
143 static void inspector(Client *c, const Arg *arg);
144 static WebKitWebView *inspector_new(WebKitWebInspector *i, WebKitWebView *v,
145                                     Client *c);
146 static gboolean inspector_show(WebKitWebInspector *i, Client *c);
147 static gboolean inspector_close(WebKitWebInspector *i, Client *c);
148 static void inspector_finished(WebKitWebInspector *i, Client *c);
149
150 static gboolean keypress(GtkAccelGroup *group, GObject *obj, guint key,
151                          GdkModifierType mods, Client *c);
152 static void linkhover(WebKitWebView *v, const char* t, const char* l,
153                       Client *c);
154 static void loadstatuschange(WebKitWebView *view, GParamSpec *pspec,
155                              Client *c);
156 static void loaduri(Client *c, const Arg *arg);
157 static void navigate(Client *c, const Arg *arg);
158 static Client *newclient(void);
159 static void newwindow(Client *c, const Arg *arg, gboolean noembed);
160 static void pasteuri(GtkClipboard *clipboard, const char *text, gpointer d);
161 static gboolean contextmenu(WebKitWebView *view, GtkWidget *menu,
162                             WebKitHitTestResult *target, gboolean keyboard,
163                             Client *c);
164 static void menuactivate(GtkMenuItem *item, Client *c);
165 static void print(Client *c, const Arg *arg);
166 static GdkFilterReturn processx(GdkXEvent *xevent, GdkEvent *event,
167                                 gpointer d);
168 static void progresschange(WebKitWebView *view, GParamSpec *pspec, Client *c);
169 static void linkopen(Client *c, const Arg *arg);
170 static void linkopenembed(Client *c, const Arg *arg);
171 static void reload(Client *c, const Arg *arg);
172 static void scroll_h(Client *c, const Arg *arg);
173 static void scroll_v(Client *c, const Arg *arg);
174 static void scroll(GtkAdjustment *a, const Arg *arg);
175 static void setatom(Client *c, int a, const char *v);
176 static void setup(void);
177 static void sigchld(int unused);
178 static void spawn(Client *c, const Arg *arg);
179 static void stop(Client *c, const Arg *arg);
180 static void titlechange(WebKitWebView *view, GParamSpec *pspec, Client *c);
181 static void titlechangeleave(void *a, void *b, Client *c);
182 static void toggle(Client *c, const Arg *arg);
183 static void togglecookiepolicy(Client *c, const Arg *arg);
184 static void togglegeolocation(Client *c, const Arg *arg);
185 static void togglescrollbars(Client *c, const Arg *arg);
186 static void togglestyle(Client *c, const Arg *arg);
187 static void updatetitle(Client *c);
188 static void updatewinid(Client *c);
189 static void usage(void);
190 static void windowobjectcleared(GtkWidget *w, WebKitWebFrame *frame,
191                                 JSContextRef js, JSObjectRef win, Client *c);
192 static void zoom(Client *c, const Arg *arg);
193
194 /* configuration, allows nested code to access above variables */
195 #include "config.h"
196
197 void
198 addaccelgroup(Client *c)
199 {
200         int i;
201         GtkAccelGroup *group = gtk_accel_group_new();
202         GClosure *closure;
203
204         for (i = 0; i < LENGTH(keys); i++) {
205                 closure = g_cclosure_new(G_CALLBACK(keypress), c, NULL);
206                 gtk_accel_group_connect(group, keys[i].keyval, keys[i].mod, 0,
207                                         closure);
208         }
209         gtk_window_add_accel_group(GTK_WINDOW(c->win), group);
210 }
211
212 void
213 beforerequest(WebKitWebView *w, WebKitWebFrame *f, WebKitWebResource *r,
214               WebKitNetworkRequest *req, WebKitNetworkResponse *resp,
215               Client *c)
216 {
217         const gchar *uri = webkit_network_request_get_uri(req);
218         int i, isascii = 1;
219
220         if (g_str_has_suffix(uri, "/favicon.ico"))
221                 webkit_network_request_set_uri(req, "about:blank");
222
223         if (!g_str_has_prefix(uri, "http://")
224             && !g_str_has_prefix(uri, "https://")
225             && !g_str_has_prefix(uri, "about:")
226             && !g_str_has_prefix(uri, "file://")
227             && !g_str_has_prefix(uri, "data:")
228             && !g_str_has_prefix(uri, "blob:")
229             && strlen(uri) > 0) {
230                 for (i = 0; i < strlen(uri); i++) {
231                         if (!g_ascii_isprint(uri[i])) {
232                                 isascii = 0;
233                                 break;
234                         }
235                 }
236                 if (isascii)
237                         handleplumb(c, w, uri);
238         }
239 }
240
241 char *
242 buildfile(const char *path)
243 {
244         char *dname, *bname, *bpath, *fpath;
245         FILE *f;
246
247         dname = g_path_get_dirname(path);
248         bname = g_path_get_basename(path);
249
250         bpath = buildpath(dname);
251         g_free(dname);
252
253         fpath = g_build_filename(bpath, bname, NULL);
254         g_free(bpath);
255         g_free(bname);
256
257         if (!(f = fopen(fpath, "a")))
258                 die("Could not open file: %s\n", fpath);
259
260         g_chmod(fpath, 0600); /* always */
261         fclose(f);
262
263         return fpath;
264 }
265
266 char *
267 buildpath(const char *path)
268 {
269         struct passwd *pw;
270         char *apath, *name, *p, *fpath;
271
272         if (path[0] == '~') {
273                 if (path[1] == '/' || path[1] == '\0') {
274                         p = (char *)&path[1];
275                         pw = getpwuid(getuid());
276                 } else {
277                         if ((p = strchr(path, '/')))
278                                 name = g_strndup(&path[1], --p - path);
279                         else
280                                 name = g_strdup(&path[1]);
281
282                         if (!(pw = getpwnam(name))) {
283                                 die("Can't get user %s home directory: %s.\n",
284                                     name, path);
285                         }
286                         g_free(name);
287                 }
288                 apath = g_build_filename(pw->pw_dir, p, NULL);
289         } else {
290                 apath = g_strdup(path);
291         }
292
293         /* creating directory */
294         if (g_mkdir_with_parents(apath, 0700) < 0)
295                 die("Could not access directory: %s\n", apath);
296
297         fpath = realpath(apath, NULL);
298         g_free(apath);
299
300         return fpath;
301 }
302
303 gboolean
304 buttonrelease(WebKitWebView *web, GdkEventButton *e, Client *c)
305 {
306         WebKitHitTestResultContext context;
307         WebKitHitTestResult *result;
308         Arg arg;
309         unsigned int i;
310
311         result = webkit_web_view_get_hit_test_result(web, e);
312         g_object_get(result, "context", &context, NULL);
313         g_object_get(result, "link-uri", &arg.v, NULL);
314         for (i = 0; i < LENGTH(buttons); i++) {
315                 if (context & buttons[i].click
316                     && e->button == buttons[i].button
317                     && CLEANMASK(e->state) == CLEANMASK(buttons[i].mask)
318                     && buttons[i].func) {
319                         buttons[i].func(c, buttons[i].click == ClkLink
320                             && buttons[i].arg.i == 0 ? &arg : &buttons[i].arg);
321                         return true;
322                 }
323         }
324         return false;
325 }
326
327 void
328 cleanup(void)
329 {
330         while (clients)
331                 destroyclient(clients);
332         g_free(cookiefile);
333         g_free(scriptfile);
334         g_free(stylefile);
335 }
336
337 WebKitCookieAcceptPolicy
338 cookiepolicy_get(void)
339 {
340         switch (cookiepolicies[cookiepolicy]) {
341         case 'a':
342                 return WEBKIT_COOKIE_POLICY_ACCEPT_NEVER;
343         case '@':
344                 return WEBKIT_COOKIE_POLICY_ACCEPT_NO_THIRD_PARTY;
345         case 'A':
346         default:
347                 break;
348         }
349
350         return WEBKIT_COOKIE_POLICY_ACCEPT_ALWAYS;
351 }
352
353 char
354 cookiepolicy_set(const WebKitCookieAcceptPolicy ep)
355 {
356         switch (ep) {
357         case WEBKIT_COOKIE_POLICY_ACCEPT_NEVER:
358                 return 'a';
359         case WEBKIT_COOKIE_POLICY_ACCEPT_NO_THIRD_PARTY:
360                 return '@';
361         case WEBKIT_COOKIE_POLICY_ACCEPT_ALWAYS:
362         default:
363                 break;
364         }
365
366         return 'A';
367 }
368
369 void
370 evalscript(JSContextRef js, char *script, char* scriptname)
371 {
372         JSStringRef jsscript, jsscriptname;
373         JSValueRef exception = NULL;
374
375         jsscript = JSStringCreateWithUTF8CString(script);
376         jsscriptname = JSStringCreateWithUTF8CString(scriptname);
377         JSEvaluateScript(js, jsscript, JSContextGetGlobalObject(js),
378                          jsscriptname, 0, &exception);
379         JSStringRelease(jsscript);
380         JSStringRelease(jsscriptname);
381 }
382
383 void
384 runscript(WebKitWebFrame *frame)
385 {
386         char *script;
387         GError *error;
388
389         if (g_file_get_contents(scriptfile, &script, NULL, &error)) {
390                 evalscript(webkit_web_frame_get_global_context(frame), script,
391                            scriptfile);
392         }
393 }
394
395 void
396 clipboard(Client *c, const Arg *arg)
397 {
398         gboolean paste = *(gboolean *)arg;
399
400         if (paste) {
401                 gtk_clipboard_request_text(gtk_clipboard_get(
402                                            GDK_SELECTION_PRIMARY),
403                                            pasteuri, c);
404         } else {
405                 gtk_clipboard_set_text(gtk_clipboard_get(
406                                        GDK_SELECTION_PRIMARY), c->linkhover
407                                        ? c->linkhover : geturi(c), -1);
408         }
409 }
410
411 char *
412 copystr(char **str, const char *src)
413 {
414         char *tmp;
415         tmp = g_strdup(src);
416
417         if (str && *str) {
418                 g_free(*str);
419                 *str = tmp;
420         }
421         return tmp;
422 }
423
424 WebKitWebView *
425 createwindow(WebKitWebView  *v, WebKitWebFrame *f, Client *c)
426 {
427         Client *n = newclient();
428         return n->view;
429 }
430
431 gboolean
432 decidedownload(WebKitWebView *v, WebKitWebFrame *f, WebKitNetworkRequest *r,
433                gchar *m,  WebKitWebPolicyDecision *p, Client *c)
434 {
435         if (!webkit_web_view_can_show_mime_type(v, m)) {
436                 webkit_web_policy_decision_download(p);
437                 return TRUE;
438         }
439         return FALSE;
440 }
441
442 gboolean
443 decidewindow(WebKitWebView *view, WebKitWebFrame *f, WebKitNetworkRequest *r,
444              WebKitWebNavigationAction *n, WebKitWebPolicyDecision *p,
445              Client *c)
446 {
447         Arg arg;
448
449         if (webkit_web_navigation_action_get_reason(n)
450             == WEBKIT_WEB_NAVIGATION_REASON_LINK_CLICKED) {
451                 webkit_web_policy_decision_ignore(p);
452                 arg.v = (void *)webkit_network_request_get_uri(r);
453                 newwindow(NULL, &arg, 0);
454                 return TRUE;
455         }
456         return FALSE;
457 }
458
459 gboolean
460 deletion_interface(WebKitWebView *view, WebKitDOMHTMLElement *arg1, Client *c)
461 {
462         return FALSE;
463 }
464
465 void
466 destroyclient(Client *c)
467 {
468         Client *p;
469
470         webkit_web_view_stop_loading(c->view);
471         gtk_widget_destroy(GTK_WIDGET(c->view));
472         gtk_widget_destroy(c->scroll);
473         gtk_widget_destroy(c->vbox);
474         gtk_widget_destroy(c->win);
475
476         for (p = clients; p && p->next != c; p = p->next)
477                 ;
478         if (p)
479                 p->next = c->next;
480         else
481                 clients = c->next;
482         free(c);
483         if (clients == NULL)
484                 gtk_main_quit();
485 }
486
487 void
488 destroywin(GtkWidget* w, Client *c)
489 {
490         destroyclient(c);
491 }
492
493 void
494 die(const char *errstr, ...)
495 {
496         va_list ap;
497
498         va_start(ap, errstr);
499         vfprintf(stderr, errstr, ap);
500         va_end(ap);
501         exit(EXIT_FAILURE);
502 }
503
504 void
505 find(Client *c, const Arg *arg)
506 {
507         const char *s;
508
509         s = getatom(c, AtomFind);
510         gboolean forward = *(gboolean *)arg;
511         webkit_web_view_search_text(c->view, s, FALSE, forward, TRUE);
512 }
513
514 void
515 fullscreen(Client *c, const Arg *arg)
516 {
517         if (c->fullscreen)
518                 gtk_window_unfullscreen(GTK_WINDOW(c->win));
519         else
520                 gtk_window_fullscreen(GTK_WINDOW(c->win));
521         c->fullscreen = !c->fullscreen;
522 }
523
524 void
525 geopolicyrequested(WebKitWebView *v, WebKitWebFrame *f,
526                    WebKitGeolocationPolicyDecision *d, Client *c)
527 {
528         if (allowgeolocation)
529                 webkit_geolocation_policy_allow(d);
530         else
531                 webkit_geolocation_policy_deny(d);
532 }
533
534 const char *
535 getatom(Client *c, int a)
536 {
537         static char buf[BUFSIZ];
538         Atom adummy;
539         int idummy;
540         unsigned long ldummy;
541         unsigned char *p = NULL;
542
543         XGetWindowProperty(dpy, c->xid,
544                            atoms[a], 0L, BUFSIZ, False, XA_STRING,
545                            &adummy, &idummy, &ldummy, &ldummy, &p);
546         if (p)
547                 strncpy(buf, (char *)p, LENGTH(buf)-1);
548         else
549                 buf[0] = '\0';
550         XFree(p);
551
552         return buf;
553 }
554
555 char *
556 geturi(Client *c)
557 {
558         char *uri;
559
560         if (!(uri = (char *)webkit_web_view_get_uri(c->view)))
561                 uri = "about:blank";
562         return uri;
563 }
564
565 const gchar *
566 getstyle(const char *uri)
567 {
568         int i;
569
570         if (stylefile != NULL)
571                 return stylefile;
572
573         for (i = 0; i < LENGTH(styles); i++) {
574                 if (styles[i].regex && !regexec(&(styles[i].re), uri, 0,
575                     NULL, 0))
576                         return styles[i].style;
577         }
578
579         return "";
580 }
581
582 void
583 setstyle(Client *c, const char *style)
584 {
585         WebKitWebSettings *settings = webkit_web_view_get_settings(c->view);
586
587         g_object_set(G_OBJECT(settings), "user-stylesheet-uri", style, NULL);
588 }
589
590 void
591 handleplumb(Client *c, WebKitWebView *w, const gchar *uri)
592 {
593         Arg arg;
594
595         webkit_web_view_stop_loading(w);
596         arg = (Arg)PLUMB((char *)uri);
597         spawn(c, &arg);
598 }
599
600 gboolean
601 initdownload(WebKitWebView *view, WebKitDownload *o, Client *c)
602 {
603         Arg arg;
604
605         updatewinid(c);
606         arg = (Arg)DOWNLOAD((char *)webkit_download_get_uri(o), geturi(c));
607         spawn(c, &arg);
608         return FALSE;
609 }
610
611 void
612 inspector(Client *c, const Arg *arg)
613 {
614         if (enableinspector) {
615                 if (c->isinspecting)
616                         webkit_web_inspector_close(c->inspector);
617                 else
618                         webkit_web_inspector_show(c->inspector);
619         }
620 }
621
622 WebKitWebView *
623 inspector_new(WebKitWebInspector *i, WebKitWebView *v, Client *c)
624 {
625         return WEBKIT_WEB_VIEW(webkit_web_view_new());
626 }
627
628 gboolean
629 inspector_show(WebKitWebInspector *i, Client *c)
630 {
631         WebKitWebView *w;
632
633         if (c->isinspecting)
634                 return false;
635
636         w = webkit_web_inspector_get_web_view(i);
637         gtk_paned_pack2(GTK_PANED(c->pane), GTK_WIDGET(w), TRUE, TRUE);
638         gtk_widget_show(GTK_WIDGET(w));
639         c->isinspecting = true;
640
641         return true;
642 }
643
644 gboolean
645 inspector_close(WebKitWebInspector *i, Client *c)
646 {
647         GtkWidget *w;
648
649         if (!c->isinspecting)
650                 return false;
651
652         w = GTK_WIDGET(webkit_web_inspector_get_web_view(i));
653         gtk_widget_hide(w);
654         gtk_widget_destroy(w);
655         c->isinspecting = false;
656
657         return true;
658 }
659
660 void
661 inspector_finished(WebKitWebInspector *i, Client *c)
662 {
663         g_free(c->inspector);
664 }
665
666 gboolean
667 keypress(GtkAccelGroup *group, GObject *obj, guint key, GdkModifierType mods,
668          Client *c)
669 {
670         guint i;
671         gboolean processed = FALSE;
672
673         mods = CLEANMASK(mods);
674         key = gdk_keyval_to_lower(key);
675         updatewinid(c);
676         for (i = 0; i < LENGTH(keys); i++) {
677                 if (key == keys[i].keyval
678                     && mods == keys[i].mod
679                     && keys[i].func) {
680                         keys[i].func(c, &(keys[i].arg));
681                         processed = TRUE;
682                 }
683         }
684
685         return processed;
686 }
687
688 void
689 linkhover(WebKitWebView *v, const char* t, const char* l, Client *c)
690 {
691         if (l) {
692                 c->linkhover = copystr(&c->linkhover, l);
693         } else if (c->linkhover) {
694                 free(c->linkhover);
695                 c->linkhover = NULL;
696         }
697         updatetitle(c);
698 }
699
700 void
701 loadstatuschange(WebKitWebView *view, GParamSpec *pspec, Client *c)
702 {
703         WebKitWebFrame *frame;
704         WebKitWebDataSource *src;
705         WebKitNetworkRequest *request;
706         SoupMessage *msg;
707         char *uri;
708
709         switch (webkit_web_view_get_load_status (c->view)) {
710         case WEBKIT_LOAD_COMMITTED:
711                 uri = geturi(c);
712                 if (strstr(uri, "https://") == uri) {
713                         frame = webkit_web_view_get_main_frame(c->view);
714                         src = webkit_web_frame_get_data_source(frame);
715                         request = webkit_web_data_source_get_request(src);
716                         msg = webkit_network_request_get_message(request);
717                         c->sslfailed = !(soup_message_get_flags(msg)
718                                        & SOUP_MESSAGE_CERTIFICATE_TRUSTED);
719                 }
720                 setatom(c, AtomUri, uri);
721
722                 if (enablestyle)
723                         setstyle(c, getstyle(uri));
724                 break;
725         case WEBKIT_LOAD_FINISHED:
726                 c->progress = 100;
727                 updatetitle(c);
728                 break;
729         default:
730                 break;
731         }
732 }
733
734 void
735 loaduri(Client *c, const Arg *arg)
736 {
737         char *u = NULL, *rp;
738         const char *uri = (char *)arg->v;
739         Arg a = { .b = FALSE };
740         struct stat st;
741
742         if (strcmp(uri, "") == 0)
743                 return;
744
745         /* In case it's a file path. */
746         if (stat(uri, &st) == 0) {
747                 rp = realpath(uri, NULL);
748                 u = g_strdup_printf("file://%s", rp);
749                 free(rp);
750         } else {
751                 u = g_strrstr(uri, "://") ? g_strdup(uri)
752                     : g_strdup_printf("http://%s", uri);
753         }
754
755         setatom(c, AtomUri, uri);
756
757         /* prevents endless loop */
758         if (strcmp(u, geturi(c)) == 0) {
759                 reload(c, &a);
760         } else {
761                 webkit_web_view_load_uri(c->view, u);
762                 c->progress = 0;
763                 c->title = copystr(&c->title, u);
764                 updatetitle(c);
765         }
766         g_free(u);
767 }
768
769 void
770 navigate(Client *c, const Arg *arg)
771 {
772         int steps = *(int *)arg;
773         webkit_web_view_go_back_or_forward(c->view, steps);
774 }
775
776 Client *
777 newclient(void)
778 {
779         Client *c;
780         WebKitWebSettings *settings;
781         GdkGeometry hints = { 1, 1 };
782         GdkScreen *screen;
783         GdkWindow *gwin;
784         gdouble dpi;
785         char *ua;
786
787         if (!(c = calloc(1, sizeof(Client))))
788                 die("Cannot malloc!\n");
789
790         c->title = NULL;
791         c->progress = 100;
792
793         /* Window */
794         if (embed) {
795                 c->win = gtk_plug_new(embed);
796         } else {
797                 c->win = gtk_window_new(GTK_WINDOW_TOPLEVEL);
798
799                 /* TA:  20091214:  Despite what the GNOME docs say, the ICCCM
800                  * is always correct, so we should still call this function.
801                  * But when doing so, we *must* differentiate between a
802                  * WM_CLASS and a resource on the window.  By convention, the
803                  * window class (WM_CLASS) is capped, while the resource is in
804                  * lowercase.   Both these values come as a pair.
805                  */
806                 gtk_window_set_wmclass(GTK_WINDOW(c->win), "surf", "Surf");
807
808                 /* TA:  20091214:  And set the role here as well -- so that
809                  * sessions can pick this up.
810                  */
811                 gtk_window_set_role(GTK_WINDOW(c->win), "Surf");
812         }
813         gtk_window_set_default_size(GTK_WINDOW(c->win), 800, 600);
814         g_signal_connect(G_OBJECT(c->win),
815                          "destroy",
816                          G_CALLBACK(destroywin), c);
817         g_signal_connect(G_OBJECT(c->win),
818                          "leave_notify_event",
819                          G_CALLBACK(titlechangeleave), c);
820
821         if (!kioskmode)
822                 addaccelgroup(c);
823
824         /* Webview */
825         c->view = WEBKIT_WEB_VIEW(webkit_web_view_new());
826
827         g_signal_connect(G_OBJECT(c->view),
828                          "notify::title",
829                          G_CALLBACK(titlechange), c);
830         g_signal_connect(G_OBJECT(c->view),
831                          "hovering-over-link",
832                          G_CALLBACK(linkhover), c);
833         g_signal_connect(G_OBJECT(c->view),
834                          "geolocation-policy-decision-requested",
835                          G_CALLBACK(geopolicyrequested), c);
836         g_signal_connect(G_OBJECT(c->view),
837                          "create-web-view",
838                          G_CALLBACK(createwindow), c);
839         g_signal_connect(G_OBJECT(c->view),
840                          "new-window-policy-decision-requested",
841                          G_CALLBACK(decidewindow), c);
842         g_signal_connect(G_OBJECT(c->view),
843                          "mime-type-policy-decision-requested",
844                          G_CALLBACK(decidedownload), c);
845         g_signal_connect(G_OBJECT(c->view),
846                          "window-object-cleared",
847                          G_CALLBACK(windowobjectcleared), c);
848         g_signal_connect(G_OBJECT(c->view),
849                          "notify::load-status",
850                          G_CALLBACK(loadstatuschange), c);
851         g_signal_connect(G_OBJECT(c->view),
852                          "notify::progress",
853                          G_CALLBACK(progresschange), c);
854         g_signal_connect(G_OBJECT(c->view),
855                          "download-requested",
856                          G_CALLBACK(initdownload), c);
857         g_signal_connect(G_OBJECT(c->view),
858                          "button-release-event",
859                          G_CALLBACK(buttonrelease), c);
860         g_signal_connect(G_OBJECT(c->view),
861                          "context-menu",
862                          G_CALLBACK(contextmenu), c);
863         g_signal_connect(G_OBJECT(c->view),
864                          "resource-request-starting",
865                          G_CALLBACK(beforerequest), c);
866         g_signal_connect(G_OBJECT(c->view),
867                          "should-show-delete-interface-for-element",
868                          G_CALLBACK(deletion_interface), c);
869
870         /* Arranging */
871         gtk_container_add(GTK_CONTAINER(c->win), GTK_WIDGET(c->view));
872
873         /* Setup */
874         gtk_widget_grab_focus(GTK_WIDGET(c->view));
875         gtk_widget_show(GTK_WIDGET(c->view));
876         gtk_widget_show(c->win);
877         gwin = gtk_widget_get_window(GTK_WIDGET(c->win));
878         c->xid = gdk_x11_window_get_xid(gwin);
879         gtk_window_set_geometry_hints(GTK_WINDOW(c->win), NULL, &hints,
880                                       GDK_HINT_MIN_SIZE);
881         gdk_window_set_events(gwin, GDK_ALL_EVENTS_MASK);
882         gdk_window_add_filter(gwin, processx, c);
883         webkit_web_view_set_full_content_zoom(c->view, TRUE);
884
885         runscript(frame);
886
887         settings = webkit_web_view_get_settings(c->view);
888         if (!(ua = getenv("SURF_USERAGENT")))
889                 ua = useragent;
890         g_object_set(G_OBJECT(settings), "user-agent", ua, NULL);
891         g_object_set(G_OBJECT(settings),
892                      "auto-load-images", loadimages, NULL);
893         g_object_set(G_OBJECT(settings),
894                      "enable-plugins", enableplugins, NULL);
895         g_object_set(G_OBJECT(settings),
896                      "enable-scripts", enablescripts, NULL);
897         g_object_set(G_OBJECT(settings),
898                      "enable-spatial-navigation", enablespatialbrowsing, NULL);
899         g_object_set(G_OBJECT(settings),
900                      "enable-developer-extras", enableinspector, NULL);
901         g_object_set(G_OBJECT(settings),
902                      "enable-default-context-menu", kioskmode ^ 1, NULL);
903         g_object_set(G_OBJECT(settings),
904                      "default-font-size", defaultfontsize, NULL);
905         g_object_set(G_OBJECT(settings),
906                      "resizable-text-areas", 1, NULL);
907         if (enablestyle)
908                 setstyle(c, getstyle("about:blank"));
909
910         /*
911          * While stupid, CSS specifies that a pixel represents 1/96 of an inch.
912          * This ensures websites are not unusably small with a high DPI screen.
913          * It is equivalent to firefox's "layout.css.devPixelsPerPx" setting.
914          */
915         if (zoomto96dpi) {
916                 screen = gdk_window_get_screen(gwin);
917                 dpi = gdk_screen_get_resolution(screen);
918                 if (dpi != -1) {
919                         g_object_set(G_OBJECT(settings),
920                                      "enforce-96-dpi", true, NULL);
921                         webkit_web_view_set_zoom_level(c->view, dpi/96);
922                 }
923         }
924         /* This might conflict with _zoomto96dpi_. */
925         if (zoomlevel != 1.0)
926                 webkit_web_view_set_zoom_level(c->view, zoomlevel);
927
928         if (enableinspector) {
929                 c->inspector = webkit_web_view_get_inspector(c->view);
930                 g_signal_connect(G_OBJECT(c->inspector), "inspect-web-view",
931                                  G_CALLBACK(inspector_new), c);
932                 g_signal_connect(G_OBJECT(c->inspector), "show-window",
933                                  G_CALLBACK(inspector_show), c);
934                 g_signal_connect(G_OBJECT(c->inspector), "close-window",
935                                  G_CALLBACK(inspector_close), c);
936                 g_signal_connect(G_OBJECT(c->inspector), "finished",
937                                  G_CALLBACK(inspector_finished), c);
938                 c->isinspecting = false;
939         }
940
941         if (runinfullscreen)
942                 fullscreen(c, NULL);
943
944         setatom(c, AtomFind, "");
945         setatom(c, AtomUri, "about:blank");
946         if (hidebackground)
947                 webkit_web_view_set_transparent(c->view, TRUE);
948
949         c->next = clients;
950         clients = c;
951
952         if (showxid) {
953                 gdk_display_sync(gtk_widget_get_display(c->win));
954                 printf("%lu\n", c->xid);
955                 fflush(NULL);
956                 if (fclose(stdout) != 0) {
957                         die("Error closing stdout");
958                 }
959         }
960
961         return c;
962 }
963
964 void
965 newwindow(Client *c, const Arg *arg, gboolean noembed)
966 {
967         guint i = 0;
968         const char *cmd[18], *uri;
969         const Arg a = { .v = (void *)cmd };
970         char tmp[64];
971
972         cmd[i++] = argv0;
973         cmd[i++] = "-a";
974         cmd[i++] = cookiepolicies;
975         if (!enablescrollbars)
976                 cmd[i++] = "-b";
977         if (embed && !noembed) {
978                 cmd[i++] = "-e";
979                 snprintf(tmp, LENGTH(tmp), "%u", (int)embed);
980                 cmd[i++] = tmp;
981         }
982         if (!allowgeolocation)
983                 cmd[i++] = "-g";
984         if (!loadimages)
985                 cmd[i++] = "-i";
986         if (kioskmode)
987                 cmd[i++] = "-k";
988         if (!enableplugins)
989                 cmd[i++] = "-p";
990         if (!enablescripts)
991                 cmd[i++] = "-s";
992         if (showxid)
993                 cmd[i++] = "-x";
994         if (enablediskcache)
995                 cmd[i++] = "-D";
996         cmd[i++] = "-c";
997         cmd[i++] = cookiefile;
998         cmd[i++] = "--";
999         uri = arg->v ? (char *)arg->v : c->linkhover;
1000         if (uri)
1001                 cmd[i++] = uri;
1002         cmd[i++] = NULL;
1003         spawn(NULL, &a);
1004 }
1005
1006 gboolean
1007 contextmenu(WebKitWebView *view, GtkWidget *menu, WebKitHitTestResult *target,
1008             gboolean keyboard, Client *c)
1009 {
1010         GList *items = gtk_container_get_children(GTK_CONTAINER(GTK_MENU(menu)));
1011
1012         for (GList *l = items; l; l = l->next)
1013                 g_signal_connect(l->data, "activate", G_CALLBACK(menuactivate), c);
1014
1015         g_list_free(items);
1016         return FALSE;
1017 }
1018
1019 void
1020 menuactivate(GtkMenuItem *item, Client *c)
1021 {
1022         /*
1023          * context-menu-action-2000 open link
1024          * context-menu-action-1    open link in window
1025          * context-menu-action-2    download linked file
1026          * context-menu-action-3    copy link location
1027          * context-menu-action-7    copy image address
1028          * context-menu-action-13   reload
1029          * context-menu-action-10   back
1030          * context-menu-action-11   forward
1031          * context-menu-action-12   stop
1032          */
1033
1034         const gchar *name, *uri;
1035         GtkClipboard *prisel, *clpbrd;
1036
1037         name = gtk_actionable_get_action_name(GTK_ACTIONABLE(item));
1038         if (name == NULL)
1039                 return;
1040
1041         if (!g_strcmp0(name, "context-menu-action-3")) {
1042                 prisel = gtk_clipboard_get(GDK_SELECTION_PRIMARY);
1043                 gtk_clipboard_set_text(prisel, c->linkhover, -1);
1044         } else if (!g_strcmp0(name, "context-menu-action-7")) {
1045                 prisel = gtk_clipboard_get(GDK_SELECTION_PRIMARY);
1046                 clpbrd = gtk_clipboard_get(GDK_SELECTION_CLIPBOARD);
1047                 uri = gtk_clipboard_wait_for_text(clpbrd);
1048                 if (uri)
1049                         gtk_clipboard_set_text(prisel, uri, -1);
1050         }
1051 }
1052
1053 void
1054 pasteuri(GtkClipboard *clipboard, const char *text, gpointer d)
1055 {
1056         Arg arg = {.v = text };
1057         if (text != NULL)
1058                 loaduri((Client *) d, &arg);
1059 }
1060
1061 void
1062 print(Client *c, const Arg *arg)
1063 {
1064         webkit_web_frame_print(webkit_web_view_get_main_frame(c->view));
1065 }
1066
1067 GdkFilterReturn
1068 processx(GdkXEvent *e, GdkEvent *event, gpointer d)
1069 {
1070         Client *c = (Client *)d;
1071         XPropertyEvent *ev;
1072         Arg arg;
1073
1074         if (((XEvent *)e)->type == PropertyNotify) {
1075                 ev = &((XEvent *)e)->xproperty;
1076                 if (ev->state == PropertyNewValue) {
1077                         if (ev->atom == atoms[AtomFind]) {
1078                                 arg.b = TRUE;
1079                                 find(c, &arg);
1080
1081                                 return GDK_FILTER_REMOVE;
1082                         } else if (ev->atom == atoms[AtomGo]) {
1083                                 arg.v = getatom(c, AtomGo);
1084                                 loaduri(c, &arg);
1085
1086                                 return GDK_FILTER_REMOVE;
1087                         }
1088                 }
1089         }
1090         return GDK_FILTER_CONTINUE;
1091 }
1092
1093 void
1094 progresschange(WebKitWebView *view, GParamSpec *pspec, Client *c)
1095 {
1096         c->progress = webkit_web_view_get_progress(c->view) * 100;
1097         updatetitle(c);
1098 }
1099
1100 void
1101 linkopen(Client *c, const Arg *arg)
1102 {
1103         newwindow(NULL, arg, 1);
1104 }
1105
1106 void
1107 linkopenembed(Client *c, const Arg *arg)
1108 {
1109         newwindow(NULL, arg, 0);
1110 }
1111
1112 void
1113 reload(Client *c, const Arg *arg)
1114 {
1115         gboolean nocache = *(gboolean *)arg;
1116         if (nocache)
1117                 webkit_web_view_reload_bypass_cache(c->view);
1118         else
1119                 webkit_web_view_reload(c->view);
1120 }
1121
1122 void
1123 scroll_h(Client *c, const Arg *arg)
1124 {
1125         scroll(gtk_scrolled_window_get_hadjustment(
1126                GTK_SCROLLED_WINDOW(c->scroll)), arg);
1127 }
1128
1129 void
1130 scroll_v(Client *c, const Arg *arg)
1131 {
1132         scroll(gtk_scrolled_window_get_vadjustment(
1133                GTK_SCROLLED_WINDOW(c->scroll)), arg);
1134 }
1135
1136 void
1137 scroll(GtkAdjustment *a, const Arg *arg)
1138 {
1139         gdouble v;
1140
1141         v = gtk_adjustment_get_value(a);
1142         switch (arg->i) {
1143         case +10000:
1144         case -10000:
1145                 v += gtk_adjustment_get_page_increment(a) * (arg->i / 10000);
1146                 break;
1147         case +20000:
1148         case -20000:
1149         default:
1150                 v += gtk_adjustment_get_step_increment(a) * arg->i;
1151         }
1152
1153         v = MAX(v, 0.0);
1154         v = MIN(v, gtk_adjustment_get_upper(a) -
1155                 gtk_adjustment_get_page_size(a));
1156         gtk_adjustment_set_value(a, v);
1157 }
1158
1159 void
1160 setatom(Client *c, int a, const char *v)
1161 {
1162         XSync(dpy, False);
1163         XChangeProperty(dpy, c->xid,
1164                         atoms[a], XA_STRING, 8, PropModeReplace,
1165                         (unsigned char *)v, strlen(v) + 1);
1166 }
1167
1168 void
1169 setup(void)
1170 {
1171         int i;
1172         char *styledirfile, *stylepath;
1173         WebKitWebContext *context;
1174         GError *error = NULL;
1175
1176         /* clean up any zombies immediately */
1177         sigchld(0);
1178         gtk_init(NULL, NULL);
1179
1180         dpy = GDK_DISPLAY_XDISPLAY(gdk_display_get_default());
1181
1182         /* atoms */
1183         atoms[AtomFind] = XInternAtom(dpy, "_SURF_FIND", False);
1184         atoms[AtomGo] = XInternAtom(dpy, "_SURF_GO", False);
1185         atoms[AtomUri] = XInternAtom(dpy, "_SURF_URI", False);
1186
1187         /* dirs and files */
1188         cookiefile = buildfile(cookiefile);
1189         scriptfile = buildfile(scriptfile);
1190         cachefolder = buildpath(cachefolder);
1191         if (stylefile == NULL) {
1192                 styledir = buildpath(styledir);
1193                 for (i = 0; i < LENGTH(styles); i++) {
1194                         if (regcomp(&(styles[i].re), styles[i].regex,
1195                             REG_EXTENDED)) {
1196                                 fprintf(stderr,
1197                                         "Could not compile regex: %s\n",
1198                                         styles[i].regex);
1199                                 styles[i].regex = NULL;
1200                         }
1201                         styledirfile    = g_strconcat(styledir, "/",
1202                                                       styles[i].style, NULL);
1203                         stylepath       = buildfile(styledirfile);
1204                         styles[i].style = g_strconcat("file://", stylepath,
1205                                                       NULL);
1206                         g_free(styledirfile);
1207                         g_free(stylepath);
1208                 }
1209                 g_free(styledir);
1210         } else {
1211                 stylepath = buildfile(stylefile);
1212                 stylefile = g_strconcat("file://", stylepath, NULL);
1213                 g_free(stylepath);
1214         }
1215
1216         /* cookie policy */
1217         webkit_cookie_manager_set_persistent_storage(
1218             webkit_web_context_get_cookie_manager(context), cookiefile,
1219             WEBKIT_COOKIE_PERSISTENT_STORAGE_TEXT);
1220         webkit_cookie_manager_set_accept_policy(
1221             webkit_web_context_get_cookie_manager(context),
1222             cookiepolicy_get());
1223
1224         /* disk cache */
1225         webkit_web_context_set_cache_model(context, enablecache ?
1226             WEBKIT_CACHE_MODEL_WEB_BROWSER :
1227             WEBKIT_CACHE_MODEL_DOCUMENT_VIEWER);
1228
1229         /* ssl */
1230         webkit_web_context_set_tls_errors_policy(context, strictssl ?
1231             WEBKIT_TLS_ERRORS_POLICY_FAIL :
1232             WEBKIT_TLS_ERRORS_POLICY_IGNORE);
1233 }
1234
1235 void
1236 sigchld(int unused)
1237 {
1238         if (signal(SIGCHLD, sigchld) == SIG_ERR)
1239                 die("Can't install SIGCHLD handler");
1240         while (0 < waitpid(-1, NULL, WNOHANG));
1241 }
1242
1243 void
1244 spawn(Client *c, const Arg *arg)
1245 {
1246         if (fork() == 0) {
1247                 if (dpy)
1248                         close(ConnectionNumber(dpy));
1249                 setsid();
1250                 execvp(((char **)arg->v)[0], (char **)arg->v);
1251                 fprintf(stderr, "surf: execvp %s", ((char **)arg->v)[0]);
1252                 perror(" failed");
1253                 exit(0);
1254         }
1255 }
1256
1257 void
1258 eval(Client *c, const Arg *arg)
1259 {
1260         WebKitWebFrame *frame = webkit_web_view_get_main_frame(c->view);
1261         evalscript(webkit_web_frame_get_global_context(frame),
1262                    ((char **)arg->v)[0], "");
1263 }
1264
1265 void
1266 stop(Client *c, const Arg *arg)
1267 {
1268         webkit_web_view_stop_loading(c->view);
1269 }
1270
1271 void
1272 titlechange(WebKitWebView *view, GParamSpec *pspec, Client *c)
1273 {
1274         const gchar *t = webkit_web_view_get_title(view);
1275         if (t) {
1276                 c->title = copystr(&c->title, t);
1277                 updatetitle(c);
1278         }
1279 }
1280
1281 void
1282 titlechangeleave(void *a, void *b, Client *c)
1283 {
1284         c->linkhover = NULL;
1285         updatetitle(c);
1286 }
1287
1288 void
1289 toggle(Client *c, const Arg *arg)
1290 {
1291         WebKitWebSettings *settings;
1292         char *name = (char *)arg->v;
1293         gboolean value;
1294         Arg a = { .b = FALSE };
1295
1296         settings = webkit_web_view_get_settings(c->view);
1297         g_object_get(G_OBJECT(settings), name, &value, NULL);
1298         g_object_set(G_OBJECT(settings), name, !value, NULL);
1299
1300         reload(c, &a);
1301 }
1302
1303 void
1304 togglecookiepolicy(Client *c, const Arg *arg)
1305 {
1306         ++cookiepolicy;
1307         cookiepolicy %= strlen(cookiepolicies);
1308
1309         webkit_cookie_manager_set_accept_policy(
1310             webkit_web_context_get_cookie_manager(
1311             webkit_web_view_get_context(c->view)),
1312             cookiepolicy_get());
1313
1314         updatetitle(c);
1315         /* Do not reload. */
1316 }
1317
1318 void
1319 togglegeolocation(Client *c, const Arg *arg)
1320 {
1321         Arg a = { .b = FALSE };
1322
1323         allowgeolocation ^= 1;
1324         reload(c, &a);
1325 }
1326
1327 void
1328 twitch(Client *c, const Arg *arg)
1329 {
1330         GtkAdjustment *a;
1331         gdouble v;
1332
1333         a = gtk_scrolled_window_get_vadjustment(GTK_SCROLLED_WINDOW(
1334                                                 c->scroll));
1335
1336         v = gtk_adjustment_get_value(a);
1337
1338         v += arg->i;
1339
1340         v = MAX(v, 0.0);
1341         v = MIN(v, gtk_adjustment_get_upper(a) -
1342                 gtk_adjustment_get_page_size(a));
1343         gtk_adjustment_set_value(a, v);
1344 }
1345
1346 void
1347 togglescrollbars(Client *c, const Arg *arg)
1348 {
1349         GtkPolicyType vspolicy;
1350         Arg a;
1351
1352         gtk_scrolled_window_get_policy(GTK_SCROLLED_WINDOW(c->scroll), NULL,
1353                                        &vspolicy);
1354
1355         if (vspolicy == GTK_POLICY_AUTOMATIC) {
1356                 gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(c->scroll),
1357                                                GTK_POLICY_NEVER,
1358                                                GTK_POLICY_NEVER);
1359         } else {
1360                 gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(c->scroll),
1361                                                GTK_POLICY_AUTOMATIC,
1362                                                GTK_POLICY_AUTOMATIC);
1363                 a.i = +1;
1364                 twitch(c, &a);
1365                 a.i = -1;
1366                 twitch(c, &a);
1367         }
1368 }
1369
1370 void
1371 togglestyle(Client *c, const Arg *arg)
1372 {
1373         enablestyle = !enablestyle;
1374         setstyle(c, enablestyle ? getstyle(geturi(c)) : "");
1375
1376         updatetitle(c);
1377 }
1378
1379 void
1380 gettogglestat(Client *c)
1381 {
1382         gboolean value;
1383         int p = 0;
1384         WebKitWebSettings *settings = webkit_web_view_get_settings(c->view);
1385
1386         togglestat[p++] = cookiepolicy_set(cookiepolicy_get());
1387
1388         g_object_get(G_OBJECT(settings), "enable-caret-browsing", &value,
1389                      NULL);
1390         togglestat[p++] = value? 'C': 'c';
1391
1392         togglestat[p++] = allowgeolocation? 'G': 'g';
1393
1394         togglestat[p++] = enablediskcache? 'D': 'd';
1395
1396         g_object_get(G_OBJECT(settings), "auto-load-images", &value, NULL);
1397         togglestat[p++] = value? 'I': 'i';
1398
1399         g_object_get(G_OBJECT(settings), "enable-scripts", &value, NULL);
1400         togglestat[p++] = value? 'S': 's';
1401
1402         g_object_get(G_OBJECT(settings), "enable-plugins", &value, NULL);
1403         togglestat[p++] = value? 'V': 'v';
1404
1405         togglestat[p++] = enablestyle ? 'M': 'm';
1406
1407         togglestat[p] = '\0';
1408 }
1409
1410 void
1411 getpagestat(Client *c)
1412 {
1413         const char *uri = geturi(c);
1414
1415         if (strstr(uri, "https://") == uri)
1416                 pagestat[0] = c->sslfailed ? 'U' : 'T';
1417         else
1418                 pagestat[0] = '-';
1419
1420         pagestat[1] = '\0';
1421 }
1422
1423 void
1424 updatetitle(Client *c)
1425 {
1426         char *t;
1427
1428         if (showindicators) {
1429                 gettogglestat(c);
1430                 getpagestat(c);
1431
1432                 if (c->linkhover) {
1433                         t = g_strdup_printf("%s:%s | %s", togglestat, pagestat,
1434                                             c->linkhover);
1435                 } else if (c->progress != 100) {
1436                         t = g_strdup_printf("[%i%%] %s:%s | %s", c->progress,
1437                                             togglestat, pagestat,
1438                                             c->title == NULL ? "" : c->title);
1439                 } else {
1440                         t = g_strdup_printf("%s:%s | %s", togglestat, pagestat,
1441                                             c->title == NULL ? "" : c->title);
1442                 }
1443
1444                 gtk_window_set_title(GTK_WINDOW(c->win), t);
1445                 g_free(t);
1446         } else {
1447                 gtk_window_set_title(GTK_WINDOW(c->win), (c->title == NULL) ?
1448                                      "" : c->title);
1449         }
1450 }
1451
1452 void
1453 updatewinid(Client *c)
1454 {
1455         snprintf(winid, LENGTH(winid), "%lu", c->xid);
1456 }
1457
1458 void
1459 usage(void)
1460 {
1461         die("usage: %s [-bBdDfFgGiIkKmMnNpPsSvx] [-a cookiepolicies ] "
1462             "[-c cookiefile] [-e xid] [-r scriptfile] [-t stylefile] "
1463             "[-u useragent] [-z zoomlevel] [uri]\n", basename(argv0));
1464 }
1465
1466 void
1467 windowobjectcleared(GtkWidget *w, WebKitWebFrame *frame, JSContextRef js,
1468                     JSObjectRef win, Client *c)
1469 {
1470         runscript(frame);
1471 }
1472
1473 void
1474 zoom(Client *c, const Arg *arg)
1475 {
1476         c->zoomed = TRUE;
1477         if (arg->i < 0) {
1478                 /* zoom out */
1479                 webkit_web_view_zoom_out(c->view);
1480         } else if (arg->i > 0) {
1481                 /* zoom in */
1482                 webkit_web_view_zoom_in(c->view);
1483         } else {
1484                 /* reset */
1485                 c->zoomed = FALSE;
1486                 webkit_web_view_set_zoom_level(c->view, 1.0);
1487         }
1488 }
1489
1490 int
1491 main(int argc, char *argv[])
1492 {
1493         Arg arg;
1494         Client *c;
1495
1496         memset(&arg, 0, sizeof(arg));
1497
1498         /* command line args */
1499         ARGBEGIN {
1500         case 'a':
1501                 cookiepolicies = EARGF(usage());
1502                 break;
1503         case 'b':
1504                 enablescrollbars = 0;
1505                 break;
1506         case 'B':
1507                 enablescrollbars = 1;
1508                 break;
1509         case 'c':
1510                 cookiefile = EARGF(usage());
1511                 break;
1512         case 'd':
1513                 enablediskcache = 0;
1514                 break;
1515         case 'D':
1516                 enablediskcache = 1;
1517                 break;
1518         case 'e':
1519                 embed = strtol(EARGF(usage()), NULL, 0);
1520                 break;
1521         case 'f':
1522                 runinfullscreen = 0;
1523                 break;
1524         case 'F':
1525                 runinfullscreen = 1;
1526                 break;
1527         case 'g':
1528                 allowgeolocation = 0;
1529                 break;
1530         case 'G':
1531                 allowgeolocation = 1;
1532                 break;
1533         case 'i':
1534                 loadimages = 0;
1535                 break;
1536         case 'I':
1537                 loadimages = 1;
1538                 break;
1539         case 'k':
1540                 kioskmode = 0;
1541                 break;
1542         case 'K':
1543                 kioskmode = 1;
1544                 break;
1545         case 'm':
1546                 enablestyle = 0;
1547                 break;
1548         case 'M':
1549                 enablestyle = 1;
1550                 break;
1551         case 'n':
1552                 enableinspector = 0;
1553                 break;
1554         case 'N':
1555                 enableinspector = 1;
1556                 break;
1557         case 'p':
1558                 enableplugins = 0;
1559                 break;
1560         case 'P':
1561                 enableplugins = 1;
1562                 break;
1563         case 'r':
1564                 scriptfile = EARGF(usage());
1565                 break;
1566         case 's':
1567                 enablescripts = 0;
1568                 break;
1569         case 'S':
1570                 enablescripts = 1;
1571                 break;
1572         case 't':
1573                 stylefile = EARGF(usage());
1574                 break;
1575         case 'u':
1576                 useragent = EARGF(usage());
1577                 break;
1578         case 'v':
1579                 die("surf-"VERSION", ©2009-2015 surf engineers, "
1580                     "see LICENSE for details\n");
1581         case 'x':
1582                 showxid = TRUE;
1583                 break;
1584         case 'z':
1585                 zoomlevel = strtof(EARGF(usage()), NULL);
1586                 break;
1587         default:
1588                 usage();
1589         } ARGEND;
1590         if (argc > 0)
1591                 arg.v = argv[0];
1592
1593         setup();
1594         c = newclient();
1595         if (arg.v)
1596                 loaduri(clients, &arg);
1597         else
1598                 updatetitle(c);
1599
1600         gtk_main();
1601         cleanup();
1602
1603         return EXIT_SUCCESS;
1604 }
1605