mirror of
https://github.com/emilk/egui.git
synced 2026-08-29 04:40:03 -04:00
[web] move all reusable web code into egui_web
This commit is contained in:
@@ -10,6 +10,7 @@ crate-type = ["cdylib", "rlib"]
|
||||
|
||||
[dependencies]
|
||||
js-sys = "0.3"
|
||||
parking_lot = "0.11"
|
||||
serde = "1"
|
||||
serde_json = "1"
|
||||
wasm-bindgen = "0.2"
|
||||
@@ -26,7 +27,9 @@ features = [
|
||||
'Element',
|
||||
'HtmlCanvasElement',
|
||||
'HtmlElement',
|
||||
'KeyboardEvent',
|
||||
'Location',
|
||||
'MouseEvent',
|
||||
'Performance',
|
||||
'Storage',
|
||||
'Touch',
|
||||
|
||||
@@ -3,25 +3,43 @@
|
||||
|
||||
pub mod webgl;
|
||||
|
||||
use parking_lot::Mutex;
|
||||
use std::sync::Arc;
|
||||
use wasm_bindgen::prelude::*;
|
||||
|
||||
// ----------------------------------------------------------------------------
|
||||
|
||||
use std::sync::Arc;
|
||||
use wasm_bindgen::JsValue;
|
||||
pub struct BackendInfo {
|
||||
pub painter_debug_info: String,
|
||||
/// excludes call to paint backend
|
||||
pub cpu_time: f32,
|
||||
pub fps: f32,
|
||||
|
||||
pub struct EguiWeb {
|
||||
/// e.g. "#fragment" part of "www.example.com/index.html#fragment"
|
||||
pub web_location_hash: String,
|
||||
}
|
||||
|
||||
/// Implement this and use `egui_web::AppRunner` to run your app.
|
||||
pub trait App {
|
||||
fn ui(&mut self, ui: &mut egui::Ui, info: &BackendInfo);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------------
|
||||
|
||||
pub struct Backend {
|
||||
ctx: Arc<egui::Context>,
|
||||
webgl_painter: webgl::Painter,
|
||||
painter: webgl::Painter,
|
||||
frame_times: egui::MovementTracker<f32>,
|
||||
frame_start: Option<f64>,
|
||||
}
|
||||
|
||||
impl EguiWeb {
|
||||
pub fn new(canvas_id: &str) -> Result<EguiWeb, JsValue> {
|
||||
impl Backend {
|
||||
pub fn new(canvas_id: &str) -> Result<Backend, JsValue> {
|
||||
let ctx = egui::Context::new();
|
||||
load_memory(&ctx);
|
||||
Ok(EguiWeb {
|
||||
Ok(Backend {
|
||||
ctx,
|
||||
webgl_painter: webgl::Painter::new(canvas_id)?,
|
||||
painter: webgl::Painter::new(canvas_id)?,
|
||||
frame_times: egui::MovementTracker::new(1000, 1.0),
|
||||
frame_start: None,
|
||||
})
|
||||
@@ -29,7 +47,7 @@ impl EguiWeb {
|
||||
|
||||
/// id of the canvas html element containing the rendering
|
||||
pub fn canvas_id(&self) -> &str {
|
||||
self.webgl_painter.canvas_id()
|
||||
self.painter.canvas_id()
|
||||
}
|
||||
|
||||
pub fn begin_frame(&mut self, raw_input: egui::RawInput) -> egui::Ui {
|
||||
@@ -49,7 +67,7 @@ impl EguiWeb {
|
||||
let now = now_sec();
|
||||
self.frame_times.add(now, (now - frame_start) as f32);
|
||||
|
||||
self.webgl_painter.paint_batches(
|
||||
self.painter.paint_batches(
|
||||
bg_color,
|
||||
batches,
|
||||
self.ctx.texture(),
|
||||
@@ -62,11 +80,11 @@ impl EguiWeb {
|
||||
}
|
||||
|
||||
pub fn painter_debug_info(&self) -> String {
|
||||
self.webgl_painter.debug_info()
|
||||
self.painter.debug_info()
|
||||
}
|
||||
|
||||
/// excludes painting
|
||||
pub fn cpu_usage(&self) -> f32 {
|
||||
pub fn cpu_time(&self) -> f32 {
|
||||
self.frame_times.average().unwrap_or_default()
|
||||
}
|
||||
|
||||
@@ -75,6 +93,87 @@ impl EguiWeb {
|
||||
}
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------------
|
||||
|
||||
/// Data gathered between frames.
|
||||
/// Is translated to `egui::RawInput` at the start of each frame.
|
||||
#[derive(Default)]
|
||||
pub struct WebInput {
|
||||
pub mouse_pos: Option<egui::Pos2>,
|
||||
pub mouse_down: bool, // TODO: which button
|
||||
pub is_touch: bool,
|
||||
pub scroll_delta: egui::Vec2,
|
||||
pub events: Vec<egui::Event>,
|
||||
}
|
||||
|
||||
impl WebInput {
|
||||
pub fn new_frame(&mut self) -> egui::RawInput {
|
||||
egui::RawInput {
|
||||
mouse_down: self.mouse_down,
|
||||
mouse_pos: self.mouse_pos,
|
||||
scroll_delta: std::mem::take(&mut self.scroll_delta),
|
||||
screen_size: screen_size().unwrap(),
|
||||
pixels_per_point: Some(pixels_per_point()),
|
||||
time: now_sec(),
|
||||
seconds_since_midnight: Some(seconds_since_midnight()),
|
||||
events: std::mem::take(&mut self.events),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------------
|
||||
|
||||
pub struct AppRunner {
|
||||
pub backend: Backend,
|
||||
pub web_input: WebInput,
|
||||
pub app: Box<dyn App>,
|
||||
}
|
||||
|
||||
impl AppRunner {
|
||||
pub fn new(canvas_id: &str, app: Box<dyn App>) -> Result<Self, JsValue> {
|
||||
Ok(Self {
|
||||
backend: Backend::new(canvas_id)?,
|
||||
web_input: Default::default(),
|
||||
app,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn canvas_id(&self) -> &str {
|
||||
self.backend.canvas_id()
|
||||
}
|
||||
|
||||
pub fn paint(&mut self) -> Result<(), JsValue> {
|
||||
resize_to_screen_size(self.backend.canvas_id());
|
||||
|
||||
let raw_input = self.web_input.new_frame();
|
||||
|
||||
let info = BackendInfo {
|
||||
painter_debug_info: self.backend.painter_debug_info(),
|
||||
cpu_time: self.backend.cpu_time(),
|
||||
fps: self.backend.fps(),
|
||||
web_location_hash: location_hash().unwrap_or_default(),
|
||||
};
|
||||
|
||||
let mut ui = self.backend.begin_frame(raw_input);
|
||||
self.app.ui(&mut ui, &info);
|
||||
let output = self.backend.end_frame()?;
|
||||
|
||||
handle_output(&output);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Install event listeners to register different input events
|
||||
/// and starts running the given `AppRunner`.
|
||||
pub fn run(runner: AppRunner) -> Result<AppRunnerRef, JsValue> {
|
||||
let runner = AppRunnerRef(Arc::new(Mutex::new(runner)));
|
||||
install_canvas_events(&runner)?;
|
||||
install_document_events(&runner)?;
|
||||
paint_and_schedule(runner.clone())?;
|
||||
Ok(runner)
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------------
|
||||
// Helpers to hide some of the verbosity of web_sys
|
||||
|
||||
@@ -272,3 +371,228 @@ pub fn translate_key(key: &str) -> Option<egui::Key> {
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------------
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct AppRunnerRef(Arc<Mutex<AppRunner>>);
|
||||
|
||||
/// If true, paint at full framerate always.
|
||||
/// If false, only paint on input.
|
||||
/// TODO: if this is turned off we must turn off animations too (which hasn't been implemented yet).
|
||||
const ANIMATION_FRAME: bool = true;
|
||||
|
||||
fn paint_and_schedule(runner: AppRunnerRef) -> Result<(), JsValue> {
|
||||
runner.0.lock().paint()?;
|
||||
if ANIMATION_FRAME {
|
||||
request_animation_frame(runner)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn request_animation_frame(runner: AppRunnerRef) -> Result<(), JsValue> {
|
||||
use wasm_bindgen::JsCast;
|
||||
let window = web_sys::window().unwrap();
|
||||
let closure = Closure::once(move || paint_and_schedule(runner));
|
||||
window.request_animation_frame(closure.as_ref().unchecked_ref())?;
|
||||
closure.forget(); // We must forget it, or else the callback is canceled on drop
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn invalidate(runner: &mut AppRunner) -> Result<(), JsValue> {
|
||||
if ANIMATION_FRAME {
|
||||
Ok(()) // No need to invalidate - we repaint all the time
|
||||
} else {
|
||||
runner.paint() // TODO: schedule repaint instead?
|
||||
}
|
||||
}
|
||||
|
||||
fn install_document_events(runner: &AppRunnerRef) -> Result<(), JsValue> {
|
||||
use wasm_bindgen::JsCast;
|
||||
let document = web_sys::window().unwrap().document().unwrap();
|
||||
|
||||
{
|
||||
// keydown
|
||||
let runner = runner.clone();
|
||||
let closure = Closure::wrap(Box::new(move |event: web_sys::KeyboardEvent| {
|
||||
let mut runner = runner.0.lock();
|
||||
let key = event.key();
|
||||
if let Some(key) = translate_key(&key) {
|
||||
runner
|
||||
.web_input
|
||||
.events
|
||||
.push(egui::Event::Key { key, pressed: true });
|
||||
} else {
|
||||
runner.web_input.events.push(egui::Event::Text(key));
|
||||
}
|
||||
invalidate(&mut runner).unwrap();
|
||||
}) as Box<dyn FnMut(_)>);
|
||||
document.add_event_listener_with_callback("keydown", closure.as_ref().unchecked_ref())?;
|
||||
closure.forget();
|
||||
}
|
||||
|
||||
{
|
||||
// keyup
|
||||
let runner = runner.clone();
|
||||
let closure = Closure::wrap(Box::new(move |event: web_sys::KeyboardEvent| {
|
||||
let mut runner = runner.0.lock();
|
||||
let key = event.key();
|
||||
if let Some(key) = translate_key(&key) {
|
||||
runner.web_input.events.push(egui::Event::Key {
|
||||
key,
|
||||
pressed: false,
|
||||
});
|
||||
invalidate(&mut runner).unwrap();
|
||||
}
|
||||
}) as Box<dyn FnMut(_)>);
|
||||
document.add_event_listener_with_callback("keyup", closure.as_ref().unchecked_ref())?;
|
||||
closure.forget();
|
||||
}
|
||||
|
||||
for event_name in &["load", "pagehide", "pageshow", "resize"] {
|
||||
let runner = runner.clone();
|
||||
let closure = Closure::wrap(Box::new(move || {
|
||||
invalidate(&mut runner.0.lock()).unwrap();
|
||||
}) as Box<dyn FnMut()>);
|
||||
document.add_event_listener_with_callback(event_name, closure.as_ref().unchecked_ref())?;
|
||||
closure.forget();
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn install_canvas_events(runner: &AppRunnerRef) -> Result<(), JsValue> {
|
||||
use wasm_bindgen::JsCast;
|
||||
let canvas = canvas_element(runner.0.lock().canvas_id()).unwrap();
|
||||
|
||||
{
|
||||
let event_name = "mousedown";
|
||||
let runner = runner.clone();
|
||||
let closure = Closure::wrap(Box::new(move |event: web_sys::MouseEvent| {
|
||||
let mut runner = runner.0.lock();
|
||||
if !runner.web_input.is_touch {
|
||||
runner.web_input.mouse_pos = Some(pos_from_mouse_event(runner.canvas_id(), &event));
|
||||
runner.web_input.mouse_down = true;
|
||||
invalidate(&mut runner).unwrap();
|
||||
event.stop_propagation();
|
||||
event.prevent_default();
|
||||
}
|
||||
}) as Box<dyn FnMut(_)>);
|
||||
canvas.add_event_listener_with_callback(event_name, closure.as_ref().unchecked_ref())?;
|
||||
closure.forget();
|
||||
}
|
||||
|
||||
{
|
||||
let event_name = "mousemove";
|
||||
let runner = runner.clone();
|
||||
let closure = Closure::wrap(Box::new(move |event: web_sys::MouseEvent| {
|
||||
let mut runner = runner.0.lock();
|
||||
if !runner.web_input.is_touch {
|
||||
runner.web_input.mouse_pos = Some(pos_from_mouse_event(runner.canvas_id(), &event));
|
||||
invalidate(&mut runner).unwrap();
|
||||
event.stop_propagation();
|
||||
event.prevent_default();
|
||||
}
|
||||
}) as Box<dyn FnMut(_)>);
|
||||
canvas.add_event_listener_with_callback(event_name, closure.as_ref().unchecked_ref())?;
|
||||
closure.forget();
|
||||
}
|
||||
|
||||
{
|
||||
let event_name = "mouseup";
|
||||
let runner = runner.clone();
|
||||
let closure = Closure::wrap(Box::new(move |event: web_sys::MouseEvent| {
|
||||
let mut runner = runner.0.lock();
|
||||
if !runner.web_input.is_touch {
|
||||
runner.web_input.mouse_pos = Some(pos_from_mouse_event(runner.canvas_id(), &event));
|
||||
runner.web_input.mouse_down = false;
|
||||
invalidate(&mut runner).unwrap();
|
||||
event.stop_propagation();
|
||||
event.prevent_default();
|
||||
}
|
||||
}) as Box<dyn FnMut(_)>);
|
||||
canvas.add_event_listener_with_callback(event_name, closure.as_ref().unchecked_ref())?;
|
||||
closure.forget();
|
||||
}
|
||||
|
||||
{
|
||||
let event_name = "mouseleave";
|
||||
let runner = runner.clone();
|
||||
let closure = Closure::wrap(Box::new(move |event: web_sys::MouseEvent| {
|
||||
let mut runner = runner.0.lock();
|
||||
if !runner.web_input.is_touch {
|
||||
runner.web_input.mouse_pos = None;
|
||||
invalidate(&mut runner).unwrap();
|
||||
event.stop_propagation();
|
||||
event.prevent_default();
|
||||
}
|
||||
}) as Box<dyn FnMut(_)>);
|
||||
canvas.add_event_listener_with_callback(event_name, closure.as_ref().unchecked_ref())?;
|
||||
closure.forget();
|
||||
}
|
||||
|
||||
{
|
||||
let event_name = "touchstart";
|
||||
let runner = runner.clone();
|
||||
let closure = Closure::wrap(Box::new(move |event: web_sys::TouchEvent| {
|
||||
let mut runner = runner.0.lock();
|
||||
runner.web_input.is_touch = true;
|
||||
runner.web_input.mouse_pos = Some(pos_from_touch_event(&event));
|
||||
runner.web_input.mouse_down = true;
|
||||
invalidate(&mut runner).unwrap();
|
||||
event.stop_propagation();
|
||||
event.prevent_default();
|
||||
}) as Box<dyn FnMut(_)>);
|
||||
canvas.add_event_listener_with_callback(event_name, closure.as_ref().unchecked_ref())?;
|
||||
closure.forget();
|
||||
}
|
||||
|
||||
{
|
||||
let event_name = "touchmove";
|
||||
let runner = runner.clone();
|
||||
let closure = Closure::wrap(Box::new(move |event: web_sys::TouchEvent| {
|
||||
let mut runner = runner.0.lock();
|
||||
runner.web_input.is_touch = true;
|
||||
runner.web_input.mouse_pos = Some(pos_from_touch_event(&event));
|
||||
invalidate(&mut runner).unwrap();
|
||||
event.stop_propagation();
|
||||
event.prevent_default();
|
||||
}) as Box<dyn FnMut(_)>);
|
||||
canvas.add_event_listener_with_callback(event_name, closure.as_ref().unchecked_ref())?;
|
||||
closure.forget();
|
||||
}
|
||||
|
||||
{
|
||||
let event_name = "touchend";
|
||||
let runner = runner.clone();
|
||||
let closure = Closure::wrap(Box::new(move |event: web_sys::TouchEvent| {
|
||||
let mut runner = runner.0.lock();
|
||||
runner.web_input.is_touch = true;
|
||||
runner.web_input.mouse_down = false; // First release mouse to click...
|
||||
runner.paint().unwrap(); // ...do the clicking...
|
||||
runner.web_input.mouse_pos = None; // ...remove hover effect
|
||||
invalidate(&mut runner).unwrap();
|
||||
event.stop_propagation();
|
||||
event.prevent_default();
|
||||
}) as Box<dyn FnMut(_)>);
|
||||
canvas.add_event_listener_with_callback(event_name, closure.as_ref().unchecked_ref())?;
|
||||
closure.forget();
|
||||
}
|
||||
|
||||
{
|
||||
let event_name = "wheel";
|
||||
let runner = runner.clone();
|
||||
let closure = Closure::wrap(Box::new(move |event: web_sys::WheelEvent| {
|
||||
let mut runner = runner.0.lock();
|
||||
runner.web_input.scroll_delta.x -= event.delta_x() as f32;
|
||||
runner.web_input.scroll_delta.y -= event.delta_y() as f32;
|
||||
invalidate(&mut runner).unwrap();
|
||||
event.stop_propagation();
|
||||
event.prevent_default();
|
||||
}) as Box<dyn FnMut(_)>);
|
||||
canvas.add_event_listener_with_callback(event_name, closure.as_ref().unchecked_ref())?;
|
||||
closure.forget();
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user