1 /* See LICENSE file for copyright and license details.
3 * To understand surf, start reading main().
20 #include <gdk/gdkkeysyms.h>
22 #include <glib/gstdio.h>
25 #include <JavaScriptCore/JavaScript.h>
26 #include <webkit2/webkit2.h>
28 #include <X11/Xatom.h>
32 #define LENGTH(x) (sizeof(x) / sizeof(x[0]))
33 #define CLEANMASK(mask) (mask & (MODKEY|GDK_SHIFT_MASK))
34 #define SETB(p, s) [p] = { { .b = s }, }
35 #define SETI(p, s) [p] = { { .i = s }, }
36 #define SETV(p, s) [p] = { { .v = s }, }
37 #define SETF(p, s) [p] = { { .f = s }, }
38 #define FSETB(p, s) [p] = { { .b = s }, 1 }
39 #define FSETI(p, s) [p] = { { .i = s }, 1 }
40 #define FSETV(p, s) [p] = { { .v = s }, 1 }
41 #define FSETF(p, s) [p] = { { .f = s }, 1 }
42 #define CSETB(p, s) [p] = (Parameter){ { .b = s }, 1 }
43 #define CSETI(p, s) [p] = (Parameter){ { .i = s }, 1 }
44 #define CSETV(p, s) [p] = (Parameter){ { .v = s }, 1 }
45 #define CSETF(p, s) [p] = (Parameter){ { .f = s }, 1 }
47 enum { AtomFind, AtomGo, AtomUri, AtomLast };
50 OnDoc = WEBKIT_HIT_TEST_RESULT_CONTEXT_DOCUMENT,
51 OnLink = WEBKIT_HIT_TEST_RESULT_CONTEXT_LINK,
52 OnImg = WEBKIT_HIT_TEST_RESULT_CONTEXT_IMAGE,
53 OnMedia = WEBKIT_HIT_TEST_RESULT_CONTEXT_MEDIA,
54 OnEdit = WEBKIT_HIT_TEST_RESULT_CONTEXT_EDITABLE,
55 OnBar = WEBKIT_HIT_TEST_RESULT_CONTEXT_SCROLLBAR,
56 OnSel = WEBKIT_HIT_TEST_RESULT_CONTEXT_SELECTION,
57 OnAny = OnDoc | OnLink | OnImg | OnMedia | OnEdit | OnBar | OnSel,
101 typedef struct Client {
104 WebKitWebInspector *inspector;
105 WebKitFindController *finder;
106 WebKitHitTestResult *mousepos;
107 GTlsCertificateFlags tlserr;
109 int progress, fullscreen, https, insecure;
110 const char *title, *overtitle, *targeturi;
118 void (*func)(Client *c, const Arg *a);
126 void (*func)(Client *c, const Arg *a, WebKitHitTestResult *h);
128 unsigned int stopevent;
133 Parameter config[ParameterLast];
144 static void usage(void);
145 static void die(const char *errstr, ...);
146 static void setup(void);
147 static void sigchld(int unused);
148 static void sighup(int unused);
149 static char *buildfile(const char *path);
150 static char *buildpath(const char *path);
151 static const char *getuserhomedir(const char *user);
152 static const char *getcurrentuserhomedir(void);
153 static Client *newclient(Client *c);
154 static void loaduri(Client *c, const Arg *a);
155 static const char *geturi(Client *c);
156 static void setatom(Client *c, int a, const char *v);
157 static const char *getatom(Client *c, int a);
158 static void updatetitle(Client *c);
159 static void gettogglestats(Client *c);
160 static void getpagestats(Client *c);
161 static WebKitCookieAcceptPolicy cookiepolicy_get(void);
162 static char cookiepolicy_set(const WebKitCookieAcceptPolicy p);
163 static void seturiparameters(Client *c, const char *uri);
164 static void setparameter(Client *c, int refresh, ParamName p, const Arg *a);
165 static const char *getstyle(const char *uri);
166 static void setstyle(Client *c, const char *stylefile);
167 static void runscript(Client *c);
168 static void evalscript(Client *c, const char *jsstr, ...);
169 static void updatewinid(Client *c);
170 static void handleplumb(Client *c, const char *uri);
171 static void newwindow(Client *c, const Arg *a, int noembed);
172 static void spawn(Client *c, const Arg *a);
173 static void destroyclient(Client *c);
174 static void cleanup(void);
177 static WebKitWebView *newview(Client *c, WebKitWebView *rv);
178 static void initwebextensions(WebKitWebContext *wc, Client *c);
179 static GtkWidget *createview(WebKitWebView *v, WebKitNavigationAction *a,
181 static gboolean buttonreleased(GtkWidget *w, GdkEvent *e, Client *c);
182 static GdkFilterReturn processx(GdkXEvent *xevent, GdkEvent *event,
184 static gboolean winevent(GtkWidget *w, GdkEvent *e, Client *c);
185 static void showview(WebKitWebView *v, Client *c);
186 static GtkWidget *createwindow(Client *c);
187 static void loadchanged(WebKitWebView *v, WebKitLoadEvent e, Client *c);
188 static void progresschanged(WebKitWebView *v, GParamSpec *ps, Client *c);
189 static void titlechanged(WebKitWebView *view, GParamSpec *ps, Client *c);
190 static void mousetargetchanged(WebKitWebView *v, WebKitHitTestResult *h,
191 guint modifiers, Client *c);
192 static gboolean permissionrequested(WebKitWebView *v,
193 WebKitPermissionRequest *r, Client *c);
194 static gboolean decidepolicy(WebKitWebView *v, WebKitPolicyDecision *d,
195 WebKitPolicyDecisionType dt, Client *c);
196 static void decidenavigation(WebKitPolicyDecision *d, Client *c);
197 static void decidenewwindow(WebKitPolicyDecision *d, Client *c);
198 static void decideresource(WebKitPolicyDecision *d, Client *c);
199 static void insecurecontent(WebKitWebView *v, WebKitInsecureContentEvent e,
201 static void downloadstarted(WebKitWebContext *wc, WebKitDownload *d,
203 static void responsereceived(WebKitDownload *d, GParamSpec *ps, Client *c);
204 static void download(Client *c, WebKitURIResponse *r);
205 static void closeview(WebKitWebView *v, Client *c);
206 static void destroywin(GtkWidget* w, Client *c);
209 static void pasteuri(GtkClipboard *clipboard, const char *text, gpointer d);
210 static void reload(Client *c, const Arg *a);
211 static void print(Client *c, const Arg *a);
212 static void clipboard(Client *c, const Arg *a);
213 static void zoom(Client *c, const Arg *a);
214 static void scroll(Client *c, const Arg *a);
215 static void navigate(Client *c, const Arg *a);
216 static void stop(Client *c, const Arg *a);
217 static void toggle(Client *c, const Arg *a);
218 static void togglefullscreen(Client *c, const Arg *a);
219 static void togglecookiepolicy(Client *c, const Arg *a);
220 static void toggleinspector(Client *c, const Arg *a);
221 static void find(Client *c, const Arg *a);
224 static void clicknavigate(Client *c, const Arg *a, WebKitHitTestResult *h);
225 static void clicknewwindow(Client *c, const Arg *a, WebKitHitTestResult *h);
226 static void clickexternplayer(Client *c, const Arg *a, WebKitHitTestResult *h);
228 static char winid[64];
229 static char togglestats[10];
230 static char pagestats[2];
231 static Atom atoms[AtomLast];
234 static int cookiepolicy;
236 static Client *clients;
237 static GdkDevice *gdkkb;
238 static char *stylefile;
239 static const char *useragent;
240 static Parameter *curconfig;
243 /* configuration, allows nested code to access above variables */
249 die("usage: %s [-bBdDfFgGiIkKmMnNpPsSvx] [-a cookiepolicies ] "
250 "[-c cookiefile] [-e xid] [-r scriptfile] [-t stylefile] "
251 "[-u useragent] [-z zoomlevel] [uri]\n", basename(argv0));
255 die(const char *errstr, ...)
259 va_start(ap, errstr);
260 vfprintf(stderr, errstr, ap);
271 /* clean up any zombies immediately */
273 if (signal(SIGHUP, sighup) == SIG_ERR)
274 die("Can't install SIGHUP handler");
276 if (!(dpy = XOpenDisplay(NULL)))
277 die("Can't open default display");
280 atoms[AtomFind] = XInternAtom(dpy, "_SURF_FIND", False);
281 atoms[AtomGo] = XInternAtom(dpy, "_SURF_GO", False);
282 atoms[AtomUri] = XInternAtom(dpy, "_SURF_URI", False);
284 gtk_init(NULL, NULL);
286 gdpy = gdk_display_get_default();
288 curconfig = defconfig;
291 cookiefile = buildfile(cookiefile);
292 scriptfile = buildfile(scriptfile);
293 cachedir = buildpath(cachedir);
295 gdkkb = gdk_seat_get_keyboard(gdk_display_get_default_seat(gdpy));
298 styledir = buildpath(styledir);
299 for (i = 0; i < LENGTH(styles); ++i) {
300 if (regcomp(&(styles[i].re), styles[i].regex,
303 "Could not compile regex: %s\n",
305 styles[i].regex = NULL;
307 styles[i].style = g_strconcat(styledir, "/",
308 styles[i].style, NULL);
312 stylefile = buildfile(stylefile);
315 for (i = 0; i < LENGTH(uriparams); ++i) {
316 if (!regcomp(&(uriparams[i].re), uriparams[i].uri,
318 /* copy default parameters if they are not already set
319 * or if they are forced */
320 for (j = 0; j < ParameterLast; ++j) {
321 if (!uriparams[i].config[j].force ||
323 uriparams[i].config[j] = defconfig[j];
327 "Could not compile regex: %s\n",
329 uriparams[i].uri = NULL;
337 if (signal(SIGCHLD, sigchld) == SIG_ERR)
338 die("Can't install SIGCHLD handler");
339 while (waitpid(-1, NULL, WNOHANG) > 0)
349 for (c = clients; c; c = c->next)
354 buildfile(const char *path)
356 char *dname, *bname, *bpath, *fpath;
359 dname = g_path_get_dirname(path);
360 bname = g_path_get_basename(path);
362 bpath = buildpath(dname);
365 fpath = g_build_filename(bpath, bname, NULL);
369 if (!(f = fopen(fpath, "a")))
370 die("Could not open file: %s\n", fpath);
372 g_chmod(fpath, 0600); /* always */
379 getuserhomedir(const char *user)
381 struct passwd *pw = getpwnam(user);
384 die("Can't get user %s login information.\n", user);
390 getcurrentuserhomedir(void)
396 homedir = getenv("HOME");
400 user = getenv("USER");
402 return getuserhomedir(user);
404 pw = getpwuid(getuid());
406 die("Can't get current user home directory\n");
412 buildpath(const char *path)
414 char *apath, *name, *p, *fpath;
417 if (path[0] == '~') {
418 if (path[1] == '/' || path[1] == '\0') {
419 p = (char *)&path[1];
420 homedir = getcurrentuserhomedir();
422 if ((p = strchr(path, '/')))
423 name = g_strndup(&path[1], --p - path);
425 name = g_strdup(&path[1]);
427 homedir = getuserhomedir(name);
430 apath = g_build_filename(homedir, p, NULL);
432 apath = g_strdup(path);
435 /* creating directory */
436 if (g_mkdir_with_parents(apath, 0700) < 0)
437 die("Could not access directory: %s\n", apath);
439 fpath = realpath(apath, NULL);
446 newclient(Client *rc)
450 if (!(c = calloc(1, sizeof(Client))))
451 die("Cannot malloc!\n");
457 c->view = newview(c, rc ? rc->view : NULL);
463 loaduri(Client *c, const Arg *a)
467 const char *uri = a->v;
469 if (g_strcmp0(uri, "") == 0)
472 if (g_str_has_prefix(uri, "http://") ||
473 g_str_has_prefix(uri, "https://") ||
474 g_str_has_prefix(uri, "file://") ||
475 g_str_has_prefix(uri, "about:")) {
477 } else if (!stat(uri, &st) && (path = realpath(uri, NULL))) {
478 url = g_strdup_printf("file://%s", path);
481 url = g_strdup_printf("http://%s", uri);
484 setatom(c, AtomUri, url);
486 if (strcmp(url, geturi(c)) == 0) {
489 webkit_web_view_load_uri(c->view, url);
501 if (!(uri = webkit_web_view_get_uri(c->view)))
507 setatom(Client *c, int a, const char *v)
510 XChangeProperty(dpy, c->xid,
511 atoms[a], XA_STRING, 8, PropModeReplace,
512 (unsigned char *)v, strlen(v) + 1);
516 getatom(Client *c, int a)
518 static char buf[BUFSIZ];
521 unsigned long ldummy;
522 unsigned char *p = NULL;
524 XGetWindowProperty(dpy, c->xid, atoms[a], 0L, BUFSIZ, False, XA_STRING,
525 &adummy, &idummy, &ldummy, &ldummy, &p);
527 strncpy(buf, (char *)p, LENGTH(buf) - 1);
536 updatetitle(Client *c)
539 const char *name = c->overtitle ? c->overtitle :
540 c->title ? c->title : "";
542 if (curconfig[ShowIndicators].val.b) {
546 if (c->progress != 100)
547 title = g_strdup_printf("[%i%%] %s:%s | %s",
548 c->progress, togglestats, pagestats, name);
550 title = g_strdup_printf("%s:%s | %s",
551 togglestats, pagestats, name);
553 gtk_window_set_title(GTK_WINDOW(c->win), title);
556 gtk_window_set_title(GTK_WINDOW(c->win), name);
561 gettogglestats(Client *c)
563 togglestats[0] = cookiepolicy_set(cookiepolicy_get());
564 togglestats[1] = curconfig[CaretBrowsing].val.b ? 'C' : 'c';
565 togglestats[2] = curconfig[Geolocation].val.b ? 'G' : 'g';
566 togglestats[3] = curconfig[DiskCache].val.b ? 'D' : 'd';
567 togglestats[4] = curconfig[LoadImages].val.b ? 'I' : 'i';
568 togglestats[5] = curconfig[JavaScript].val.b ? 'S' : 's';
569 togglestats[6] = curconfig[Plugins].val.b ? 'V' : 'v';
570 togglestats[7] = curconfig[Style].val.b ? 'M' : 'm';
571 togglestats[8] = curconfig[FrameFlattening].val.b ? 'F' : 'f';
572 togglestats[9] = '\0';
576 getpagestats(Client *c)
579 pagestats[0] = (c->tlserr || c->insecure) ? 'U' : 'T';
585 WebKitCookieAcceptPolicy
586 cookiepolicy_get(void)
588 switch (((char *)curconfig[CookiePolicies].val.v)[cookiepolicy]) {
590 return WEBKIT_COOKIE_POLICY_ACCEPT_NEVER;
592 return WEBKIT_COOKIE_POLICY_ACCEPT_NO_THIRD_PARTY;
593 default: /* fallthrough */
595 return WEBKIT_COOKIE_POLICY_ACCEPT_ALWAYS;
600 cookiepolicy_set(const WebKitCookieAcceptPolicy p)
603 case WEBKIT_COOKIE_POLICY_ACCEPT_NEVER:
605 case WEBKIT_COOKIE_POLICY_ACCEPT_NO_THIRD_PARTY:
607 default: /* fallthrough */
608 case WEBKIT_COOKIE_POLICY_ACCEPT_ALWAYS:
614 seturiparameters(Client *c, const char *uri)
618 for (i = 0; i < LENGTH(uriparams); ++i) {
619 if (uriparams[i].uri &&
620 !regexec(&(uriparams[i].re), uri, 0, NULL, 0)) {
621 curconfig = uriparams[i].config;
626 for (i = 0; i < ParameterLast; ++i)
627 setparameter(c, 0, i, &curconfig[i].val);
631 setparameter(Client *c, int refresh, ParamName p, const Arg *a)
633 GdkRGBA bgcolor = { 0 };
634 WebKitSettings *s = webkit_web_view_get_settings(c->view);
637 case AcceleratedCanvas:
638 webkit_settings_set_enable_accelerated_2d_canvas(s, a->b);
641 webkit_settings_set_enable_caret_browsing(s, a->b);
645 webkit_cookie_manager_set_accept_policy(
646 webkit_web_context_get_cookie_manager(
647 webkit_web_view_get_context(c->view)),
652 webkit_web_context_set_cache_model(
653 webkit_web_view_get_context(c->view), a->b ?
654 WEBKIT_CACHE_MODEL_WEB_BROWSER :
655 WEBKIT_CACHE_MODEL_DOCUMENT_VIEWER);
656 return; /* do not update */
658 webkit_settings_set_enable_dns_prefetching(s, a->b);
659 return; /* do not update */
661 webkit_settings_set_default_font_size(s, a->i);
662 return; /* do not update */
663 case FrameFlattening:
664 webkit_settings_set_enable_frame_flattening(s, a->b);
671 webkit_web_view_set_background_color(c->view, &bgcolor);
672 return; /* do not update */
674 webkit_settings_set_enable_developer_extras(s, a->b);
675 return; /* do not update */
677 webkit_settings_set_enable_javascript(s, a->b);
680 return; /* do nothing */
682 webkit_settings_set_auto_load_images(s, a->b);
684 case MediaManualPlay:
685 webkit_settings_set_media_playback_requires_user_gesture(s, a->b);
688 webkit_settings_set_enable_plugins(s, a->b);
690 case PreferredLanguages:
691 return; /* do nothing */
692 case RunInFullscreen:
693 return; /* do nothing */
695 /* Disabled until we write some WebKitWebExtension for
696 * manipulating the DOM directly.
697 enablescrollbars = !enablescrollbars;
698 evalscript(c, "document.documentElement.style.overflow = '%s'",
699 enablescrollbars ? "auto" : "hidden");
701 return; /* do not update */
705 webkit_settings_set_enable_site_specific_quirks(s, a->b);
708 webkit_web_context_set_spell_checking_enabled(
709 webkit_web_view_get_context(c->view), a->b);
710 return; /* do not update */
712 return; /* do nothing */
714 webkit_web_context_set_tls_errors_policy(
715 webkit_web_view_get_context(c->view), a->b ?
716 WEBKIT_TLS_ERRORS_POLICY_FAIL :
717 WEBKIT_TLS_ERRORS_POLICY_IGNORE);
718 return; /* do not update */
721 setstyle(c, getstyle(geturi(c)));
723 webkit_user_content_manager_remove_all_style_sheets(
724 webkit_web_view_get_user_content_manager(c->view));
728 webkit_web_view_set_zoom_level(c->view, a->f);
729 return; /* do not update */
731 return; /* do nothing */
740 getstyle(const char *uri)
747 for (i = 0; i < LENGTH(styles); ++i) {
748 if (styles[i].regex &&
749 !regexec(&(styles[i].re), uri, 0, NULL, 0))
750 return styles[i].style;
757 setstyle(Client *c, const char *stylefile)
761 if (!g_file_get_contents(stylefile, &style, NULL, NULL)) {
762 fprintf(stderr, "Could not read style file: %s\n", stylefile);
766 webkit_user_content_manager_add_style_sheet(
767 webkit_web_view_get_user_content_manager(c->view),
768 webkit_user_style_sheet_new(style,
769 WEBKIT_USER_CONTENT_INJECT_ALL_FRAMES,
770 WEBKIT_USER_STYLE_LEVEL_USER,
782 if (g_file_get_contents(scriptfile, &script, &l, NULL) && l)
783 evalscript(c, script);
788 evalscript(Client *c, const char *jsstr, ...)
794 script = g_strdup_vprintf(jsstr, ap);
797 webkit_web_view_run_javascript(c->view, script, NULL, NULL, NULL);
802 updatewinid(Client *c)
804 snprintf(winid, LENGTH(winid), "%lu", c->xid);
808 handleplumb(Client *c, const char *uri)
810 Arg a = (Arg)PLUMB(uri);
815 newwindow(Client *c, const Arg *a, int noembed)
819 const char *cmd[26], *uri;
820 const Arg arg = { .v = cmd };
824 cmd[i++] = curconfig[CookiePolicies].val.v;
825 cmd[i++] = curconfig[ScrollBars].val.b ? "-B" : "-b";
826 if (cookiefile && g_strcmp0(cookiefile, "")) {
828 cmd[i++] = cookiefile;
830 cmd[i++] = curconfig[DiskCache].val.b ? "-D" : "-d";
831 if (embed && !noembed) {
833 snprintf(tmp, LENGTH(tmp), "%lu", embed);
836 cmd[i++] = curconfig[RunInFullscreen].val.b ? "-F" : "-f" ;
837 cmd[i++] = curconfig[Geolocation].val.b ? "-G" : "-g" ;
838 cmd[i++] = curconfig[LoadImages].val.b ? "-I" : "-i" ;
839 cmd[i++] = curconfig[KioskMode].val.b ? "-K" : "-k" ;
840 cmd[i++] = curconfig[Style].val.b ? "-M" : "-m" ;
841 cmd[i++] = curconfig[Inspector].val.b ? "-N" : "-n" ;
842 cmd[i++] = curconfig[Plugins].val.b ? "-P" : "-p" ;
843 if (scriptfile && g_strcmp0(scriptfile, "")) {
845 cmd[i++] = scriptfile;
847 cmd[i++] = curconfig[JavaScript].val.b ? "-S" : "-s";
848 if (stylefile && g_strcmp0(stylefile, "")) {
850 cmd[i++] = stylefile;
852 if (fulluseragent && g_strcmp0(fulluseragent, "")) {
854 cmd[i++] = fulluseragent;
858 /* do not keep zoom level */
868 spawn(Client *c, const Arg *a)
872 close(ConnectionNumber(dpy));
874 execvp(((char **)a->v)[0], (char **)a->v);
875 fprintf(stderr, "%s: execvp %s", argv0, ((char **)a->v)[0]);
882 destroyclient(Client *c)
886 webkit_web_view_stop_loading(c->view);
887 /* Not needed, has already been called
888 gtk_widget_destroy(c->win);
891 for (p = clients; p && p->next != c; p = p->next)
904 destroyclient(clients);
913 newview(Client *c, WebKitWebView *rv)
916 WebKitSettings *settings;
917 WebKitUserContentManager *contentmanager;
918 WebKitWebContext *context;
923 webkit_web_view_new_with_related_view(rv));
925 settings = webkit_settings_new_with_settings(
926 "auto-load-images", curconfig[LoadImages].val.b,
927 "default-font-size", curconfig[FontSize].val.i,
928 "enable-caret-browsing", curconfig[CaretBrowsing].val.b,
929 "enable-developer-extras", curconfig[Inspector].val.b,
930 "enable-dns-prefetching", curconfig[DNSPrefetch].val.b,
931 "enable-frame-flattening", curconfig[FrameFlattening].val.b,
932 "enable-html5-database", curconfig[DiskCache].val.b,
933 "enable-html5-local-storage", curconfig[DiskCache].val.b,
934 "enable-javascript", curconfig[JavaScript].val.b,
935 "enable-plugins", curconfig[Plugins].val.b,
936 "enable-accelerated-2d-canvas", curconfig[AcceleratedCanvas].val.b,
937 "enable-site-specific-quirks", curconfig[SiteQuirks].val.b,
938 "media-playback-requires-user-gesture", curconfig[MediaManualPlay].val.b,
940 /* For mor interesting settings, have a look at
941 * http://webkitgtk.org/reference/webkit2gtk/stable/WebKitSettings.html */
943 if (strcmp(fulluseragent, "")) {
944 webkit_settings_set_user_agent(settings, fulluseragent);
945 } else if (surfuseragent) {
946 webkit_settings_set_user_agent_with_application_details(
947 settings, "Surf", VERSION);
949 useragent = webkit_settings_get_user_agent(settings);
951 contentmanager = webkit_user_content_manager_new();
953 context = webkit_web_context_new_with_website_data_manager(
954 webkit_website_data_manager_new(
955 "base-cache-directory", cachedir,
956 "base-data-directory", cachedir,
959 /* rendering process model, can be a shared unique one
960 * or one for each view */
961 webkit_web_context_set_process_model(context,
962 WEBKIT_PROCESS_MODEL_MULTIPLE_SECONDARY_PROCESSES);
964 webkit_web_context_set_tls_errors_policy(context,
965 curconfig[StrictSSL].val.b ? WEBKIT_TLS_ERRORS_POLICY_FAIL :
966 WEBKIT_TLS_ERRORS_POLICY_IGNORE);
968 webkit_web_context_set_cache_model(context,
969 curconfig[DiskCache].val.b ? WEBKIT_CACHE_MODEL_WEB_BROWSER :
970 WEBKIT_CACHE_MODEL_DOCUMENT_VIEWER);
972 /* Currently only works with text file to be compatible with curl */
973 webkit_cookie_manager_set_persistent_storage(
974 webkit_web_context_get_cookie_manager(context), cookiefile,
975 WEBKIT_COOKIE_PERSISTENT_STORAGE_TEXT);
977 webkit_cookie_manager_set_accept_policy(
978 webkit_web_context_get_cookie_manager(context),
981 webkit_web_context_set_preferred_languages(context,
982 curconfig[PreferredLanguages].val.v);
983 webkit_web_context_set_spell_checking_languages(context,
984 curconfig[SpellLanguages].val.v);
985 webkit_web_context_set_spell_checking_enabled(context,
986 curconfig[SpellChecking].val.b);
988 g_signal_connect(G_OBJECT(context), "download-started",
989 G_CALLBACK(downloadstarted), c);
990 g_signal_connect(G_OBJECT(context), "initialize-web-extensions",
991 G_CALLBACK(initwebextensions), c);
993 v = g_object_new(WEBKIT_TYPE_WEB_VIEW,
994 "settings", settings,
995 "user-content-manager", contentmanager,
996 "web-context", context,
1000 g_signal_connect(G_OBJECT(v), "notify::estimated-load-progress",
1001 G_CALLBACK(progresschanged), c);
1002 g_signal_connect(G_OBJECT(v), "notify::title",
1003 G_CALLBACK(titlechanged), c);
1004 g_signal_connect(G_OBJECT(v), "button-release-event",
1005 G_CALLBACK(buttonreleased), c);
1006 g_signal_connect(G_OBJECT(v), "close",
1007 G_CALLBACK(closeview), c);
1008 g_signal_connect(G_OBJECT(v), "create",
1009 G_CALLBACK(createview), c);
1010 g_signal_connect(G_OBJECT(v), "decide-policy",
1011 G_CALLBACK(decidepolicy), c);
1012 g_signal_connect(G_OBJECT(v), "insecure-content-detected",
1013 G_CALLBACK(insecurecontent), c);
1014 g_signal_connect(G_OBJECT(v), "load-changed",
1015 G_CALLBACK(loadchanged), c);
1016 g_signal_connect(G_OBJECT(v), "mouse-target-changed",
1017 G_CALLBACK(mousetargetchanged), c);
1018 g_signal_connect(G_OBJECT(v), "permission-request",
1019 G_CALLBACK(permissionrequested), c);
1020 g_signal_connect(G_OBJECT(v), "ready-to-show",
1021 G_CALLBACK(showview), c);
1027 initwebextensions(WebKitWebContext *wc, Client *c)
1029 webkit_web_context_set_web_extensions_directory(wc, WEBEXTDIR);
1033 createview(WebKitWebView *v, WebKitNavigationAction *a, Client *c)
1037 switch (webkit_navigation_action_get_navigation_type(a)) {
1038 case WEBKIT_NAVIGATION_TYPE_OTHER: /* fallthrough */
1040 * popup windows of type “other” are almost always triggered
1041 * by user gesture, so inverse the logic here
1043 /* instead of this, compare destination uri to mouse-over uri for validating window */
1044 if (webkit_navigation_action_is_user_gesture(a))
1046 case WEBKIT_NAVIGATION_TYPE_LINK_CLICKED: /* fallthrough */
1047 case WEBKIT_NAVIGATION_TYPE_FORM_SUBMITTED: /* fallthrough */
1048 case WEBKIT_NAVIGATION_TYPE_BACK_FORWARD: /* fallthrough */
1049 case WEBKIT_NAVIGATION_TYPE_RELOAD: /* fallthrough */
1050 case WEBKIT_NAVIGATION_TYPE_FORM_RESUBMITTED:
1057 return GTK_WIDGET(n->view);
1061 buttonreleased(GtkWidget *w, GdkEvent *e, Client *c)
1063 WebKitHitTestResultContext element;
1066 element = webkit_hit_test_result_get_context(c->mousepos);
1068 for (i = 0; i < LENGTH(buttons); ++i) {
1069 if (element & buttons[i].target &&
1070 e->button.button == buttons[i].button &&
1071 CLEANMASK(e->button.state) == CLEANMASK(buttons[i].mask) &&
1073 buttons[i].func(c, &buttons[i].arg, c->mousepos);
1074 return buttons[i].stopevent;
1082 processx(GdkXEvent *e, GdkEvent *event, gpointer d)
1084 Client *c = (Client *)d;
1088 if (((XEvent *)e)->type == PropertyNotify) {
1089 ev = &((XEvent *)e)->xproperty;
1090 if (ev->state == PropertyNewValue) {
1091 if (ev->atom == atoms[AtomFind]) {
1094 return GDK_FILTER_REMOVE;
1095 } else if (ev->atom == atoms[AtomGo]) {
1096 a.v = getatom(c, AtomGo);
1099 return GDK_FILTER_REMOVE;
1103 return GDK_FILTER_CONTINUE;
1107 winevent(GtkWidget *w, GdkEvent *e, Client *c)
1112 case GDK_ENTER_NOTIFY:
1113 c->overtitle = c->targeturi;
1117 if (!curconfig[KioskMode].val.b) {
1118 for (i = 0; i < LENGTH(keys); ++i) {
1119 if (gdk_keyval_to_lower(e->key.keyval) ==
1121 CLEANMASK(e->key.state) == keys[i].mod &&
1124 keys[i].func(c, &(keys[i].arg));
1129 case GDK_LEAVE_NOTIFY:
1130 c->overtitle = NULL;
1133 case GDK_WINDOW_STATE:
1134 if (e->window_state.changed_mask ==
1135 GDK_WINDOW_STATE_FULLSCREEN)
1136 c->fullscreen = e->window_state.new_window_state &
1137 GDK_WINDOW_STATE_FULLSCREEN;
1147 showview(WebKitWebView *v, Client *c)
1149 GdkRGBA bgcolor = { 0 };
1152 c->finder = webkit_web_view_get_find_controller(c->view);
1153 c->inspector = webkit_web_view_get_inspector(c->view);
1155 c->win = createwindow(c);
1157 gtk_container_add(GTK_CONTAINER(c->win), GTK_WIDGET(c->view));
1158 gtk_widget_show_all(c->win);
1159 gtk_widget_grab_focus(GTK_WIDGET(c->view));
1161 gwin = gtk_widget_get_window(GTK_WIDGET(c->win));
1162 c->xid = gdk_x11_window_get_xid(gwin);
1165 gdk_display_sync(gtk_widget_get_display(c->win));
1169 if (curconfig[HideBackground].val.b)
1170 webkit_web_view_set_background_color(c->view, &bgcolor);
1172 if (!curconfig[KioskMode].val.b) {
1173 gdk_window_set_events(gwin, GDK_ALL_EVENTS_MASK);
1174 gdk_window_add_filter(gwin, processx, c);
1177 if (curconfig[RunInFullscreen].val.b)
1178 togglefullscreen(c, NULL);
1180 if (curconfig[ZoomLevel].val.f != 1.0)
1181 webkit_web_view_set_zoom_level(c->view,
1182 curconfig[ZoomLevel].val.f);
1184 setatom(c, AtomFind, "");
1185 setatom(c, AtomUri, "about:blank");
1189 createwindow(Client *c)
1195 w = gtk_plug_new(embed);
1197 w = gtk_window_new(GTK_WINDOW_TOPLEVEL);
1199 wmstr = g_path_get_basename(argv0);
1200 gtk_window_set_wmclass(GTK_WINDOW(w), wmstr, "Surf");
1203 wmstr = g_strdup_printf("%s[%lu]", "Surf",
1204 webkit_web_view_get_page_id(c->view));
1205 gtk_window_set_role(GTK_WINDOW(w), wmstr);
1208 gtk_window_set_default_size(GTK_WINDOW(w), winsize[0], winsize[1]);
1211 g_signal_connect(G_OBJECT(w), "destroy",
1212 G_CALLBACK(destroywin), c);
1213 g_signal_connect(G_OBJECT(w), "enter-notify-event",
1214 G_CALLBACK(winevent), c);
1215 g_signal_connect(G_OBJECT(w), "key-press-event",
1216 G_CALLBACK(winevent), c);
1217 g_signal_connect(G_OBJECT(w), "leave-notify-event",
1218 G_CALLBACK(winevent), c);
1219 g_signal_connect(G_OBJECT(w), "window-state-event",
1220 G_CALLBACK(winevent), c);
1226 loadchanged(WebKitWebView *v, WebKitLoadEvent e, Client *c)
1228 const char *title = geturi(c);
1231 case WEBKIT_LOAD_STARTED:
1232 curconfig = defconfig;
1233 setatom(c, AtomUri, title);
1235 c->https = c->insecure = 0;
1236 seturiparameters(c, geturi(c));
1238 case WEBKIT_LOAD_REDIRECTED:
1239 setatom(c, AtomUri, title);
1241 seturiparameters(c, geturi(c));
1243 case WEBKIT_LOAD_COMMITTED:
1244 c->https = webkit_web_view_get_tls_info(c->view, NULL,
1247 case WEBKIT_LOAD_FINISHED:
1248 /* Disabled until we write some WebKitWebExtension for
1249 * manipulating the DOM directly.
1250 evalscript(c, "document.documentElement.style.overflow = '%s'",
1251 enablescrollbars ? "auto" : "hidden");
1260 progresschanged(WebKitWebView *v, GParamSpec *ps, Client *c)
1262 c->progress = webkit_web_view_get_estimated_load_progress(c->view) *
1268 titlechanged(WebKitWebView *view, GParamSpec *ps, Client *c)
1270 c->title = webkit_web_view_get_title(c->view);
1275 mousetargetchanged(WebKitWebView *v, WebKitHitTestResult *h, guint modifiers,
1278 WebKitHitTestResultContext hc = webkit_hit_test_result_get_context(h);
1280 /* Keep the hit test to know where is the pointer on the next click */
1284 c->targeturi = webkit_hit_test_result_get_link_uri(h);
1285 else if (hc & OnImg)
1286 c->targeturi = webkit_hit_test_result_get_image_uri(h);
1287 else if (hc & OnMedia)
1288 c->targeturi = webkit_hit_test_result_get_media_uri(h);
1290 c->targeturi = NULL;
1292 c->overtitle = c->targeturi;
1297 permissionrequested(WebKitWebView *v, WebKitPermissionRequest *r, Client *c)
1299 if (WEBKIT_IS_GEOLOCATION_PERMISSION_REQUEST(r)) {
1300 if (curconfig[Geolocation].val.b)
1301 webkit_permission_request_allow(r);
1303 webkit_permission_request_deny(r);
1311 decidepolicy(WebKitWebView *v, WebKitPolicyDecision *d,
1312 WebKitPolicyDecisionType dt, Client *c)
1315 case WEBKIT_POLICY_DECISION_TYPE_NAVIGATION_ACTION:
1316 decidenavigation(d, c);
1318 case WEBKIT_POLICY_DECISION_TYPE_NEW_WINDOW_ACTION:
1319 decidenewwindow(d, c);
1321 case WEBKIT_POLICY_DECISION_TYPE_RESPONSE:
1322 decideresource(d, c);
1325 webkit_policy_decision_ignore(d);
1332 decidenavigation(WebKitPolicyDecision *d, Client *c)
1334 WebKitNavigationAction *a =
1335 webkit_navigation_policy_decision_get_navigation_action(
1336 WEBKIT_NAVIGATION_POLICY_DECISION(d));
1338 switch (webkit_navigation_action_get_navigation_type(a)) {
1339 case WEBKIT_NAVIGATION_TYPE_LINK_CLICKED: /* fallthrough */
1340 case WEBKIT_NAVIGATION_TYPE_FORM_SUBMITTED: /* fallthrough */
1341 case WEBKIT_NAVIGATION_TYPE_BACK_FORWARD: /* fallthrough */
1342 case WEBKIT_NAVIGATION_TYPE_RELOAD: /* fallthrough */
1343 case WEBKIT_NAVIGATION_TYPE_FORM_RESUBMITTED: /* fallthrough */
1344 case WEBKIT_NAVIGATION_TYPE_OTHER: /* fallthrough */
1346 /* Do not navigate to links with a "_blank" target (popup) */
1347 if (webkit_navigation_policy_decision_get_frame_name(
1348 WEBKIT_NAVIGATION_POLICY_DECISION(d))) {
1349 webkit_policy_decision_ignore(d);
1351 /* Filter out navigation to different domain ? */
1352 /* get action→urirequest, copy and load in new window+view
1353 * on Ctrl+Click ? */
1354 webkit_policy_decision_use(d);
1361 decidenewwindow(WebKitPolicyDecision *d, Client *c)
1364 WebKitNavigationAction *a =
1365 webkit_navigation_policy_decision_get_navigation_action(
1366 WEBKIT_NAVIGATION_POLICY_DECISION(d));
1369 switch (webkit_navigation_action_get_navigation_type(a)) {
1370 case WEBKIT_NAVIGATION_TYPE_LINK_CLICKED: /* fallthrough */
1371 case WEBKIT_NAVIGATION_TYPE_FORM_SUBMITTED: /* fallthrough */
1372 case WEBKIT_NAVIGATION_TYPE_BACK_FORWARD: /* fallthrough */
1373 case WEBKIT_NAVIGATION_TYPE_RELOAD: /* fallthrough */
1374 case WEBKIT_NAVIGATION_TYPE_FORM_RESUBMITTED:
1375 /* Filter domains here */
1376 /* If the value of “mouse-button” is not 0, then the navigation was triggered by a mouse event.
1377 * test for link clicked but no button ? */
1378 arg.v = webkit_uri_request_get_uri(
1379 webkit_navigation_action_get_request(a));
1380 newwindow(c, &arg, 0);
1382 case WEBKIT_NAVIGATION_TYPE_OTHER: /* fallthrough */
1387 webkit_policy_decision_ignore(d);
1391 decideresource(WebKitPolicyDecision *d, Client *c)
1394 WebKitResponsePolicyDecision *r = WEBKIT_RESPONSE_POLICY_DECISION(d);
1395 WebKitURIResponse *res =
1396 webkit_response_policy_decision_get_response(r);
1397 const gchar *uri = webkit_uri_response_get_uri(res);
1399 if (g_str_has_suffix(uri, "/favicon.ico")) {
1400 webkit_policy_decision_ignore(d);
1404 if (!g_str_has_prefix(uri, "http://")
1405 && !g_str_has_prefix(uri, "https://")
1406 && !g_str_has_prefix(uri, "about:")
1407 && !g_str_has_prefix(uri, "file://")
1408 && !g_str_has_prefix(uri, "data:")
1409 && !g_str_has_prefix(uri, "blob:")
1410 && strlen(uri) > 0) {
1411 for (i = 0; i < strlen(uri); i++) {
1412 if (!g_ascii_isprint(uri[i])) {
1418 handleplumb(c, uri);
1419 webkit_policy_decision_ignore(d);
1424 if (webkit_response_policy_decision_is_mime_type_supported(r)) {
1425 webkit_policy_decision_use(d);
1427 webkit_policy_decision_ignore(d);
1433 insecurecontent(WebKitWebView *v, WebKitInsecureContentEvent e, Client *c)
1439 downloadstarted(WebKitWebContext *wc, WebKitDownload *d, Client *c)
1441 g_signal_connect(G_OBJECT(d), "notify::response",
1442 G_CALLBACK(responsereceived), c);
1446 responsereceived(WebKitDownload *d, GParamSpec *ps, Client *c)
1448 download(c, webkit_download_get_response(d));
1449 webkit_download_cancel(d);
1453 download(Client *c, WebKitURIResponse *r)
1455 Arg a = (Arg)DOWNLOAD(webkit_uri_response_get_uri(r), geturi(c));
1460 closeview(WebKitWebView *v, Client *c)
1462 gtk_widget_destroy(c->win);
1466 destroywin(GtkWidget* w, Client *c)
1474 pasteuri(GtkClipboard *clipboard, const char *text, gpointer d)
1476 Arg a = {.v = text };
1478 loaduri((Client *) d, &a);
1482 reload(Client *c, const Arg *a)
1485 webkit_web_view_reload_bypass_cache(c->view);
1487 webkit_web_view_reload(c->view);
1491 print(Client *c, const Arg *a)
1493 webkit_print_operation_run_dialog(webkit_print_operation_new(c->view),
1494 GTK_WINDOW(c->win));
1498 clipboard(Client *c, const Arg *a)
1500 if (a->b) { /* load clipboard uri */
1501 gtk_clipboard_request_text(gtk_clipboard_get(
1502 GDK_SELECTION_PRIMARY),
1504 } else { /* copy uri */
1505 gtk_clipboard_set_text(gtk_clipboard_get(
1506 GDK_SELECTION_PRIMARY), c->targeturi
1507 ? c->targeturi : geturi(c), -1);
1512 zoom(Client *c, const Arg *a)
1515 webkit_web_view_set_zoom_level(c->view,
1516 curconfig[ZoomLevel].val.f + 0.1);
1518 webkit_web_view_set_zoom_level(c->view,
1519 curconfig[ZoomLevel].val.f - 0.1);
1521 webkit_web_view_set_zoom_level(c->view, 1.0);
1523 curconfig[ZoomLevel].val.f = webkit_web_view_get_zoom_level(c->view);
1527 scroll(Client *c, const Arg *a)
1529 GdkEvent *ev = gdk_event_new(GDK_KEY_PRESS);
1531 gdk_event_set_device(ev, gdkkb);
1532 ev->key.window = gtk_widget_get_window(GTK_WIDGET(c->win));
1533 ev->key.state = GDK_CONTROL_MASK;
1534 ev->key.time = GDK_CURRENT_TIME;
1538 ev->key.keyval = GDK_KEY_Down;
1541 ev->key.keyval = GDK_KEY_Page_Down;
1544 ev->key.keyval = GDK_KEY_Left;
1547 ev->key.keyval = GDK_KEY_Right;
1550 ev->key.keyval = GDK_KEY_Page_Up;
1553 ev->key.keyval = GDK_KEY_Up;
1561 navigate(Client *c, const Arg *a)
1564 webkit_web_view_go_back(c->view);
1566 webkit_web_view_go_forward(c->view);
1570 stop(Client *c, const Arg *a)
1572 webkit_web_view_stop_loading(c->view);
1576 toggle(Client *c, const Arg *a)
1578 curconfig[a->i].val.b ^= 1;
1579 setparameter(c, 1, (ParamName)a->i, &curconfig[a->i].val);
1583 togglefullscreen(Client *c, const Arg *a)
1585 /* toggling value is handled in winevent() */
1587 gtk_window_unfullscreen(GTK_WINDOW(c->win));
1589 gtk_window_fullscreen(GTK_WINDOW(c->win));
1593 togglecookiepolicy(Client *c, const Arg *a)
1596 cookiepolicy %= strlen(curconfig[CookiePolicies].val.v);
1598 setparameter(c, 0, CookiePolicies, NULL);
1602 toggleinspector(Client *c, const Arg *a)
1604 if (webkit_web_inspector_is_attached(c->inspector))
1605 webkit_web_inspector_close(c->inspector);
1606 else if (curconfig[Inspector].val.b)
1607 webkit_web_inspector_show(c->inspector);
1611 find(Client *c, const Arg *a)
1617 webkit_find_controller_search_next(c->finder);
1619 webkit_find_controller_search_previous(c->finder);
1621 s = getatom(c, AtomFind);
1622 f = webkit_find_controller_get_search_text(c->finder);
1624 if (g_strcmp0(f, s) == 0) /* reset search */
1625 webkit_find_controller_search(c->finder, "", findopts,
1628 webkit_find_controller_search(c->finder, s, findopts,
1631 if (strcmp(s, "") == 0)
1632 webkit_find_controller_search_finish(c->finder);
1637 clicknavigate(Client *c, const Arg *a, WebKitHitTestResult *h)
1643 clicknewwindow(Client *c, const Arg *a, WebKitHitTestResult *h)
1647 arg.v = webkit_hit_test_result_get_link_uri(h);
1648 newwindow(c, &arg, a->b);
1652 clickexternplayer(Client *c, const Arg *a, WebKitHitTestResult *h)
1656 arg = (Arg)VIDEOPLAY(webkit_hit_test_result_get_media_uri(h));
1661 main(int argc, char *argv[])
1666 memset(&arg, 0, sizeof(arg));
1668 /* command line args */
1671 defconfig CSETV(CookiePolicies, EARGF(usage()));
1674 defconfig CSETB(ScrollBars, 0);
1677 defconfig CSETB(ScrollBars, 1);
1680 cookiefile = EARGF(usage());
1683 defconfig CSETB(DiskCache, 0);
1686 defconfig CSETB(DiskCache, 1);
1689 embed = strtol(EARGF(usage()), NULL, 0);
1692 defconfig CSETB(RunInFullscreen, 0);
1695 defconfig CSETB(RunInFullscreen, 1);
1698 defconfig CSETB(Geolocation, 0);
1701 defconfig CSETB(Geolocation, 1);
1704 defconfig CSETB(LoadImages, 0);
1707 defconfig CSETB(LoadImages, 1);
1710 defconfig CSETB(KioskMode, 0);
1713 defconfig CSETB(KioskMode, 1);
1716 defconfig CSETB(Style, 0);
1719 defconfig CSETB(Style, 1);
1722 defconfig CSETB(Inspector, 0);
1725 defconfig CSETB(Inspector, 1);
1728 defconfig CSETB(Plugins, 0);
1731 defconfig CSETB(Plugins, 1);
1734 scriptfile = EARGF(usage());
1737 defconfig CSETB(JavaScript, 0);
1740 defconfig CSETB(JavaScript, 1);
1743 stylefile = EARGF(usage());
1746 fulluseragent = EARGF(usage());
1749 die("surf-"VERSION", ©2009-2015 surf engineers, "
1750 "see LICENSE for details\n");
1755 defconfig CSETF(ZoomLevel, strtof(EARGF(usage()), NULL));
1763 arg.v = "about:blank";
1766 c = newclient(NULL);