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