No option to enforce 96DPI anymore on WebKit2
[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         /* This might conflict with _zoomto96dpi_. */
911         if (zoomlevel != 1.0)
912                 webkit_web_view_set_zoom_level(c->view, zoomlevel);
913
914         if (enableinspector) {
915                 c->inspector = webkit_web_view_get_inspector(c->view);
916                 g_signal_connect(G_OBJECT(c->inspector), "inspect-web-view",
917                                  G_CALLBACK(inspector_new), c);
918                 g_signal_connect(G_OBJECT(c->inspector), "show-window",
919                                  G_CALLBACK(inspector_show), c);
920                 g_signal_connect(G_OBJECT(c->inspector), "close-window",
921                                  G_CALLBACK(inspector_close), c);
922                 g_signal_connect(G_OBJECT(c->inspector), "finished",
923                                  G_CALLBACK(inspector_finished), c);
924                 c->isinspecting = false;
925         }
926
927         if (runinfullscreen)
928                 fullscreen(c, NULL);
929
930         setatom(c, AtomFind, "");
931         setatom(c, AtomUri, "about:blank");
932         if (hidebackground)
933                 webkit_web_view_set_transparent(c->view, TRUE);
934
935         c->next = clients;
936         clients = c;
937
938         if (showxid) {
939                 gdk_display_sync(gtk_widget_get_display(c->win));
940                 printf("%lu\n", c->xid);
941                 fflush(NULL);
942                 if (fclose(stdout) != 0) {
943                         die("Error closing stdout");
944                 }
945         }
946
947         return c;
948 }
949
950 void
951 newwindow(Client *c, const Arg *arg, gboolean noembed)
952 {
953         guint i = 0;
954         const char *cmd[18], *uri;
955         const Arg a = { .v = (void *)cmd };
956         char tmp[64];
957
958         cmd[i++] = argv0;
959         cmd[i++] = "-a";
960         cmd[i++] = cookiepolicies;
961         if (!enablescrollbars)
962                 cmd[i++] = "-b";
963         if (embed && !noembed) {
964                 cmd[i++] = "-e";
965                 snprintf(tmp, LENGTH(tmp), "%u", (int)embed);
966                 cmd[i++] = tmp;
967         }
968         if (!allowgeolocation)
969                 cmd[i++] = "-g";
970         if (!loadimages)
971                 cmd[i++] = "-i";
972         if (kioskmode)
973                 cmd[i++] = "-k";
974         if (!enableplugins)
975                 cmd[i++] = "-p";
976         if (!enablescripts)
977                 cmd[i++] = "-s";
978         if (showxid)
979                 cmd[i++] = "-x";
980         if (enablediskcache)
981                 cmd[i++] = "-D";
982         cmd[i++] = "-c";
983         cmd[i++] = cookiefile;
984         cmd[i++] = "--";
985         uri = arg->v ? (char *)arg->v : c->linkhover;
986         if (uri)
987                 cmd[i++] = uri;
988         cmd[i++] = NULL;
989         spawn(NULL, &a);
990 }
991
992 gboolean
993 contextmenu(WebKitWebView *view, GtkWidget *menu, WebKitHitTestResult *target,
994             gboolean keyboard, Client *c)
995 {
996         GList *items = gtk_container_get_children(GTK_CONTAINER(GTK_MENU(menu)));
997
998         for (GList *l = items; l; l = l->next)
999                 g_signal_connect(l->data, "activate", G_CALLBACK(menuactivate), c);
1000
1001         g_list_free(items);
1002         return FALSE;
1003 }
1004
1005 void
1006 menuactivate(GtkMenuItem *item, Client *c)
1007 {
1008         /*
1009          * context-menu-action-2000 open link
1010          * context-menu-action-1    open link in window
1011          * context-menu-action-2    download linked file
1012          * context-menu-action-3    copy link location
1013          * context-menu-action-7    copy image address
1014          * context-menu-action-13   reload
1015          * context-menu-action-10   back
1016          * context-menu-action-11   forward
1017          * context-menu-action-12   stop
1018          */
1019
1020         const gchar *name, *uri;
1021         GtkClipboard *prisel, *clpbrd;
1022
1023         name = gtk_actionable_get_action_name(GTK_ACTIONABLE(item));
1024         if (name == NULL)
1025                 return;
1026
1027         if (!g_strcmp0(name, "context-menu-action-3")) {
1028                 prisel = gtk_clipboard_get(GDK_SELECTION_PRIMARY);
1029                 gtk_clipboard_set_text(prisel, c->linkhover, -1);
1030         } else if (!g_strcmp0(name, "context-menu-action-7")) {
1031                 prisel = gtk_clipboard_get(GDK_SELECTION_PRIMARY);
1032                 clpbrd = gtk_clipboard_get(GDK_SELECTION_CLIPBOARD);
1033                 uri = gtk_clipboard_wait_for_text(clpbrd);
1034                 if (uri)
1035                         gtk_clipboard_set_text(prisel, uri, -1);
1036         }
1037 }
1038
1039 void
1040 pasteuri(GtkClipboard *clipboard, const char *text, gpointer d)
1041 {
1042         Arg arg = {.v = text };
1043         if (text != NULL)
1044                 loaduri((Client *) d, &arg);
1045 }
1046
1047 void
1048 print(Client *c, const Arg *arg)
1049 {
1050         webkit_web_frame_print(webkit_web_view_get_main_frame(c->view));
1051 }
1052
1053 GdkFilterReturn
1054 processx(GdkXEvent *e, GdkEvent *event, gpointer d)
1055 {
1056         Client *c = (Client *)d;
1057         XPropertyEvent *ev;
1058         Arg arg;
1059
1060         if (((XEvent *)e)->type == PropertyNotify) {
1061                 ev = &((XEvent *)e)->xproperty;
1062                 if (ev->state == PropertyNewValue) {
1063                         if (ev->atom == atoms[AtomFind]) {
1064                                 arg.b = TRUE;
1065                                 find(c, &arg);
1066
1067                                 return GDK_FILTER_REMOVE;
1068                         } else if (ev->atom == atoms[AtomGo]) {
1069                                 arg.v = getatom(c, AtomGo);
1070                                 loaduri(c, &arg);
1071
1072                                 return GDK_FILTER_REMOVE;
1073                         }
1074                 }
1075         }
1076         return GDK_FILTER_CONTINUE;
1077 }
1078
1079 void
1080 progresschange(WebKitWebView *view, GParamSpec *pspec, Client *c)
1081 {
1082         c->progress = webkit_web_view_get_progress(c->view) * 100;
1083         updatetitle(c);
1084 }
1085
1086 void
1087 linkopen(Client *c, const Arg *arg)
1088 {
1089         newwindow(NULL, arg, 1);
1090 }
1091
1092 void
1093 linkopenembed(Client *c, const Arg *arg)
1094 {
1095         newwindow(NULL, arg, 0);
1096 }
1097
1098 void
1099 reload(Client *c, const Arg *arg)
1100 {
1101         gboolean nocache = *(gboolean *)arg;
1102         if (nocache)
1103                 webkit_web_view_reload_bypass_cache(c->view);
1104         else
1105                 webkit_web_view_reload(c->view);
1106 }
1107
1108 void
1109 scroll_h(Client *c, const Arg *arg)
1110 {
1111         scroll(gtk_scrolled_window_get_hadjustment(
1112                GTK_SCROLLED_WINDOW(c->scroll)), arg);
1113 }
1114
1115 void
1116 scroll_v(Client *c, const Arg *arg)
1117 {
1118         scroll(gtk_scrolled_window_get_vadjustment(
1119                GTK_SCROLLED_WINDOW(c->scroll)), arg);
1120 }
1121
1122 void
1123 scroll(GtkAdjustment *a, const Arg *arg)
1124 {
1125         gdouble v;
1126
1127         v = gtk_adjustment_get_value(a);
1128         switch (arg->i) {
1129         case +10000:
1130         case -10000:
1131                 v += gtk_adjustment_get_page_increment(a) * (arg->i / 10000);
1132                 break;
1133         case +20000:
1134         case -20000:
1135         default:
1136                 v += gtk_adjustment_get_step_increment(a) * arg->i;
1137         }
1138
1139         v = MAX(v, 0.0);
1140         v = MIN(v, gtk_adjustment_get_upper(a) -
1141                 gtk_adjustment_get_page_size(a));
1142         gtk_adjustment_set_value(a, v);
1143 }
1144
1145 void
1146 setatom(Client *c, int a, const char *v)
1147 {
1148         XSync(dpy, False);
1149         XChangeProperty(dpy, c->xid,
1150                         atoms[a], XA_STRING, 8, PropModeReplace,
1151                         (unsigned char *)v, strlen(v) + 1);
1152 }
1153
1154 void
1155 setup(void)
1156 {
1157         int i;
1158         char *styledirfile, *stylepath;
1159         WebKitWebContext *context;
1160         GError *error = NULL;
1161
1162         /* clean up any zombies immediately */
1163         sigchld(0);
1164         gtk_init(NULL, NULL);
1165
1166         dpy = GDK_DISPLAY_XDISPLAY(gdk_display_get_default());
1167
1168         /* atoms */
1169         atoms[AtomFind] = XInternAtom(dpy, "_SURF_FIND", False);
1170         atoms[AtomGo] = XInternAtom(dpy, "_SURF_GO", False);
1171         atoms[AtomUri] = XInternAtom(dpy, "_SURF_URI", False);
1172
1173         /* dirs and files */
1174         cookiefile = buildfile(cookiefile);
1175         scriptfile = buildfile(scriptfile);
1176         cachefolder = buildpath(cachefolder);
1177         if (stylefile == NULL) {
1178                 styledir = buildpath(styledir);
1179                 for (i = 0; i < LENGTH(styles); i++) {
1180                         if (regcomp(&(styles[i].re), styles[i].regex,
1181                             REG_EXTENDED)) {
1182                                 fprintf(stderr,
1183                                         "Could not compile regex: %s\n",
1184                                         styles[i].regex);
1185                                 styles[i].regex = NULL;
1186                         }
1187                         styledirfile    = g_strconcat(styledir, "/",
1188                                                       styles[i].style, NULL);
1189                         stylepath       = buildfile(styledirfile);
1190                         styles[i].style = g_strconcat("file://", stylepath,
1191                                                       NULL);
1192                         g_free(styledirfile);
1193                         g_free(stylepath);
1194                 }
1195                 g_free(styledir);
1196         } else {
1197                 stylepath = buildfile(stylefile);
1198                 stylefile = g_strconcat("file://", stylepath, NULL);
1199                 g_free(stylepath);
1200         }
1201
1202         /* cookie policy */
1203         webkit_cookie_manager_set_persistent_storage(
1204             webkit_web_context_get_cookie_manager(context), cookiefile,
1205             WEBKIT_COOKIE_PERSISTENT_STORAGE_TEXT);
1206         webkit_cookie_manager_set_accept_policy(
1207             webkit_web_context_get_cookie_manager(context),
1208             cookiepolicy_get());
1209
1210         /* disk cache */
1211         webkit_web_context_set_cache_model(context, enablecache ?
1212             WEBKIT_CACHE_MODEL_WEB_BROWSER :
1213             WEBKIT_CACHE_MODEL_DOCUMENT_VIEWER);
1214
1215         /* ssl */
1216         webkit_web_context_set_tls_errors_policy(context, strictssl ?
1217             WEBKIT_TLS_ERRORS_POLICY_FAIL :
1218             WEBKIT_TLS_ERRORS_POLICY_IGNORE);
1219 }
1220
1221 void
1222 sigchld(int unused)
1223 {
1224         if (signal(SIGCHLD, sigchld) == SIG_ERR)
1225                 die("Can't install SIGCHLD handler");
1226         while (0 < waitpid(-1, NULL, WNOHANG));
1227 }
1228
1229 void
1230 spawn(Client *c, const Arg *arg)
1231 {
1232         if (fork() == 0) {
1233                 if (dpy)
1234                         close(ConnectionNumber(dpy));
1235                 setsid();
1236                 execvp(((char **)arg->v)[0], (char **)arg->v);
1237                 fprintf(stderr, "surf: execvp %s", ((char **)arg->v)[0]);
1238                 perror(" failed");
1239                 exit(0);
1240         }
1241 }
1242
1243 void
1244 eval(Client *c, const Arg *arg)
1245 {
1246         WebKitWebFrame *frame = webkit_web_view_get_main_frame(c->view);
1247         evalscript(webkit_web_frame_get_global_context(frame),
1248                    ((char **)arg->v)[0], "");
1249 }
1250
1251 void
1252 stop(Client *c, const Arg *arg)
1253 {
1254         webkit_web_view_stop_loading(c->view);
1255 }
1256
1257 void
1258 titlechange(WebKitWebView *view, GParamSpec *pspec, Client *c)
1259 {
1260         const gchar *t = webkit_web_view_get_title(view);
1261         if (t) {
1262                 c->title = copystr(&c->title, t);
1263                 updatetitle(c);
1264         }
1265 }
1266
1267 void
1268 titlechangeleave(void *a, void *b, Client *c)
1269 {
1270         c->linkhover = NULL;
1271         updatetitle(c);
1272 }
1273
1274 void
1275 toggle(Client *c, const Arg *arg)
1276 {
1277         WebKitWebSettings *settings;
1278         char *name = (char *)arg->v;
1279         gboolean value;
1280         Arg a = { .b = FALSE };
1281
1282         settings = webkit_web_view_get_settings(c->view);
1283         g_object_get(G_OBJECT(settings), name, &value, NULL);
1284         g_object_set(G_OBJECT(settings), name, !value, NULL);
1285
1286         reload(c, &a);
1287 }
1288
1289 void
1290 togglecookiepolicy(Client *c, const Arg *arg)
1291 {
1292         ++cookiepolicy;
1293         cookiepolicy %= strlen(cookiepolicies);
1294
1295         webkit_cookie_manager_set_accept_policy(
1296             webkit_web_context_get_cookie_manager(
1297             webkit_web_view_get_context(c->view)),
1298             cookiepolicy_get());
1299
1300         updatetitle(c);
1301         /* Do not reload. */
1302 }
1303
1304 void
1305 togglegeolocation(Client *c, const Arg *arg)
1306 {
1307         Arg a = { .b = FALSE };
1308
1309         allowgeolocation ^= 1;
1310         reload(c, &a);
1311 }
1312
1313 void
1314 twitch(Client *c, const Arg *arg)
1315 {
1316         GtkAdjustment *a;
1317         gdouble v;
1318
1319         a = gtk_scrolled_window_get_vadjustment(GTK_SCROLLED_WINDOW(
1320                                                 c->scroll));
1321
1322         v = gtk_adjustment_get_value(a);
1323
1324         v += arg->i;
1325
1326         v = MAX(v, 0.0);
1327         v = MIN(v, gtk_adjustment_get_upper(a) -
1328                 gtk_adjustment_get_page_size(a));
1329         gtk_adjustment_set_value(a, v);
1330 }
1331
1332 void
1333 togglescrollbars(Client *c, const Arg *arg)
1334 {
1335         GtkPolicyType vspolicy;
1336         Arg a;
1337
1338         gtk_scrolled_window_get_policy(GTK_SCROLLED_WINDOW(c->scroll), NULL,
1339                                        &vspolicy);
1340
1341         if (vspolicy == GTK_POLICY_AUTOMATIC) {
1342                 gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(c->scroll),
1343                                                GTK_POLICY_NEVER,
1344                                                GTK_POLICY_NEVER);
1345         } else {
1346                 gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(c->scroll),
1347                                                GTK_POLICY_AUTOMATIC,
1348                                                GTK_POLICY_AUTOMATIC);
1349                 a.i = +1;
1350                 twitch(c, &a);
1351                 a.i = -1;
1352                 twitch(c, &a);
1353         }
1354 }
1355
1356 void
1357 togglestyle(Client *c, const Arg *arg)
1358 {
1359         enablestyle = !enablestyle;
1360         setstyle(c, enablestyle ? getstyle(geturi(c)) : "");
1361
1362         updatetitle(c);
1363 }
1364
1365 void
1366 gettogglestat(Client *c)
1367 {
1368         gboolean value;
1369         int p = 0;
1370         WebKitWebSettings *settings = webkit_web_view_get_settings(c->view);
1371
1372         togglestat[p++] = cookiepolicy_set(cookiepolicy_get());
1373
1374         g_object_get(G_OBJECT(settings), "enable-caret-browsing", &value,
1375                      NULL);
1376         togglestat[p++] = value? 'C': 'c';
1377
1378         togglestat[p++] = allowgeolocation? 'G': 'g';
1379
1380         togglestat[p++] = enablediskcache? 'D': 'd';
1381
1382         g_object_get(G_OBJECT(settings), "auto-load-images", &value, NULL);
1383         togglestat[p++] = value? 'I': 'i';
1384
1385         g_object_get(G_OBJECT(settings), "enable-scripts", &value, NULL);
1386         togglestat[p++] = value? 'S': 's';
1387
1388         g_object_get(G_OBJECT(settings), "enable-plugins", &value, NULL);
1389         togglestat[p++] = value? 'V': 'v';
1390
1391         togglestat[p++] = enablestyle ? 'M': 'm';
1392
1393         togglestat[p] = '\0';
1394 }
1395
1396 void
1397 getpagestat(Client *c)
1398 {
1399         const char *uri = geturi(c);
1400
1401         if (strstr(uri, "https://") == uri)
1402                 pagestat[0] = c->sslfailed ? 'U' : 'T';
1403         else
1404                 pagestat[0] = '-';
1405
1406         pagestat[1] = '\0';
1407 }
1408
1409 void
1410 updatetitle(Client *c)
1411 {
1412         char *t;
1413
1414         if (showindicators) {
1415                 gettogglestat(c);
1416                 getpagestat(c);
1417
1418                 if (c->linkhover) {
1419                         t = g_strdup_printf("%s:%s | %s", togglestat, pagestat,
1420                                             c->linkhover);
1421                 } else if (c->progress != 100) {
1422                         t = g_strdup_printf("[%i%%] %s:%s | %s", c->progress,
1423                                             togglestat, pagestat,
1424                                             c->title == NULL ? "" : c->title);
1425                 } else {
1426                         t = g_strdup_printf("%s:%s | %s", togglestat, pagestat,
1427                                             c->title == NULL ? "" : c->title);
1428                 }
1429
1430                 gtk_window_set_title(GTK_WINDOW(c->win), t);
1431                 g_free(t);
1432         } else {
1433                 gtk_window_set_title(GTK_WINDOW(c->win), (c->title == NULL) ?
1434                                      "" : c->title);
1435         }
1436 }
1437
1438 void
1439 updatewinid(Client *c)
1440 {
1441         snprintf(winid, LENGTH(winid), "%lu", c->xid);
1442 }
1443
1444 void
1445 usage(void)
1446 {
1447         die("usage: %s [-bBdDfFgGiIkKmMnNpPsSvx] [-a cookiepolicies ] "
1448             "[-c cookiefile] [-e xid] [-r scriptfile] [-t stylefile] "
1449             "[-u useragent] [-z zoomlevel] [uri]\n", basename(argv0));
1450 }
1451
1452 void
1453 windowobjectcleared(GtkWidget *w, WebKitWebFrame *frame, JSContextRef js,
1454                     JSObjectRef win, Client *c)
1455 {
1456         runscript(frame);
1457 }
1458
1459 void
1460 zoom(Client *c, const Arg *arg)
1461 {
1462         c->zoomed = TRUE;
1463         if (arg->i < 0) {
1464                 /* zoom out */
1465                 webkit_web_view_zoom_out(c->view);
1466         } else if (arg->i > 0) {
1467                 /* zoom in */
1468                 webkit_web_view_zoom_in(c->view);
1469         } else {
1470                 /* reset */
1471                 c->zoomed = FALSE;
1472                 webkit_web_view_set_zoom_level(c->view, 1.0);
1473         }
1474 }
1475
1476 int
1477 main(int argc, char *argv[])
1478 {
1479         Arg arg;
1480         Client *c;
1481
1482         memset(&arg, 0, sizeof(arg));
1483
1484         /* command line args */
1485         ARGBEGIN {
1486         case 'a':
1487                 cookiepolicies = EARGF(usage());
1488                 break;
1489         case 'b':
1490                 enablescrollbars = 0;
1491                 break;
1492         case 'B':
1493                 enablescrollbars = 1;
1494                 break;
1495         case 'c':
1496                 cookiefile = EARGF(usage());
1497                 break;
1498         case 'd':
1499                 enablediskcache = 0;
1500                 break;
1501         case 'D':
1502                 enablediskcache = 1;
1503                 break;
1504         case 'e':
1505                 embed = strtol(EARGF(usage()), NULL, 0);
1506                 break;
1507         case 'f':
1508                 runinfullscreen = 0;
1509                 break;
1510         case 'F':
1511                 runinfullscreen = 1;
1512                 break;
1513         case 'g':
1514                 allowgeolocation = 0;
1515                 break;
1516         case 'G':
1517                 allowgeolocation = 1;
1518                 break;
1519         case 'i':
1520                 loadimages = 0;
1521                 break;
1522         case 'I':
1523                 loadimages = 1;
1524                 break;
1525         case 'k':
1526                 kioskmode = 0;
1527                 break;
1528         case 'K':
1529                 kioskmode = 1;
1530                 break;
1531         case 'm':
1532                 enablestyle = 0;
1533                 break;
1534         case 'M':
1535                 enablestyle = 1;
1536                 break;
1537         case 'n':
1538                 enableinspector = 0;
1539                 break;
1540         case 'N':
1541                 enableinspector = 1;
1542                 break;
1543         case 'p':
1544                 enableplugins = 0;
1545                 break;
1546         case 'P':
1547                 enableplugins = 1;
1548                 break;
1549         case 'r':
1550                 scriptfile = EARGF(usage());
1551                 break;
1552         case 's':
1553                 enablescripts = 0;
1554                 break;
1555         case 'S':
1556                 enablescripts = 1;
1557                 break;
1558         case 't':
1559                 stylefile = EARGF(usage());
1560                 break;
1561         case 'u':
1562                 useragent = EARGF(usage());
1563                 break;
1564         case 'v':
1565                 die("surf-"VERSION", ©2009-2015 surf engineers, "
1566                     "see LICENSE for details\n");
1567         case 'x':
1568                 showxid = TRUE;
1569                 break;
1570         case 'z':
1571                 zoomlevel = strtof(EARGF(usage()), NULL);
1572                 break;
1573         default:
1574                 usage();
1575         } ARGEND;
1576         if (argc > 0)
1577                 arg.v = argv[0];
1578
1579         setup();
1580         c = newclient();
1581         if (arg.v)
1582                 loaduri(clients, &arg);
1583         else
1584                 updatetitle(c);
1585
1586         gtk_main();
1587         cleanup();
1588
1589         return EXIT_SUCCESS;
1590 }
1591