1
0
mirror of https://github.com/emilk/egui.git synced 2026-06-26 22:53:14 -04:00

Fix the web backend too

This commit is contained in:
Emil Ernerfeldt
2023-04-20 10:14:17 +02:00
parent a27182472f
commit 6bac3d702f
5 changed files with 37 additions and 6 deletions

2
Cargo.lock generated
View File

@@ -1272,7 +1272,9 @@ dependencies = [
"log",
"poll-promise",
"serde",
"wasm-bindgen",
"wasm-bindgen-futures",
"web-sys",
]
[[package]]

View File

@@ -259,8 +259,8 @@ impl AppRunner {
let needs_repaint: std::sync::Arc<NeedRepaint> = Default::default();
{
let needs_repaint = needs_repaint.clone();
egui_ctx.set_request_repaint_callback(move || {
needs_repaint.repaint_asap();
egui_ctx.set_request_repaint_callback(move |info| {
needs_repaint.repaint_after(info.after.as_secs_f64());
});
}

View File

@@ -4,12 +4,15 @@ use egui::Key;
use super::*;
struct IsDestroyed(pub bool);
/// Calls `request_animation_frame` to schedule repaint.
///
/// It will only paint if needed, but will always call `request_animation_frame` immediately.
pub fn paint_and_schedule(
runner_ref: &AppRunnerRef,
panicked: Arc<AtomicBool>,
) -> Result<(), JsValue> {
struct IsDestroyed(pub bool);
fn paint_if_needed(runner_ref: &AppRunnerRef) -> Result<IsDestroyed, JsValue> {
let mut runner_lock = runner_ref.lock();
let is_destroyed = runner_lock.is_destroyed.fetch();

View File

@@ -63,4 +63,6 @@ env_logger = "0.10"
# web:
[target.'cfg(target_arch = "wasm32")'.dependencies]
console_error_panic_hook = "0.1.6"
wasm-bindgen = "=0.2.84"
wasm-bindgen-futures = "0.4"
web-sys = "0.3"

View File

@@ -265,8 +265,7 @@ impl BackendPanel {
{
log::info!("Waiting 2s before requesting repaint...");
let ctx = ui.ctx().clone();
std::thread::spawn(move || {
std::thread::sleep(std::time::Duration::from_secs(2));
call_after_delay(std::time::Duration::from_secs(2), move || {
log::info!("Request a repaint in 3s...");
ctx.request_repaint_after(std::time::Duration::from_secs(3));
});
@@ -385,3 +384,28 @@ impl EguiWindows {
});
}
}
// ----------------------------------------------------------------------------
#[cfg(not(target_arch = "wasm32"))]
fn call_after_delay(delay: std::time::Duration, f: impl FnOnce() + Send + 'static) {
std::thread::spawn(move || {
std::thread::sleep(delay);
f();
});
}
#[cfg(target_arch = "wasm32")]
fn call_after_delay(delay: std::time::Duration, f: impl FnOnce() + Send + 'static) {
use wasm_bindgen::prelude::*;
let window = web_sys::window().unwrap();
let closure = Closure::once(f);
let delay_ms = delay.as_millis() as _;
window
.set_timeout_with_callback_and_timeout_and_arguments_0(
closure.as_ref().unchecked_ref(),
delay_ms,
)
.unwrap();
closure.forget(); // We must forget it, or else the callback is canceled on drop
}