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