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