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