Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

web clipboard handling #178

Closed
wants to merge 19 commits into from
Closed
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions .cargo/config.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
[alias]
run-wasm = ["run", "--release", "--package", "run-wasm", "--"]
Copy link
Contributor Author

@Vrixyz Vrixyz May 22, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think cargo run-wasm is quite handy to easily test a wasm version ; I can make another PR if interested


# Credits to https://github.com/emilk/egui

# clipboard api is still unstable, so web-sys requires the below flag to be passed for copy (ctrl + c) to work
# https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html
# check status at https://developer.mozilla.org/en-US/docs/Web/API/Clipboard#browser_compatibility
#[build]
#target = "wasm32-unknown-unknown"

Vrixyz marked this conversation as resolved.
Show resolved Hide resolved
[target.wasm32-unknown-unknown]
rustflags = ["--cfg=web_sys_unstable_apis"]
20 changes: 19 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,10 @@ default_fonts = ["egui/default_fonts"]
serde = ["egui/serde"]

[dependencies]
bevy = { version = "0.10", default-features = false, features = ["bevy_render", "bevy_asset"] }
bevy = { version = "0.10", default-features = false, features = [
"bevy_render",
"bevy_asset",
] }
egui = { version = "0.21.0", default-features = false, features = ["bytemuck"] }
webbrowser = { version = "0.8.2", optional = true }

Expand All @@ -39,3 +42,18 @@ bevy = { version = "0.10", default-features = false, features = [
"bevy_pbr",
"bevy_core_pipeline",
] }

[target.'cfg(target_arch = "wasm32")'.dependencies]
web-sys = { version = "*", features = [
Vrixyz marked this conversation as resolved.
Show resolved Hide resolved
"Clipboard",
"Window",
"Navigator",
"Permissions",
"ClipboardPermissionDescriptor",
"PermissionName",
] }
js-sys = "*"
wasm-bindgen-futures = "*"

[workspace]
members = ["run-wasm"]
92 changes: 92 additions & 0 deletions examples/clipboard.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
use bevy::{input::common_conditions::input_just_pressed, prelude::*};
use bevy_egui::{egui, EguiContexts, EguiPlugin};
use egui::{text_edit::CursorRange, TextEdit, Widget};
use wasm_bindgen_futures::spawn_local;
use web_sys::ClipboardPermissionDescriptor;

fn main() {
App::new()
.add_plugins(DefaultPlugins)
Vrixyz marked this conversation as resolved.
Show resolved Hide resolved
.add_plugin(EguiPlugin)
.init_resource::<CustomText>()
// Systems that create Egui widgets should be run during the `CoreSet::Update` set,
// or after the `EguiSet::BeginFrame` system (which belongs to the `CoreSet::PreUpdate` set).
.add_system(ui_edit)
.add_system(clipboard_copy.run_if(input_just_pressed(KeyCode::C)))
.add_system(clipboard_paste.run_if(input_just_pressed(KeyCode::V)))
.run();
}

#[derive(Resource, Default)]
struct CustomText(pub String, pub Option<CursorRange>);

fn ui_edit(mut contexts: EguiContexts, mut text: ResMut<CustomText>) {
egui::Window::new("Hello").show(contexts.ctx_mut(), |ui| {
let edit = TextEdit::multiline(&mut text.0).show(ui);
text.1 = edit.cursor_range;
});
}

fn clipboard_copy(mut text: ResMut<CustomText>) {
//text.0 = "copy".into();

let text = if let Some(selected) = text.1 {
text.0[selected.primary.ccursor.index..selected.secondary.ccursor.index].to_string()
} else {
"".into()
};
let _task = spawn_local(async move {
let window = web_sys::window().expect("window"); // { obj: val };

let nav = window.navigator();

let clipboard = nav.clipboard();
match clipboard {
Some(a) => {
let p = a.write_text(&text);
let result = wasm_bindgen_futures::JsFuture::from(p)
.await
.expect("clipboard populated");
info!("clippyboy worked");
}
None => {
warn!("failed to write clippyboy");
}
};
});
}

fn clipboard_paste(mut text: ResMut<CustomText>) {
let _task = spawn_local(async move {
let window = web_sys::window().expect("window"); // { obj: val };

let nav = window.navigator();
let clipboard = nav.clipboard();

let Ok(permissions) = nav.permissions() else {
return;
};
let clipboard_permission_desc = js_sys::Object::new();
js_sys::Reflect::set(
&clipboard_permission_desc,
&"name".into(),
// 'clipboard-read' fails on firefox because it's not implemented.
// more info: https://developer.mozilla.org/en-US/docs/Web/API/Permissions_API#browser_compatibility
&"clipboard-read".into(),
);
dbg!(permissions.query(&clipboard_permission_desc.into()));
match clipboard {
Some(a) => {
let p = a.read();
let result = wasm_bindgen_futures::JsFuture::from(p)
.await
.expect("clipboard populated");
dbg!("result: ", &result);
info!("clippyboy worked");
}
None => {
warn!("failed to read clippyboy");
}
};
});
}
9 changes: 9 additions & 0 deletions run-wasm/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
[package]
name = "run-wasm"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
cargo-run-wasm = "0.2.0"
3 changes: 3 additions & 0 deletions run-wasm/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
fn main() {
cargo_run_wasm::run_wasm_with_css("body { margin: 0px; }");
}