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