Replace linkhover() with mousetargetchanged()
[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 void geopolicyrequested(WebKitWebView *v, WebKitWebFrame *f,
134                                WebKitGeolocationPolicyDecision *d, 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 void
531 geopolicyrequested(WebKitWebView *v, WebKitWebFrame *f,
532                    WebKitGeolocationPolicyDecision *d, Client *c)
533 {
534         if (allowgeolocation)
535                 webkit_geolocation_policy_allow(d);
536         else
537                 webkit_geolocation_policy_deny(d);
538 }
539
540 const char *
541 getatom(Client *c, int a)
542 {
543         static char buf[BUFSIZ];
544         Atom adummy;
545         int idummy;
546         unsigned long ldummy;
547         unsigned char *p = NULL;
548
549         XGetWindowProperty(dpy, c->xid,
550                            atoms[a], 0L, BUFSIZ, False, XA_STRING,
551                            &adummy, &idummy, &ldummy, &ldummy, &p);
552         if (p)
553                 strncpy(buf, (char *)p, LENGTH(buf)-1);
554         else
555                 buf[0] = '\0';
556         XFree(p);
557
558         return buf;
559 }
560
561 char *
562 geturi(Client *c)
563 {
564         char *uri;
565
566         if (!(uri = (char *)webkit_web_view_get_uri(c->view)))
567                 uri = "about:blank";
568         return uri;
569 }
570
571 const gchar *
572 getstyle(const char *uri)
573 {
574         int i;
575
576         if (stylefile != NULL)
577                 return stylefile;
578
579         for (i = 0; i < LENGTH(styles); i++) {
580                 if (styles[i].regex && !regexec(&(styles[i].re), uri, 0,
581                     NULL, 0))
582                         return styles[i].style;
583         }
584
585         return "";
586 }
587
588 void
589 setstyle(Client *c, const char *style)
590 {
591         WebKitWebSettings *settings = webkit_web_view_get_settings(c->view);
592
593         g_object_set(G_OBJECT(settings), "user-stylesheet-uri", style, NULL);
594 }
595
596 void
597 handleplumb(Client *c, WebKitWebView *w, const gchar *uri)
598 {
599         Arg arg;
600
601         webkit_web_view_stop_loading(w);
602         arg = (Arg)PLUMB((char *)uri);
603         spawn(c, &arg);
604 }
605
606 gboolean
607 initdownload(WebKitWebView *view, WebKitDownload *o, Client *c)
608 {
609         Arg arg;
610
611         updatewinid(c);
612         arg = (Arg)DOWNLOAD((char *)webkit_download_get_uri(o), geturi(c));
613         spawn(c, &arg);
614         return FALSE;
615 }
616
617 void
618 inspector(Client *c, const Arg *arg)
619 {
620         if (enableinspector) {
621                 if (c->isinspecting)
622                         webkit_web_inspector_close(c->inspector);
623                 else
624                         webkit_web_inspector_show(c->inspector);
625         }
626 }
627
628 WebKitWebView *
629 inspector_new(WebKitWebInspector *i, WebKitWebView *v, Client *c)
630 {
631         return WEBKIT_WEB_VIEW(webkit_web_view_new());
632 }
633
634 gboolean
635 inspector_show(WebKitWebInspector *i, Client *c)
636 {
637         WebKitWebView *w;
638
639         if (c->isinspecting)
640                 return false;
641
642         w = webkit_web_inspector_get_web_view(i);
643         gtk_paned_pack2(GTK_PANED(c->pane), GTK_WIDGET(w), TRUE, TRUE);
644         gtk_widget_show(GTK_WIDGET(w));
645         c->isinspecting = true;
646
647         return true;
648 }
649
650 gboolean
651 inspector_close(WebKitWebInspector *i, Client *c)
652 {
653         GtkWidget *w;
654
655         if (!c->isinspecting)
656                 return false;
657
658         w = GTK_WIDGET(webkit_web_inspector_get_web_view(i));
659         gtk_widget_hide(w);
660         gtk_widget_destroy(w);
661         c->isinspecting = false;
662
663         return true;
664 }
665
666 void
667 inspector_finished(WebKitWebInspector *i, Client *c)
668 {
669         g_free(c->inspector);
670 }
671
672 gboolean
673 keypress(GtkAccelGroup *group, GObject *obj, guint key, GdkModifierType mods,
674          Client *c)
675 {
676         guint i;
677         gboolean processed = FALSE;
678
679         mods = CLEANMASK(mods);
680         key = gdk_keyval_to_lower(key);
681         updatewinid(c);
682         for (i = 0; i < LENGTH(keys); i++) {
683                 if (key == keys[i].keyval
684                     && mods == keys[i].mod
685                     && keys[i].func) {
686                         keys[i].func(c, &(keys[i].arg));
687                         processed = TRUE;
688                 }
689         }
690
691         return processed;
692 }
693
694 void
695 mousetargetchanged(WebKitWebView *v, WebKitHitTestResult *h, guint modifiers,
696     Client *c)
697 {
698         WebKitHitTestResultContext hc;
699
700         /* Keep the hit test to know where is the pointer on the next click */
701         c->mousepos = h;
702
703         hc = webkit_hit_test_result_get_context(h);
704
705         if (hc & OnLink)
706                 c->targeturi = webkit_hit_test_result_get_link_uri(h);
707         else if (hc & OnImg)
708                 c->targeturi = webkit_hit_test_result_get_image_uri(h);
709         else if (hc & OnMedia)
710                 c->targeturi = webkit_hit_test_result_get_media_uri(h);
711         else
712                 c->targeturi = NULL;
713         updatetitle(c);
714 }
715
716 void
717 loadstatuschange(WebKitWebView *view, GParamSpec *pspec, Client *c)
718 {
719         WebKitWebFrame *frame;
720         WebKitWebDataSource *src;
721         WebKitNetworkRequest *request;
722         SoupMessage *msg;
723         char *uri;
724
725         switch (webkit_web_view_get_load_status (c->view)) {
726         case WEBKIT_LOAD_COMMITTED:
727                 uri = geturi(c);
728                 if (strstr(uri, "https://") == uri) {
729                         frame = webkit_web_view_get_main_frame(c->view);
730                         src = webkit_web_frame_get_data_source(frame);
731                         request = webkit_web_data_source_get_request(src);
732                         msg = webkit_network_request_get_message(request);
733                         c->sslfailed = !(soup_message_get_flags(msg)
734                                        & SOUP_MESSAGE_CERTIFICATE_TRUSTED);
735                 }
736                 setatom(c, AtomUri, uri);
737
738                 if (enablestyle)
739                         setstyle(c, getstyle(uri));
740                 break;
741         case WEBKIT_LOAD_FINISHED:
742                 c->progress = 100;
743                 updatetitle(c);
744                 break;
745         default:
746                 break;
747         }
748 }
749
750 void
751 loaduri(Client *c, const Arg *arg)
752 {
753         char *u = NULL, *rp;
754         const char *uri = (char *)arg->v;
755         Arg a = { .b = FALSE };
756         struct stat st;
757
758         if (strcmp(uri, "") == 0)
759                 return;
760
761         /* In case it's a file path. */
762         if (stat(uri, &st) == 0) {
763                 rp = realpath(uri, NULL);
764                 u = g_strdup_printf("file://%s", rp);
765                 free(rp);
766         } else {
767                 u = g_strrstr(uri, "://") ? g_strdup(uri)
768                     : g_strdup_printf("http://%s", uri);
769         }
770
771         setatom(c, AtomUri, uri);
772
773         /* prevents endless loop */
774         if (strcmp(u, geturi(c)) == 0) {
775                 reload(c, &a);
776         } else {
777                 webkit_web_view_load_uri(c->view, u);
778                 c->progress = 0;
779                 c->title = copystr(&c->title, u);
780                 updatetitle(c);
781         }
782         g_free(u);
783 }
784
785 void
786 navigate(Client *c, const Arg *arg)
787 {
788         int steps = *(int *)arg;
789         webkit_web_view_go_back_or_forward(c->view, steps);
790 }
791
792 Client *
793 newclient(Client *rc)
794 {
795         Client *c;
796         gdouble dpi;
797
798         if (!(c = calloc(1, sizeof(Client))))
799                 die("Cannot malloc!\n");
800
801         c->title = NULL;
802         c->progress = 100;
803
804         c->next = clients;
805         clients = c;
806
807         c->view = newview(c, rc ? rc->view : NULL);
808
809         return c;
810 }
811
812 WebKitWebView *
813 newview(Client *c, WebKitWebView *rv)
814 {
815         WebKitWebView *v;
816         WebKitSettings *settings;
817         WebKitUserContentManager *contentmanager;
818         WebKitWebContext *context;
819         char *ua;
820
821         /* Webview */
822         if (rv) {
823                 v = WEBKIT_WEB_VIEW(
824                     webkit_web_view_new_with_related_view(rv));
825         } else {
826                 settings = webkit_settings_new_with_settings(
827                     "auto-load-images", loadimages,
828                     "default-font-size", defaultfontsize,
829                     "enable-caret-browsing", enablecaretbrowsing,
830                     "enable-developer-extras", enableinspector,
831                     "enable-dns-prefetching", enablednsprefetching,
832                     "enable-frame-flattening", enableframeflattening,
833                     "enable-html5-database", enablecache,
834                     "enable-html5-local-storage", enablecache,
835                     "enable-javascript", enablescripts,
836                     "enable-plugins", enableplugins,
837                     NULL);
838                 if (!(ua = getenv("SURF_USERAGENT")))
839                         ua = useragent;
840                 webkit_settings_set_user_agent(settings, ua);
841                 /* Have a look at http://webkitgtk.org/reference/webkit2gtk/stable/WebKitSettings.html
842                  * for more interesting settings */
843
844                 contentmanager = webkit_user_content_manager_new();
845
846                 context = webkit_web_context_new_with_website_data_manager(
847                     webkit_website_data_manager_new(
848                     "base-cache-directory", cachedir,
849                     "base-data-directory", cachedir,
850                     NULL));
851
852                 /* rendering process model, can be a shared unique one or one for each
853                  * view */
854                 webkit_web_context_set_process_model(context,
855                     WEBKIT_PROCESS_MODEL_MULTIPLE_SECONDARY_PROCESSES);
856                 /* ssl */
857                 webkit_web_context_set_tls_errors_policy(context, strictssl ?
858                     WEBKIT_TLS_ERRORS_POLICY_FAIL : WEBKIT_TLS_ERRORS_POLICY_IGNORE);
859                 /* disk cache */
860                 webkit_web_context_set_cache_model(context, enablecache ?
861                     WEBKIT_CACHE_MODEL_WEB_BROWSER : WEBKIT_CACHE_MODEL_DOCUMENT_VIEWER);
862
863                 /* Currently only works with text file to be compatible with curl */
864                 webkit_cookie_manager_set_persistent_storage(
865                     webkit_web_context_get_cookie_manager(context), cookiefile,
866                     WEBKIT_COOKIE_PERSISTENT_STORAGE_TEXT);
867                 /* cookie policy */
868                 webkit_cookie_manager_set_accept_policy(
869                     webkit_web_context_get_cookie_manager(context),
870                     cookiepolicy_get());
871
872                 v = g_object_new(WEBKIT_TYPE_WEB_VIEW,
873                     "settings", settings,
874                     "user-content-manager", contentmanager,
875                     "web-context", context,
876                     NULL);
877         }
878
879         g_signal_connect(G_OBJECT(v),
880                          "notify::title",
881                          G_CALLBACK(titlechanged), c);
882         g_signal_connect(G_OBJECT(v),
883                          "mouse-target-changed",
884                          G_CALLBACK(mousetargetchanged), c);
885         g_signal_connect(G_OBJECT(v),
886                          "geolocation-policy-decision-requested",
887                          G_CALLBACK(geopolicyrequested), c);
888         g_signal_connect(G_OBJECT(v),
889                          "create-web-view",
890                          G_CALLBACK(createwindow), c);
891         g_signal_connect(G_OBJECT(v), "ready-to-show",
892                          G_CALLBACK(showview), c);
893         g_signal_connect(G_OBJECT(v),
894                          "new-window-policy-decision-requested",
895                          G_CALLBACK(decidewindow), c);
896         g_signal_connect(G_OBJECT(v),
897                          "mime-type-policy-decision-requested",
898                          G_CALLBACK(decidedownload), c);
899         g_signal_connect(G_OBJECT(v),
900                          "window-object-cleared",
901                          G_CALLBACK(windowobjectcleared), c);
902         g_signal_connect(G_OBJECT(v),
903                          "notify::load-status",
904                          G_CALLBACK(loadstatuschange), c);
905         g_signal_connect(G_OBJECT(v),
906                          "notify::progress",
907                          G_CALLBACK(progresschange), c);
908         g_signal_connect(G_OBJECT(v),
909                          "download-requested",
910                          G_CALLBACK(initdownload), c);
911         g_signal_connect(G_OBJECT(v),
912                          "button-release-event",
913                          G_CALLBACK(buttonrelease), c);
914         g_signal_connect(G_OBJECT(v),
915                          "context-menu",
916                          G_CALLBACK(contextmenu), c);
917         g_signal_connect(G_OBJECT(v),
918                          "resource-request-starting",
919                          G_CALLBACK(beforerequest), c);
920         g_signal_connect(G_OBJECT(v),
921                          "should-show-delete-interface-for-element",
922                          G_CALLBACK(deletion_interface), c);
923
924         return v;
925 }
926
927 void
928 showview(WebKitWebView *v, Client *c)
929 {
930         GdkGeometry hints = { 1, 1 };
931         GdkRGBA bgcolor = { 0 };
932         GdkWindow *gwin;
933
934         /* Window */
935         if (embed) {
936                 c->win = gtk_plug_new(embed);
937         } else {
938                 c->win = gtk_window_new(GTK_WINDOW_TOPLEVEL);
939
940                 /* TA:  20091214:  Despite what the GNOME docs say, the ICCCM
941                  * is always correct, so we should still call this function.
942                  * But when doing so, we *must* differentiate between a
943                  * WM_CLASS and a resource on the window.  By convention, the
944                  * window class (WM_CLASS) is capped, while the resource is in
945                  * lowercase.   Both these values come as a pair.
946                  */
947                 gtk_window_set_wmclass(GTK_WINDOW(c->win), "surf", "Surf");
948
949                 /* TA:  20091214:  And set the role here as well -- so that
950                  * sessions can pick this up.
951                  */
952                 gtk_window_set_role(GTK_WINDOW(c->win), "Surf");
953         }
954         gtk_window_set_default_size(GTK_WINDOW(c->win), 800, 600);
955         g_signal_connect(G_OBJECT(c->win),
956                          "destroy",
957                          G_CALLBACK(destroywin), c);
958         g_signal_connect(G_OBJECT(c->win),
959                          "leave_notify_event",
960                          G_CALLBACK(titlechangeleave), c);
961
962         if (!kioskmode)
963                 addaccelgroup(c);
964
965         /* Arranging */
966         gtk_container_add(GTK_CONTAINER(c->win), GTK_WIDGET(c->view));
967
968         /* Setup */
969         gtk_widget_grab_focus(GTK_WIDGET(c->view));
970         gtk_widget_show(GTK_WIDGET(c->view));
971         gtk_widget_show(c->win);
972         gwin = gtk_widget_get_window(GTK_WIDGET(c->win));
973         c->xid = gdk_x11_window_get_xid(gwin);
974         gtk_window_set_geometry_hints(GTK_WINDOW(c->win), NULL, &hints,
975                                       GDK_HINT_MIN_SIZE);
976         gdk_window_set_events(gwin, GDK_ALL_EVENTS_MASK);
977         gdk_window_add_filter(gwin, processx, c);
978
979         runscript(frame);
980
981         /* This might conflict with _zoomto96dpi_. */
982         if (zoomlevel != 1.0)
983                 webkit_web_view_set_zoom_level(c->view, zoomlevel);
984
985         if (runinfullscreen)
986                 fullscreen(c, NULL);
987
988         setatom(c, AtomFind, "");
989         setatom(c, AtomUri, "about:blank");
990         if (hidebackground)
991                 webkit_web_view_set_background_color(c->view, &bgcolor);
992
993         if (showxid) {
994                 gdk_display_sync(gtk_widget_get_display(c->win));
995                 printf("%lu\n", c->xid);
996                 fflush(NULL);
997                 if (fclose(stdout) != 0) {
998                         die("Error closing stdout");
999                 }
1000         }
1001 }
1002
1003 void
1004 newwindow(Client *c, const Arg *arg, gboolean noembed)
1005 {
1006         guint i = 0;
1007         const char *cmd[18], *uri;
1008         const Arg a = { .v = (void *)cmd };
1009         char tmp[64];
1010
1011         cmd[i++] = argv0;
1012         cmd[i++] = "-a";
1013         cmd[i++] = cookiepolicies;
1014         if (!enablescrollbars)
1015                 cmd[i++] = "-b";
1016         if (embed && !noembed) {
1017                 cmd[i++] = "-e";
1018                 snprintf(tmp, LENGTH(tmp), "%u", (int)embed);
1019                 cmd[i++] = tmp;
1020         }
1021         if (!allowgeolocation)
1022                 cmd[i++] = "-g";
1023         if (!loadimages)
1024                 cmd[i++] = "-i";
1025         if (kioskmode)
1026                 cmd[i++] = "-k";
1027         if (!enableplugins)
1028                 cmd[i++] = "-p";
1029         if (!enablescripts)
1030                 cmd[i++] = "-s";
1031         if (showxid)
1032                 cmd[i++] = "-x";
1033         if (enablediskcache)
1034                 cmd[i++] = "-D";
1035         cmd[i++] = "-c";
1036         cmd[i++] = cookiefile;
1037         cmd[i++] = "--";
1038         uri = arg->v ? (char *)arg->v : c->linkhover;
1039         if (uri)
1040                 cmd[i++] = uri;
1041         cmd[i++] = NULL;
1042         spawn(NULL, &a);
1043 }
1044
1045 gboolean
1046 contextmenu(WebKitWebView *view, GtkWidget *menu, WebKitHitTestResult *target,
1047             gboolean keyboard, Client *c)
1048 {
1049         GList *items = gtk_container_get_children(GTK_CONTAINER(GTK_MENU(menu)));
1050
1051         for (GList *l = items; l; l = l->next)
1052                 g_signal_connect(l->data, "activate", G_CALLBACK(menuactivate), c);
1053
1054         g_list_free(items);
1055         return FALSE;
1056 }
1057
1058 void
1059 menuactivate(GtkMenuItem *item, Client *c)
1060 {
1061         /*
1062          * context-menu-action-2000 open link
1063          * context-menu-action-1    open link in window
1064          * context-menu-action-2    download linked file
1065          * context-menu-action-3    copy link location
1066          * context-menu-action-7    copy image address
1067          * context-menu-action-13   reload
1068          * context-menu-action-10   back
1069          * context-menu-action-11   forward
1070          * context-menu-action-12   stop
1071          */
1072
1073         const gchar *name, *uri;
1074         GtkClipboard *prisel, *clpbrd;
1075
1076         name = gtk_actionable_get_action_name(GTK_ACTIONABLE(item));
1077         if (name == NULL)
1078                 return;
1079
1080         if (!g_strcmp0(name, "context-menu-action-3")) {
1081                 prisel = gtk_clipboard_get(GDK_SELECTION_PRIMARY);
1082                 gtk_clipboard_set_text(prisel, c->linkhover, -1);
1083         } else if (!g_strcmp0(name, "context-menu-action-7")) {
1084                 prisel = gtk_clipboard_get(GDK_SELECTION_PRIMARY);
1085                 clpbrd = gtk_clipboard_get(GDK_SELECTION_CLIPBOARD);
1086                 uri = gtk_clipboard_wait_for_text(clpbrd);
1087                 if (uri)
1088                         gtk_clipboard_set_text(prisel, uri, -1);
1089         }
1090 }
1091
1092 void
1093 pasteuri(GtkClipboard *clipboard, const char *text, gpointer d)
1094 {
1095         Arg arg = {.v = text };
1096         if (text != NULL)
1097                 loaduri((Client *) d, &arg);
1098 }
1099
1100 void
1101 print(Client *c, const Arg *arg)
1102 {
1103         webkit_web_frame_print(webkit_web_view_get_main_frame(c->view));
1104 }
1105
1106 GdkFilterReturn
1107 processx(GdkXEvent *e, GdkEvent *event, gpointer d)
1108 {
1109         Client *c = (Client *)d;
1110         XPropertyEvent *ev;
1111         Arg arg;
1112
1113         if (((XEvent *)e)->type == PropertyNotify) {
1114                 ev = &((XEvent *)e)->xproperty;
1115                 if (ev->state == PropertyNewValue) {
1116                         if (ev->atom == atoms[AtomFind]) {
1117                                 arg.b = TRUE;
1118                                 find(c, &arg);
1119
1120                                 return GDK_FILTER_REMOVE;
1121                         } else if (ev->atom == atoms[AtomGo]) {
1122                                 arg.v = getatom(c, AtomGo);
1123                                 loaduri(c, &arg);
1124
1125                                 return GDK_FILTER_REMOVE;
1126                         }
1127                 }
1128         }
1129         return GDK_FILTER_CONTINUE;
1130 }
1131
1132 void
1133 progresschange(WebKitWebView *view, GParamSpec *pspec, Client *c)
1134 {
1135         c->progress = webkit_web_view_get_progress(c->view) * 100;
1136         updatetitle(c);
1137 }
1138
1139 void
1140 linkopen(Client *c, const Arg *arg)
1141 {
1142         newwindow(NULL, arg, 1);
1143 }
1144
1145 void
1146 linkopenembed(Client *c, const Arg *arg)
1147 {
1148         newwindow(NULL, arg, 0);
1149 }
1150
1151 void
1152 reload(Client *c, const Arg *arg)
1153 {
1154         gboolean nocache = *(gboolean *)arg;
1155         if (nocache)
1156                 webkit_web_view_reload_bypass_cache(c->view);
1157         else
1158                 webkit_web_view_reload(c->view);
1159 }
1160
1161 void
1162 scroll_h(Client *c, const Arg *arg)
1163 {
1164         scroll(gtk_scrolled_window_get_hadjustment(
1165                GTK_SCROLLED_WINDOW(c->scroll)), arg);
1166 }
1167
1168 void
1169 scroll_v(Client *c, const Arg *arg)
1170 {
1171         scroll(gtk_scrolled_window_get_vadjustment(
1172                GTK_SCROLLED_WINDOW(c->scroll)), arg);
1173 }
1174
1175 void
1176 scroll(GtkAdjustment *a, const Arg *arg)
1177 {
1178         gdouble v;
1179
1180         v = gtk_adjustment_get_value(a);
1181         switch (arg->i) {
1182         case +10000:
1183         case -10000:
1184                 v += gtk_adjustment_get_page_increment(a) * (arg->i / 10000);
1185                 break;
1186         case +20000:
1187         case -20000:
1188         default:
1189                 v += gtk_adjustment_get_step_increment(a) * arg->i;
1190         }
1191
1192         v = MAX(v, 0.0);
1193         v = MIN(v, gtk_adjustment_get_upper(a) -
1194                 gtk_adjustment_get_page_size(a));
1195         gtk_adjustment_set_value(a, v);
1196 }
1197
1198 void
1199 setatom(Client *c, int a, const char *v)
1200 {
1201         XSync(dpy, False);
1202         XChangeProperty(dpy, c->xid,
1203                         atoms[a], XA_STRING, 8, PropModeReplace,
1204                         (unsigned char *)v, strlen(v) + 1);
1205 }
1206
1207 void
1208 setup(void)
1209 {
1210         int i;
1211         char *styledirfile, *stylepath;
1212         WebKitWebContext *context;
1213         GError *error = NULL;
1214
1215         /* clean up any zombies immediately */
1216         sigchld(0);
1217         gtk_init(NULL, NULL);
1218
1219         dpy = GDK_DISPLAY_XDISPLAY(gdk_display_get_default());
1220
1221         /* atoms */
1222         atoms[AtomFind] = XInternAtom(dpy, "_SURF_FIND", False);
1223         atoms[AtomGo] = XInternAtom(dpy, "_SURF_GO", False);
1224         atoms[AtomUri] = XInternAtom(dpy, "_SURF_URI", False);
1225
1226         /* dirs and files */
1227         cookiefile = buildfile(cookiefile);
1228         scriptfile = buildfile(scriptfile);
1229         cachedir   = buildpath(cachedir);
1230         if (stylefile == NULL) {
1231                 styledir = buildpath(styledir);
1232                 for (i = 0; i < LENGTH(styles); i++) {
1233                         if (regcomp(&(styles[i].re), styles[i].regex,
1234                             REG_EXTENDED)) {
1235                                 fprintf(stderr,
1236                                         "Could not compile regex: %s\n",
1237                                         styles[i].regex);
1238                                 styles[i].regex = NULL;
1239                         }
1240                         styledirfile    = g_strconcat(styledir, "/",
1241                                                       styles[i].style, NULL);
1242                         stylepath       = buildfile(styledirfile);
1243                         styles[i].style = g_strconcat("file://", stylepath,
1244                                                       NULL);
1245                         g_free(styledirfile);
1246                         g_free(stylepath);
1247                 }
1248                 g_free(styledir);
1249         } else {
1250                 stylepath = buildfile(stylefile);
1251                 stylefile = g_strconcat("file://", stylepath, NULL);
1252                 g_free(stylepath);
1253         }
1254 }
1255
1256 void
1257 sigchld(int unused)
1258 {
1259         if (signal(SIGCHLD, sigchld) == SIG_ERR)
1260                 die("Can't install SIGCHLD handler");
1261         while (0 < waitpid(-1, NULL, WNOHANG));
1262 }
1263
1264 void
1265 spawn(Client *c, const Arg *arg)
1266 {
1267         if (fork() == 0) {
1268                 if (dpy)
1269                         close(ConnectionNumber(dpy));
1270                 setsid();
1271                 execvp(((char **)arg->v)[0], (char **)arg->v);
1272                 fprintf(stderr, "surf: execvp %s", ((char **)arg->v)[0]);
1273                 perror(" failed");
1274                 exit(0);
1275         }
1276 }
1277
1278 void
1279 eval(Client *c, const Arg *arg)
1280 {
1281         WebKitWebFrame *frame = webkit_web_view_get_main_frame(c->view);
1282         evalscript(webkit_web_frame_get_global_context(frame),
1283                    ((char **)arg->v)[0], "");
1284 }
1285
1286 void
1287 stop(Client *c, const Arg *arg)
1288 {
1289         webkit_web_view_stop_loading(c->view);
1290 }
1291
1292 void
1293 titlechanged(WebKitWebView *view, GParamSpec *ps, Client *c)
1294 {
1295         c->title = webkit_web_view_get_title(c->view);
1296         updatetitle(c);
1297 }
1298
1299 void
1300 titlechangeleave(void *a, void *b, Client *c)
1301 {
1302         c->linkhover = NULL;
1303         updatetitle(c);
1304 }
1305
1306 void
1307 toggle(Client *c, const Arg *arg)
1308 {
1309         WebKitWebSettings *settings;
1310         char *name = (char *)arg->v;
1311         gboolean value;
1312         Arg a = { .b = FALSE };
1313
1314         settings = webkit_web_view_get_settings(c->view);
1315         g_object_get(G_OBJECT(settings), name, &value, NULL);
1316         g_object_set(G_OBJECT(settings), name, !value, NULL);
1317
1318         reload(c, &a);
1319 }
1320
1321 void
1322 togglecookiepolicy(Client *c, const Arg *arg)
1323 {
1324         ++cookiepolicy;
1325         cookiepolicy %= strlen(cookiepolicies);
1326
1327         webkit_cookie_manager_set_accept_policy(
1328             webkit_web_context_get_cookie_manager(
1329             webkit_web_view_get_context(c->view)),
1330             cookiepolicy_get());
1331
1332         updatetitle(c);
1333         /* Do not reload. */
1334 }
1335
1336 void
1337 togglegeolocation(Client *c, const Arg *arg)
1338 {
1339         Arg a = { .b = FALSE };
1340
1341         allowgeolocation ^= 1;
1342         reload(c, &a);
1343 }
1344
1345 void
1346 twitch(Client *c, const Arg *arg)
1347 {
1348         GtkAdjustment *a;
1349         gdouble v;
1350
1351         a = gtk_scrolled_window_get_vadjustment(GTK_SCROLLED_WINDOW(
1352                                                 c->scroll));
1353
1354         v = gtk_adjustment_get_value(a);
1355
1356         v += arg->i;
1357
1358         v = MAX(v, 0.0);
1359         v = MIN(v, gtk_adjustment_get_upper(a) -
1360                 gtk_adjustment_get_page_size(a));
1361         gtk_adjustment_set_value(a, v);
1362 }
1363
1364 void
1365 togglescrollbars(Client *c, const Arg *arg)
1366 {
1367         GtkPolicyType vspolicy;
1368         Arg a;
1369
1370         gtk_scrolled_window_get_policy(GTK_SCROLLED_WINDOW(c->scroll), NULL,
1371                                        &vspolicy);
1372
1373         if (vspolicy == GTK_POLICY_AUTOMATIC) {
1374                 gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(c->scroll),
1375                                                GTK_POLICY_NEVER,
1376                                                GTK_POLICY_NEVER);
1377         } else {
1378                 gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(c->scroll),
1379                                                GTK_POLICY_AUTOMATIC,
1380                                                GTK_POLICY_AUTOMATIC);
1381                 a.i = +1;
1382                 twitch(c, &a);
1383                 a.i = -1;
1384                 twitch(c, &a);
1385         }
1386 }
1387
1388 void
1389 togglestyle(Client *c, const Arg *arg)
1390 {
1391         enablestyle = !enablestyle;
1392         setstyle(c, enablestyle ? getstyle(geturi(c)) : "");
1393
1394         updatetitle(c);
1395 }
1396
1397 void
1398 gettogglestat(Client *c)
1399 {
1400         gboolean value;
1401         int p = 0;
1402         WebKitWebSettings *settings = webkit_web_view_get_settings(c->view);
1403
1404         togglestat[p++] = cookiepolicy_set(cookiepolicy_get());
1405
1406         g_object_get(G_OBJECT(settings), "enable-caret-browsing", &value,
1407                      NULL);
1408         togglestat[p++] = value? 'C': 'c';
1409
1410         togglestat[p++] = allowgeolocation? 'G': 'g';
1411
1412         togglestat[p++] = enablediskcache? 'D': 'd';
1413
1414         g_object_get(G_OBJECT(settings), "auto-load-images", &value, NULL);
1415         togglestat[p++] = value? 'I': 'i';
1416
1417         g_object_get(G_OBJECT(settings), "enable-scripts", &value, NULL);
1418         togglestat[p++] = value? 'S': 's';
1419
1420         g_object_get(G_OBJECT(settings), "enable-plugins", &value, NULL);
1421         togglestat[p++] = value? 'V': 'v';
1422
1423         togglestat[p++] = enablestyle ? 'M': 'm';
1424
1425         togglestat[p] = '\0';
1426 }
1427
1428 void
1429 getpagestat(Client *c)
1430 {
1431         const char *uri = geturi(c);
1432
1433         if (strstr(uri, "https://") == uri)
1434                 pagestat[0] = c->sslfailed ? 'U' : 'T';
1435         else
1436                 pagestat[0] = '-';
1437
1438         pagestat[1] = '\0';
1439 }
1440
1441 void
1442 updatetitle(Client *c)
1443 {
1444         char *t;
1445
1446         if (showindicators) {
1447                 gettogglestat(c);
1448                 getpagestat(c);
1449
1450                 if (c->linkhover) {
1451                         t = g_strdup_printf("%s:%s | %s", togglestat, pagestat,
1452                                             c->linkhover);
1453                 } else if (c->progress != 100) {
1454                         t = g_strdup_printf("[%i%%] %s:%s | %s", c->progress,
1455                                             togglestat, pagestat,
1456                                             c->title == NULL ? "" : c->title);
1457                 } else {
1458                         t = g_strdup_printf("%s:%s | %s", togglestat, pagestat,
1459                                             c->title == NULL ? "" : c->title);
1460                 }
1461
1462                 gtk_window_set_title(GTK_WINDOW(c->win), t);
1463                 g_free(t);
1464         } else {
1465                 gtk_window_set_title(GTK_WINDOW(c->win), (c->title == NULL) ?
1466                                      "" : c->title);
1467         }
1468 }
1469
1470 void
1471 updatewinid(Client *c)
1472 {
1473         snprintf(winid, LENGTH(winid), "%lu", c->xid);
1474 }
1475
1476 void
1477 usage(void)
1478 {
1479         die("usage: %s [-bBdDfFgGiIkKmMnNpPsSvx] [-a cookiepolicies ] "
1480             "[-c cookiefile] [-e xid] [-r scriptfile] [-t stylefile] "
1481             "[-u useragent] [-z zoomlevel] [uri]\n", basename(argv0));
1482 }
1483
1484 void
1485 windowobjectcleared(GtkWidget *w, WebKitWebFrame *frame, JSContextRef js,
1486                     JSObjectRef win, Client *c)
1487 {
1488         runscript(frame);
1489 }
1490
1491 void
1492 zoom(Client *c, const Arg *arg)
1493 {
1494         c->zoomed = TRUE;
1495         if (arg->i < 0) {
1496                 /* zoom out */
1497                 webkit_web_view_zoom_out(c->view);
1498         } else if (arg->i > 0) {
1499                 /* zoom in */
1500                 webkit_web_view_zoom_in(c->view);
1501         } else {
1502                 /* reset */
1503                 c->zoomed = FALSE;
1504                 webkit_web_view_set_zoom_level(c->view, 1.0);
1505         }
1506 }
1507
1508 int
1509 main(int argc, char *argv[])
1510 {
1511         Arg arg;
1512         Client *c;
1513
1514         memset(&arg, 0, sizeof(arg));
1515
1516         /* command line args */
1517         ARGBEGIN {
1518         case 'a':
1519                 cookiepolicies = EARGF(usage());
1520                 break;
1521         case 'b':
1522                 enablescrollbars = 0;
1523                 break;
1524         case 'B':
1525                 enablescrollbars = 1;
1526                 break;
1527         case 'c':
1528                 cookiefile = EARGF(usage());
1529                 break;
1530         case 'd':
1531                 enablediskcache = 0;
1532                 break;
1533         case 'D':
1534                 enablediskcache = 1;
1535                 break;
1536         case 'e':
1537                 embed = strtol(EARGF(usage()), NULL, 0);
1538                 break;
1539         case 'f':
1540                 runinfullscreen = 0;
1541                 break;
1542         case 'F':
1543                 runinfullscreen = 1;
1544                 break;
1545         case 'g':
1546                 allowgeolocation = 0;
1547                 break;
1548         case 'G':
1549                 allowgeolocation = 1;
1550                 break;
1551         case 'i':
1552                 loadimages = 0;
1553                 break;
1554         case 'I':
1555                 loadimages = 1;
1556                 break;
1557         case 'k':
1558                 kioskmode = 0;
1559                 break;
1560         case 'K':
1561                 kioskmode = 1;
1562                 break;
1563         case 'm':
1564                 enablestyle = 0;
1565                 break;
1566         case 'M':
1567                 enablestyle = 1;
1568                 break;
1569         case 'n':
1570                 enableinspector = 0;
1571                 break;
1572         case 'N':
1573                 enableinspector = 1;
1574                 break;
1575         case 'p':
1576                 enableplugins = 0;
1577                 break;
1578         case 'P':
1579                 enableplugins = 1;
1580                 break;
1581         case 'r':
1582                 scriptfile = EARGF(usage());
1583                 break;
1584         case 's':
1585                 enablescripts = 0;
1586                 break;
1587         case 'S':
1588                 enablescripts = 1;
1589                 break;
1590         case 't':
1591                 stylefile = EARGF(usage());
1592                 break;
1593         case 'u':
1594                 useragent = EARGF(usage());
1595                 break;
1596         case 'v':
1597                 die("surf-"VERSION", ©2009-2015 surf engineers, "
1598                     "see LICENSE for details\n");
1599         case 'x':
1600                 showxid = TRUE;
1601                 break;
1602         case 'z':
1603                 zoomlevel = strtof(EARGF(usage()), NULL);
1604                 break;
1605         default:
1606                 usage();
1607         } ARGEND;
1608         if (argc > 0)
1609                 arg.v = argv[0];
1610
1611         setup();
1612         c = newclient(NULL);
1613         showview(NULL, c);
1614         if (arg.v)
1615                 loaduri(clients, &arg);
1616         else
1617                 updatetitle(c);
1618
1619         gtk_main();
1620         cleanup();
1621
1622         return EXIT_SUCCESS;
1623 }
1624