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 3 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"]
21 changes: 20 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,19 @@ bevy = { version = "0.10", default-features = false, features = [
"bevy_pbr",
"bevy_core_pipeline",
] }

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

[workspace]
members = ["run-wasm"]
128 changes: 128 additions & 0 deletions examples/clipboard.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
use std::sync::mpsc::{self, Receiver, Sender};

use bevy::{input::common_conditions::input_just_pressed, prelude::*, winit::WinitWindows};
use bevy_egui::{egui, EguiContexts, EguiPlugin};
use egui::{text_edit::CursorRange, TextEdit, Widget};
use wasm_bindgen_futures::spawn_local;

fn main() {
App::new()
.add_plugins(DefaultPlugins.set(WindowPlugin {
primary_window: Some(Window {
prevent_default_event_handling: false,
..default()
}),
..default()
}))
.add_plugin(EguiPlugin)
.init_resource::<CustomText>()
.init_non_send_resource::<ClipboardChannel>()
// 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_startup_system(setup_clipboard_paste)
.add_system(ui_edit)
.add_system(clipboard_copy.run_if(input_just_pressed(KeyCode::C)))
.add_system(read_clipboard_channel)
.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");
}
};
});
}

#[derive(Default)]
struct ClipboardChannel {
pub rx: Option<Receiver<String>>,
}

fn setup_clipboard_paste(
mut commands: Commands,
windows: Query<Entity, With<Window>>,
winit_windows: NonSendMut<WinitWindows>,
mut clipboardChannel: NonSendMut<ClipboardChannel>,
) {
let Some(first_window) = windows.iter().next() else {
return;
};
let Some(winit_window_instance) = winit_windows.get_window(first_window) else {
return;
};
let (tx, rx): (Sender<String>, Receiver<String>) = mpsc::channel();

use wasm_bindgen::closure::Closure;
use wasm_bindgen::prelude::*;
use winit::platform::web::WindowExtWebSys;
let canvas = winit_window_instance.canvas();
info!("canvas found");
let closure = Closure::<dyn FnMut(_)>::new(move |event: web_sys::ClipboardEvent| {
tx.send("test".to_string());
match event
.clipboard_data()
.expect("could not get clipboard data.")
.get_data("text/plain")
{
Ok(data) => {
tx.send(data);
}
_ => {
info!("Not implemented.");
}
}
info!("{:?}", event.clipboard_data())
});

canvas
.add_event_listener_with_callback("paste", closure.as_ref().unchecked_ref())
.expect("Could not edd paste event listener.");
Vrixyz marked this conversation as resolved.
Show resolved Hide resolved
closure.forget();
*clipboardChannel = ClipboardChannel { rx: Some(rx) };

// winit_window_instance.can
info!("setup_clipboard_paste OK");
}

fn read_clipboard_channel(mut clipboardChannel: NonSendMut<ClipboardChannel>) {
match &mut clipboardChannel.rx {
Some(rx) => {
if let Ok(clipboard_string) = rx.try_recv() {
info!("received: {}", clipboard_string);
Vrixyz marked this conversation as resolved.
Show resolved Hide resolved
}
}
None => {}
}
}
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; }");
}