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[11];
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] [-C stylefile] [-e xid] [-r scriptfile] "
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] = curconfig[StrictTLS].val.b ? 'T' : 't';
573 togglestats[10] = '\0';
577 getpagestats(Client *c)
580 pagestats[0] = (c->tlserr || c->insecure) ? 'U' : 'T';
586 WebKitCookieAcceptPolicy
587 cookiepolicy_get(void)
589 switch (((char *)curconfig[CookiePolicies].val.v)[cookiepolicy]) {
591 return WEBKIT_COOKIE_POLICY_ACCEPT_NEVER;
593 return WEBKIT_COOKIE_POLICY_ACCEPT_NO_THIRD_PARTY;
594 default: /* fallthrough */
596 return WEBKIT_COOKIE_POLICY_ACCEPT_ALWAYS;
601 cookiepolicy_set(const WebKitCookieAcceptPolicy p)
604 case WEBKIT_COOKIE_POLICY_ACCEPT_NEVER:
606 case WEBKIT_COOKIE_POLICY_ACCEPT_NO_THIRD_PARTY:
608 default: /* fallthrough */
609 case WEBKIT_COOKIE_POLICY_ACCEPT_ALWAYS:
615 seturiparameters(Client *c, const char *uri)
619 for (i = 0; i < LENGTH(uriparams); ++i) {
620 if (uriparams[i].uri &&
621 !regexec(&(uriparams[i].re), uri, 0, NULL, 0)) {
622 curconfig = uriparams[i].config;
627 for (i = 0; i < ParameterLast; ++i)
628 setparameter(c, 0, i, &curconfig[i].val);
632 setparameter(Client *c, int refresh, ParamName p, const Arg *a)
634 GdkRGBA bgcolor = { 0 };
635 WebKitSettings *s = webkit_web_view_get_settings(c->view);
638 case AcceleratedCanvas:
639 webkit_settings_set_enable_accelerated_2d_canvas(s, a->b);
642 webkit_settings_set_enable_caret_browsing(s, a->b);
646 webkit_cookie_manager_set_accept_policy(
647 webkit_web_context_get_cookie_manager(
648 webkit_web_view_get_context(c->view)),
653 webkit_web_context_set_cache_model(
654 webkit_web_view_get_context(c->view), a->b ?
655 WEBKIT_CACHE_MODEL_WEB_BROWSER :
656 WEBKIT_CACHE_MODEL_DOCUMENT_VIEWER);
657 return; /* do not update */
659 webkit_settings_set_enable_dns_prefetching(s, a->b);
660 return; /* do not update */
662 webkit_settings_set_default_font_size(s, a->i);
663 return; /* do not update */
664 case FrameFlattening:
665 webkit_settings_set_enable_frame_flattening(s, a->b);
672 webkit_web_view_set_background_color(c->view, &bgcolor);
673 return; /* do not update */
675 webkit_settings_set_enable_developer_extras(s, a->b);
676 return; /* do not update */
678 webkit_settings_set_enable_javascript(s, a->b);
681 return; /* do nothing */
683 webkit_settings_set_auto_load_images(s, a->b);
685 case MediaManualPlay:
686 webkit_settings_set_media_playback_requires_user_gesture(s, a->b);
689 webkit_settings_set_enable_plugins(s, a->b);
691 case PreferredLanguages:
692 return; /* do nothing */
693 case RunInFullscreen:
694 return; /* do nothing */
696 /* Disabled until we write some WebKitWebExtension for
697 * manipulating the DOM directly.
698 enablescrollbars = !enablescrollbars;
699 evalscript(c, "document.documentElement.style.overflow = '%s'",
700 enablescrollbars ? "auto" : "hidden");
702 return; /* do not update */
706 webkit_settings_set_enable_site_specific_quirks(s, a->b);
709 webkit_web_context_set_spell_checking_enabled(
710 webkit_web_view_get_context(c->view), a->b);
711 return; /* do not update */
713 return; /* do nothing */
715 webkit_web_context_set_tls_errors_policy(
716 webkit_web_view_get_context(c->view), a->b ?
717 WEBKIT_TLS_ERRORS_POLICY_FAIL :
718 WEBKIT_TLS_ERRORS_POLICY_IGNORE);
722 setstyle(c, getstyle(geturi(c)));
724 webkit_user_content_manager_remove_all_style_sheets(
725 webkit_web_view_get_user_content_manager(c->view));
729 webkit_web_view_set_zoom_level(c->view, a->f);
730 return; /* do not update */
732 return; /* do nothing */
741 getstyle(const char *uri)
748 for (i = 0; i < LENGTH(styles); ++i) {
749 if (styles[i].regex &&
750 !regexec(&(styles[i].re), uri, 0, NULL, 0))
751 return styles[i].style;
758 setstyle(Client *c, const char *stylefile)
762 if (!g_file_get_contents(stylefile, &style, NULL, NULL)) {
763 fprintf(stderr, "Could not read style file: %s\n", stylefile);
767 webkit_user_content_manager_add_style_sheet(
768 webkit_web_view_get_user_content_manager(c->view),
769 webkit_user_style_sheet_new(style,
770 WEBKIT_USER_CONTENT_INJECT_ALL_FRAMES,
771 WEBKIT_USER_STYLE_LEVEL_USER,
783 if (g_file_get_contents(scriptfile, &script, &l, NULL) && l)
784 evalscript(c, script);
789 evalscript(Client *c, const char *jsstr, ...)
795 script = g_strdup_vprintf(jsstr, ap);
798 webkit_web_view_run_javascript(c->view, script, NULL, NULL, NULL);
803 updatewinid(Client *c)
805 snprintf(winid, LENGTH(winid), "%lu", c->xid);
809 handleplumb(Client *c, const char *uri)
811 Arg a = (Arg)PLUMB(uri);
816 newwindow(Client *c, const Arg *a, int noembed)
820 const char *cmd[27], *uri;
821 const Arg arg = { .v = cmd };
825 cmd[i++] = curconfig[CookiePolicies].val.v;
826 cmd[i++] = curconfig[ScrollBars].val.b ? "-B" : "-b";
827 if (cookiefile && g_strcmp0(cookiefile, "")) {
829 cmd[i++] = cookiefile;
831 if (stylefile && g_strcmp0(stylefile, "")) {
833 cmd[i++] = stylefile;
835 cmd[i++] = curconfig[DiskCache].val.b ? "-D" : "-d";
836 if (embed && !noembed) {
838 snprintf(tmp, LENGTH(tmp), "%lu", embed);
841 cmd[i++] = curconfig[RunInFullscreen].val.b ? "-F" : "-f" ;
842 cmd[i++] = curconfig[Geolocation].val.b ? "-G" : "-g" ;
843 cmd[i++] = curconfig[LoadImages].val.b ? "-I" : "-i" ;
844 cmd[i++] = curconfig[KioskMode].val.b ? "-K" : "-k" ;
845 cmd[i++] = curconfig[Style].val.b ? "-M" : "-m" ;
846 cmd[i++] = curconfig[Inspector].val.b ? "-N" : "-n" ;
847 cmd[i++] = curconfig[Plugins].val.b ? "-P" : "-p" ;
848 if (scriptfile && g_strcmp0(scriptfile, "")) {
850 cmd[i++] = scriptfile;
852 cmd[i++] = curconfig[JavaScript].val.b ? "-S" : "-s";
853 if (fulluseragent && g_strcmp0(fulluseragent, "")) {
855 cmd[i++] = fulluseragent;
859 /* do not keep zoom level */
869 spawn(Client *c, const Arg *a)
873 close(ConnectionNumber(dpy));
875 execvp(((char **)a->v)[0], (char **)a->v);
876 fprintf(stderr, "%s: execvp %s", argv0, ((char **)a->v)[0]);
883 destroyclient(Client *c)
887 webkit_web_view_stop_loading(c->view);
888 /* Not needed, has already been called
889 gtk_widget_destroy(c->win);
892 for (p = clients; p && p->next != c; p = p->next)
905 destroyclient(clients);
914 newview(Client *c, WebKitWebView *rv)
917 WebKitSettings *settings;
918 WebKitUserContentManager *contentmanager;
919 WebKitWebContext *context;
924 webkit_web_view_new_with_related_view(rv));
926 settings = webkit_settings_new_with_settings(
927 "auto-load-images", curconfig[LoadImages].val.b,
928 "default-font-size", curconfig[FontSize].val.i,
929 "enable-caret-browsing", curconfig[CaretBrowsing].val.b,
930 "enable-developer-extras", curconfig[Inspector].val.b,
931 "enable-dns-prefetching", curconfig[DNSPrefetch].val.b,
932 "enable-frame-flattening", curconfig[FrameFlattening].val.b,
933 "enable-html5-database", curconfig[DiskCache].val.b,
934 "enable-html5-local-storage", curconfig[DiskCache].val.b,
935 "enable-javascript", curconfig[JavaScript].val.b,
936 "enable-plugins", curconfig[Plugins].val.b,
937 "enable-accelerated-2d-canvas", curconfig[AcceleratedCanvas].val.b,
938 "enable-site-specific-quirks", curconfig[SiteQuirks].val.b,
939 "media-playback-requires-user-gesture", curconfig[MediaManualPlay].val.b,
941 /* For mor interesting settings, have a look at
942 * http://webkitgtk.org/reference/webkit2gtk/stable/WebKitSettings.html */
944 if (strcmp(fulluseragent, "")) {
945 webkit_settings_set_user_agent(settings, fulluseragent);
946 } else if (surfuseragent) {
947 webkit_settings_set_user_agent_with_application_details(
948 settings, "Surf", VERSION);
950 useragent = webkit_settings_get_user_agent(settings);
952 contentmanager = webkit_user_content_manager_new();
954 context = webkit_web_context_new_with_website_data_manager(
955 webkit_website_data_manager_new(
956 "base-cache-directory", cachedir,
957 "base-data-directory", cachedir,
960 /* rendering process model, can be a shared unique one
961 * or one for each view */
962 webkit_web_context_set_process_model(context,
963 WEBKIT_PROCESS_MODEL_MULTIPLE_SECONDARY_PROCESSES);
965 webkit_web_context_set_tls_errors_policy(context,
966 curconfig[StrictTLS].val.b ? WEBKIT_TLS_ERRORS_POLICY_FAIL :
967 WEBKIT_TLS_ERRORS_POLICY_IGNORE);
969 webkit_web_context_set_cache_model(context,
970 curconfig[DiskCache].val.b ? WEBKIT_CACHE_MODEL_WEB_BROWSER :
971 WEBKIT_CACHE_MODEL_DOCUMENT_VIEWER);
973 /* Currently only works with text file to be compatible with curl */
974 webkit_cookie_manager_set_persistent_storage(
975 webkit_web_context_get_cookie_manager(context), cookiefile,
976 WEBKIT_COOKIE_PERSISTENT_STORAGE_TEXT);
978 webkit_cookie_manager_set_accept_policy(
979 webkit_web_context_get_cookie_manager(context),
982 webkit_web_context_set_preferred_languages(context,
983 curconfig[PreferredLanguages].val.v);
984 webkit_web_context_set_spell_checking_languages(context,
985 curconfig[SpellLanguages].val.v);
986 webkit_web_context_set_spell_checking_enabled(context,
987 curconfig[SpellChecking].val.b);
989 g_signal_connect(G_OBJECT(context), "download-started",
990 G_CALLBACK(downloadstarted), c);
991 g_signal_connect(G_OBJECT(context), "initialize-web-extensions",
992 G_CALLBACK(initwebextensions), c);
994 v = g_object_new(WEBKIT_TYPE_WEB_VIEW,
995 "settings", settings,
996 "user-content-manager", contentmanager,
997 "web-context", context,
1001 g_signal_connect(G_OBJECT(v), "notify::estimated-load-progress",
1002 G_CALLBACK(progresschanged), c);
1003 g_signal_connect(G_OBJECT(v), "notify::title",
1004 G_CALLBACK(titlechanged), c);
1005 g_signal_connect(G_OBJECT(v), "button-release-event",
1006 G_CALLBACK(buttonreleased), c);
1007 g_signal_connect(G_OBJECT(v), "close",
1008 G_CALLBACK(closeview), c);
1009 g_signal_connect(G_OBJECT(v), "create",
1010 G_CALLBACK(createview), c);
1011 g_signal_connect(G_OBJECT(v), "decide-policy",
1012 G_CALLBACK(decidepolicy), c);
1013 g_signal_connect(G_OBJECT(v), "insecure-content-detected",
1014 G_CALLBACK(insecurecontent), c);
1015 g_signal_connect(G_OBJECT(v), "load-changed",
1016 G_CALLBACK(loadchanged), c);
1017 g_signal_connect(G_OBJECT(v), "mouse-target-changed",
1018 G_CALLBACK(mousetargetchanged), c);
1019 g_signal_connect(G_OBJECT(v), "permission-request",
1020 G_CALLBACK(permissionrequested), c);
1021 g_signal_connect(G_OBJECT(v), "ready-to-show",
1022 G_CALLBACK(showview), c);
1028 initwebextensions(WebKitWebContext *wc, Client *c)
1030 webkit_web_context_set_web_extensions_directory(wc, WEBEXTDIR);
1034 createview(WebKitWebView *v, WebKitNavigationAction *a, Client *c)
1038 switch (webkit_navigation_action_get_navigation_type(a)) {
1039 case WEBKIT_NAVIGATION_TYPE_OTHER: /* fallthrough */
1041 * popup windows of type “other” are almost always triggered
1042 * by user gesture, so inverse the logic here
1044 /* instead of this, compare destination uri to mouse-over uri for validating window */
1045 if (webkit_navigation_action_is_user_gesture(a))
1047 case WEBKIT_NAVIGATION_TYPE_LINK_CLICKED: /* fallthrough */
1048 case WEBKIT_NAVIGATION_TYPE_FORM_SUBMITTED: /* fallthrough */
1049 case WEBKIT_NAVIGATION_TYPE_BACK_FORWARD: /* fallthrough */
1050 case WEBKIT_NAVIGATION_TYPE_RELOAD: /* fallthrough */
1051 case WEBKIT_NAVIGATION_TYPE_FORM_RESUBMITTED:
1058 return GTK_WIDGET(n->view);
1062 buttonreleased(GtkWidget *w, GdkEvent *e, Client *c)
1064 WebKitHitTestResultContext element;
1067 element = webkit_hit_test_result_get_context(c->mousepos);
1069 for (i = 0; i < LENGTH(buttons); ++i) {
1070 if (element & buttons[i].target &&
1071 e->button.button == buttons[i].button &&
1072 CLEANMASK(e->button.state) == CLEANMASK(buttons[i].mask) &&
1074 buttons[i].func(c, &buttons[i].arg, c->mousepos);
1075 return buttons[i].stopevent;
1083 processx(GdkXEvent *e, GdkEvent *event, gpointer d)
1085 Client *c = (Client *)d;
1089 if (((XEvent *)e)->type == PropertyNotify) {
1090 ev = &((XEvent *)e)->xproperty;
1091 if (ev->state == PropertyNewValue) {
1092 if (ev->atom == atoms[AtomFind]) {
1095 return GDK_FILTER_REMOVE;
1096 } else if (ev->atom == atoms[AtomGo]) {
1097 a.v = getatom(c, AtomGo);
1100 return GDK_FILTER_REMOVE;
1104 return GDK_FILTER_CONTINUE;
1108 winevent(GtkWidget *w, GdkEvent *e, Client *c)
1113 case GDK_ENTER_NOTIFY:
1114 c->overtitle = c->targeturi;
1118 if (!curconfig[KioskMode].val.b) {
1119 for (i = 0; i < LENGTH(keys); ++i) {
1120 if (gdk_keyval_to_lower(e->key.keyval) ==
1122 CLEANMASK(e->key.state) == keys[i].mod &&
1125 keys[i].func(c, &(keys[i].arg));
1130 case GDK_LEAVE_NOTIFY:
1131 c->overtitle = NULL;
1134 case GDK_WINDOW_STATE:
1135 if (e->window_state.changed_mask ==
1136 GDK_WINDOW_STATE_FULLSCREEN)
1137 c->fullscreen = e->window_state.new_window_state &
1138 GDK_WINDOW_STATE_FULLSCREEN;
1148 showview(WebKitWebView *v, Client *c)
1150 GdkRGBA bgcolor = { 0 };
1153 c->finder = webkit_web_view_get_find_controller(c->view);
1154 c->inspector = webkit_web_view_get_inspector(c->view);
1156 c->win = createwindow(c);
1158 gtk_container_add(GTK_CONTAINER(c->win), GTK_WIDGET(c->view));
1159 gtk_widget_show_all(c->win);
1160 gtk_widget_grab_focus(GTK_WIDGET(c->view));
1162 gwin = gtk_widget_get_window(GTK_WIDGET(c->win));
1163 c->xid = gdk_x11_window_get_xid(gwin);
1166 gdk_display_sync(gtk_widget_get_display(c->win));
1170 if (curconfig[HideBackground].val.b)
1171 webkit_web_view_set_background_color(c->view, &bgcolor);
1173 if (!curconfig[KioskMode].val.b) {
1174 gdk_window_set_events(gwin, GDK_ALL_EVENTS_MASK);
1175 gdk_window_add_filter(gwin, processx, c);
1178 if (curconfig[RunInFullscreen].val.b)
1179 togglefullscreen(c, NULL);
1181 if (curconfig[ZoomLevel].val.f != 1.0)
1182 webkit_web_view_set_zoom_level(c->view,
1183 curconfig[ZoomLevel].val.f);
1185 setatom(c, AtomFind, "");
1186 setatom(c, AtomUri, "about:blank");
1190 createwindow(Client *c)
1196 w = gtk_plug_new(embed);
1198 w = gtk_window_new(GTK_WINDOW_TOPLEVEL);
1200 wmstr = g_path_get_basename(argv0);
1201 gtk_window_set_wmclass(GTK_WINDOW(w), wmstr, "Surf");
1204 wmstr = g_strdup_printf("%s[%lu]", "Surf",
1205 webkit_web_view_get_page_id(c->view));
1206 gtk_window_set_role(GTK_WINDOW(w), wmstr);
1209 gtk_window_set_default_size(GTK_WINDOW(w), winsize[0], winsize[1]);
1212 g_signal_connect(G_OBJECT(w), "destroy",
1213 G_CALLBACK(destroywin), c);
1214 g_signal_connect(G_OBJECT(w), "enter-notify-event",
1215 G_CALLBACK(winevent), c);
1216 g_signal_connect(G_OBJECT(w), "key-press-event",
1217 G_CALLBACK(winevent), c);
1218 g_signal_connect(G_OBJECT(w), "leave-notify-event",
1219 G_CALLBACK(winevent), c);
1220 g_signal_connect(G_OBJECT(w), "window-state-event",
1221 G_CALLBACK(winevent), c);
1227 loadchanged(WebKitWebView *v, WebKitLoadEvent e, Client *c)
1229 const char *title = geturi(c);
1232 case WEBKIT_LOAD_STARTED:
1233 curconfig = defconfig;
1234 setatom(c, AtomUri, title);
1236 c->https = c->insecure = 0;
1237 seturiparameters(c, geturi(c));
1239 case WEBKIT_LOAD_REDIRECTED:
1240 setatom(c, AtomUri, title);
1242 seturiparameters(c, geturi(c));
1244 case WEBKIT_LOAD_COMMITTED:
1245 c->https = webkit_web_view_get_tls_info(c->view, NULL,
1248 case WEBKIT_LOAD_FINISHED:
1249 /* Disabled until we write some WebKitWebExtension for
1250 * manipulating the DOM directly.
1251 evalscript(c, "document.documentElement.style.overflow = '%s'",
1252 enablescrollbars ? "auto" : "hidden");
1261 progresschanged(WebKitWebView *v, GParamSpec *ps, Client *c)
1263 c->progress = webkit_web_view_get_estimated_load_progress(c->view) *
1269 titlechanged(WebKitWebView *view, GParamSpec *ps, Client *c)
1271 c->title = webkit_web_view_get_title(c->view);
1276 mousetargetchanged(WebKitWebView *v, WebKitHitTestResult *h, guint modifiers,
1279 WebKitHitTestResultContext hc = webkit_hit_test_result_get_context(h);
1281 /* Keep the hit test to know where is the pointer on the next click */
1285 c->targeturi = webkit_hit_test_result_get_link_uri(h);
1286 else if (hc & OnImg)
1287 c->targeturi = webkit_hit_test_result_get_image_uri(h);
1288 else if (hc & OnMedia)
1289 c->targeturi = webkit_hit_test_result_get_media_uri(h);
1291 c->targeturi = NULL;
1293 c->overtitle = c->targeturi;
1298 permissionrequested(WebKitWebView *v, WebKitPermissionRequest *r, Client *c)
1300 if (WEBKIT_IS_GEOLOCATION_PERMISSION_REQUEST(r)) {
1301 if (curconfig[Geolocation].val.b)
1302 webkit_permission_request_allow(r);
1304 webkit_permission_request_deny(r);
1312 decidepolicy(WebKitWebView *v, WebKitPolicyDecision *d,
1313 WebKitPolicyDecisionType dt, Client *c)
1316 case WEBKIT_POLICY_DECISION_TYPE_NAVIGATION_ACTION:
1317 decidenavigation(d, c);
1319 case WEBKIT_POLICY_DECISION_TYPE_NEW_WINDOW_ACTION:
1320 decidenewwindow(d, c);
1322 case WEBKIT_POLICY_DECISION_TYPE_RESPONSE:
1323 decideresource(d, c);
1326 webkit_policy_decision_ignore(d);
1333 decidenavigation(WebKitPolicyDecision *d, Client *c)
1335 WebKitNavigationAction *a =
1336 webkit_navigation_policy_decision_get_navigation_action(
1337 WEBKIT_NAVIGATION_POLICY_DECISION(d));
1339 switch (webkit_navigation_action_get_navigation_type(a)) {
1340 case WEBKIT_NAVIGATION_TYPE_LINK_CLICKED: /* fallthrough */
1341 case WEBKIT_NAVIGATION_TYPE_FORM_SUBMITTED: /* fallthrough */
1342 case WEBKIT_NAVIGATION_TYPE_BACK_FORWARD: /* fallthrough */
1343 case WEBKIT_NAVIGATION_TYPE_RELOAD: /* fallthrough */
1344 case WEBKIT_NAVIGATION_TYPE_FORM_RESUBMITTED: /* fallthrough */
1345 case WEBKIT_NAVIGATION_TYPE_OTHER: /* fallthrough */
1347 /* Do not navigate to links with a "_blank" target (popup) */
1348 if (webkit_navigation_policy_decision_get_frame_name(
1349 WEBKIT_NAVIGATION_POLICY_DECISION(d))) {
1350 webkit_policy_decision_ignore(d);
1352 /* Filter out navigation to different domain ? */
1353 /* get action→urirequest, copy and load in new window+view
1354 * on Ctrl+Click ? */
1355 webkit_policy_decision_use(d);
1362 decidenewwindow(WebKitPolicyDecision *d, Client *c)
1365 WebKitNavigationAction *a =
1366 webkit_navigation_policy_decision_get_navigation_action(
1367 WEBKIT_NAVIGATION_POLICY_DECISION(d));
1370 switch (webkit_navigation_action_get_navigation_type(a)) {
1371 case WEBKIT_NAVIGATION_TYPE_LINK_CLICKED: /* fallthrough */
1372 case WEBKIT_NAVIGATION_TYPE_FORM_SUBMITTED: /* fallthrough */
1373 case WEBKIT_NAVIGATION_TYPE_BACK_FORWARD: /* fallthrough */
1374 case WEBKIT_NAVIGATION_TYPE_RELOAD: /* fallthrough */
1375 case WEBKIT_NAVIGATION_TYPE_FORM_RESUBMITTED:
1376 /* Filter domains here */
1377 /* If the value of “mouse-button” is not 0, then the navigation was triggered by a mouse event.
1378 * test for link clicked but no button ? */
1379 arg.v = webkit_uri_request_get_uri(
1380 webkit_navigation_action_get_request(a));
1381 newwindow(c, &arg, 0);
1383 case WEBKIT_NAVIGATION_TYPE_OTHER: /* fallthrough */
1388 webkit_policy_decision_ignore(d);
1392 decideresource(WebKitPolicyDecision *d, Client *c)
1395 WebKitResponsePolicyDecision *r = WEBKIT_RESPONSE_POLICY_DECISION(d);
1396 WebKitURIResponse *res =
1397 webkit_response_policy_decision_get_response(r);
1398 const gchar *uri = webkit_uri_response_get_uri(res);
1400 if (g_str_has_suffix(uri, "/favicon.ico")) {
1401 webkit_policy_decision_ignore(d);
1405 if (!g_str_has_prefix(uri, "http://")
1406 && !g_str_has_prefix(uri, "https://")
1407 && !g_str_has_prefix(uri, "about:")
1408 && !g_str_has_prefix(uri, "file://")
1409 && !g_str_has_prefix(uri, "data:")
1410 && !g_str_has_prefix(uri, "blob:")
1411 && strlen(uri) > 0) {
1412 for (i = 0; i < strlen(uri); i++) {
1413 if (!g_ascii_isprint(uri[i])) {
1419 handleplumb(c, uri);
1420 webkit_policy_decision_ignore(d);
1425 if (webkit_response_policy_decision_is_mime_type_supported(r)) {
1426 webkit_policy_decision_use(d);
1428 webkit_policy_decision_ignore(d);
1434 insecurecontent(WebKitWebView *v, WebKitInsecureContentEvent e, Client *c)
1440 downloadstarted(WebKitWebContext *wc, WebKitDownload *d, Client *c)
1442 g_signal_connect(G_OBJECT(d), "notify::response",
1443 G_CALLBACK(responsereceived), c);
1447 responsereceived(WebKitDownload *d, GParamSpec *ps, Client *c)
1449 download(c, webkit_download_get_response(d));
1450 webkit_download_cancel(d);
1454 download(Client *c, WebKitURIResponse *r)
1456 Arg a = (Arg)DOWNLOAD(webkit_uri_response_get_uri(r), geturi(c));
1461 closeview(WebKitWebView *v, Client *c)
1463 gtk_widget_destroy(c->win);
1467 destroywin(GtkWidget* w, Client *c)
1475 pasteuri(GtkClipboard *clipboard, const char *text, gpointer d)
1477 Arg a = {.v = text };
1479 loaduri((Client *) d, &a);
1483 reload(Client *c, const Arg *a)
1486 webkit_web_view_reload_bypass_cache(c->view);
1488 webkit_web_view_reload(c->view);
1492 print(Client *c, const Arg *a)
1494 webkit_print_operation_run_dialog(webkit_print_operation_new(c->view),
1495 GTK_WINDOW(c->win));
1499 clipboard(Client *c, const Arg *a)
1501 if (a->b) { /* load clipboard uri */
1502 gtk_clipboard_request_text(gtk_clipboard_get(
1503 GDK_SELECTION_PRIMARY),
1505 } else { /* copy uri */
1506 gtk_clipboard_set_text(gtk_clipboard_get(
1507 GDK_SELECTION_PRIMARY), c->targeturi
1508 ? c->targeturi : geturi(c), -1);
1513 zoom(Client *c, const Arg *a)
1516 webkit_web_view_set_zoom_level(c->view,
1517 curconfig[ZoomLevel].val.f + 0.1);
1519 webkit_web_view_set_zoom_level(c->view,
1520 curconfig[ZoomLevel].val.f - 0.1);
1522 webkit_web_view_set_zoom_level(c->view, 1.0);
1524 curconfig[ZoomLevel].val.f = webkit_web_view_get_zoom_level(c->view);
1528 scroll(Client *c, const Arg *a)
1530 GdkEvent *ev = gdk_event_new(GDK_KEY_PRESS);
1532 gdk_event_set_device(ev, gdkkb);
1533 ev->key.window = gtk_widget_get_window(GTK_WIDGET(c->win));
1534 ev->key.state = GDK_CONTROL_MASK;
1535 ev->key.time = GDK_CURRENT_TIME;
1539 ev->key.keyval = GDK_KEY_Down;
1542 ev->key.keyval = GDK_KEY_Page_Down;
1545 ev->key.keyval = GDK_KEY_Left;
1548 ev->key.keyval = GDK_KEY_Right;
1551 ev->key.keyval = GDK_KEY_Page_Up;
1554 ev->key.keyval = GDK_KEY_Up;
1562 navigate(Client *c, const Arg *a)
1565 webkit_web_view_go_back(c->view);
1567 webkit_web_view_go_forward(c->view);
1571 stop(Client *c, const Arg *a)
1573 webkit_web_view_stop_loading(c->view);
1577 toggle(Client *c, const Arg *a)
1579 curconfig[a->i].val.b ^= 1;
1580 setparameter(c, 1, (ParamName)a->i, &curconfig[a->i].val);
1584 togglefullscreen(Client *c, const Arg *a)
1586 /* toggling value is handled in winevent() */
1588 gtk_window_unfullscreen(GTK_WINDOW(c->win));
1590 gtk_window_fullscreen(GTK_WINDOW(c->win));
1594 togglecookiepolicy(Client *c, const Arg *a)
1597 cookiepolicy %= strlen(curconfig[CookiePolicies].val.v);
1599 setparameter(c, 0, CookiePolicies, NULL);
1603 toggleinspector(Client *c, const Arg *a)
1605 if (webkit_web_inspector_is_attached(c->inspector))
1606 webkit_web_inspector_close(c->inspector);
1607 else if (curconfig[Inspector].val.b)
1608 webkit_web_inspector_show(c->inspector);
1612 find(Client *c, const Arg *a)
1618 webkit_find_controller_search_next(c->finder);
1620 webkit_find_controller_search_previous(c->finder);
1622 s = getatom(c, AtomFind);
1623 f = webkit_find_controller_get_search_text(c->finder);
1625 if (g_strcmp0(f, s) == 0) /* reset search */
1626 webkit_find_controller_search(c->finder, "", findopts,
1629 webkit_find_controller_search(c->finder, s, findopts,
1632 if (strcmp(s, "") == 0)
1633 webkit_find_controller_search_finish(c->finder);
1638 clicknavigate(Client *c, const Arg *a, WebKitHitTestResult *h)
1644 clicknewwindow(Client *c, const Arg *a, WebKitHitTestResult *h)
1648 arg.v = webkit_hit_test_result_get_link_uri(h);
1649 newwindow(c, &arg, a->b);
1653 clickexternplayer(Client *c, const Arg *a, WebKitHitTestResult *h)
1657 arg = (Arg)VIDEOPLAY(webkit_hit_test_result_get_media_uri(h));
1662 main(int argc, char *argv[])
1667 memset(&arg, 0, sizeof(arg));
1669 /* command line args */
1672 defconfig CSETV(CookiePolicies, EARGF(usage()));
1675 defconfig CSETB(ScrollBars, 0);
1678 defconfig CSETB(ScrollBars, 1);
1681 cookiefile = EARGF(usage());
1684 stylefile = EARGF(usage());
1687 defconfig CSETB(DiskCache, 0);
1690 defconfig CSETB(DiskCache, 1);
1693 embed = strtol(EARGF(usage()), NULL, 0);
1696 defconfig CSETB(RunInFullscreen, 0);
1699 defconfig CSETB(RunInFullscreen, 1);
1702 defconfig CSETB(Geolocation, 0);
1705 defconfig CSETB(Geolocation, 1);
1708 defconfig CSETB(LoadImages, 0);
1711 defconfig CSETB(LoadImages, 1);
1714 defconfig CSETB(KioskMode, 0);
1717 defconfig CSETB(KioskMode, 1);
1720 defconfig CSETB(Style, 0);
1723 defconfig CSETB(Style, 1);
1726 defconfig CSETB(Inspector, 0);
1729 defconfig CSETB(Inspector, 1);
1732 defconfig CSETB(Plugins, 0);
1735 defconfig CSETB(Plugins, 1);
1738 scriptfile = EARGF(usage());
1741 defconfig CSETB(JavaScript, 0);
1744 defconfig CSETB(JavaScript, 1);
1747 fulluseragent = EARGF(usage());
1750 die("surf-"VERSION", ©2009-2017 surf engineers, "
1751 "see LICENSE for details\n");
1756 defconfig CSETF(ZoomLevel, strtof(EARGF(usage()), NULL));
1764 arg.v = "about:blank";
1767 c = newclient(NULL);