#![deny(missing_docs)]
use y901_ui::{Command, EventResult, Key, Modifiers, MouseButton, Size, UiEvent, UiTree};
pub mod gfx;
pub mod runtime;
pub mod window;
pub trait Waker: Send + Sync + 'static {
fn wake(&self);
}
pub trait Host {
fn idle(&mut self, tree: &mut UiTree);
fn attach_waker(&mut self, _waker: std::sync::Arc<dyn Waker>) {}
fn command(&mut self, tree: &mut UiTree, cmd: Command) -> bool;
fn event(&mut self, _tree: &mut UiTree, _ev: &UiEvent) -> EventResult {
EventResult::Ignored
}
fn take_theme_request(&mut self) -> Option<y901_ui::theme::Theme> {
None
}
fn take_font_request(&mut self) -> Option<FontConfig> {
None
}
fn take_snapshot_request(&mut self) -> bool {
false
}
fn on_snapshot(&mut self, _pixels: &[u8], _width: u32, _height: u32) {}
fn ime_position(&mut self, _tree: &mut UiTree) -> Option<(f32, f32)> {
None
}
}
pub type WindowFactory = Box<dyn FnMut(usize) -> (Box<dyn Host>, UiTree) + Send>;
pub trait PlatformRuntime {
fn run(
&mut self,
host: Box<dyn Host>,
build: Box<dyn FnOnce() -> UiTree>,
options: Options,
) -> Result<(), String>;
fn run_many(
&mut self,
options_list: Vec<Options>,
mut make: WindowFactory,
) -> Result<(), String> {
for (i, options) in options_list.into_iter().enumerate() {
let (host, tree) = make(i);
if let Err(e) = self.run(host, Box::new(move || tree), options) {
return Err(format!("窗口 {i}: {e}"));
}
}
Ok(())
}
}
#[derive(Clone, Copy, Debug)]
pub struct WindowHandle {
raw: gfx::PlatformWindowHandle,
width: u32,
height: u32,
scale: f32,
}
impl WindowHandle {
pub fn new(raw: gfx::PlatformWindowHandle, width: u32, height: u32, scale: f32) -> Self {
Self {
raw,
width,
height,
scale: if scale > 0.0 { scale } else { 1.0 },
}
}
pub fn size(&self) -> (u32, u32) {
(self.width, self.height)
}
pub fn scale(&self) -> f32 {
self.scale
}
pub fn raw(&self) -> gfx::PlatformWindowHandle {
self.raw
}
}
pub trait EventSource {
fn poll(&mut self, timeout_ms: u32) -> Vec<RawEvent>;
fn waker(&self) -> std::sync::Arc<dyn Waker>;
}
pub trait Presenter {
fn resize(&mut self, width: u32, height: u32) -> Result<(), String>;
fn present(&mut self, pixels: &[u8], width: u32, height: u32) -> Result<(), String>;
}
#[derive(Clone, Debug)]
pub struct Options {
pub title: String,
pub width: u32,
pub height: u32,
pub theme: Option<y901_ui::theme::Theme>,
pub font: Option<FontConfig>,
pub fullscreen: bool,
}
#[derive(Clone, Debug, PartialEq)]
pub struct FontConfig {
pub family: String,
pub size: f32,
}
impl Default for FontConfig {
fn default() -> Self {
Self {
family: "NSimSun".to_string(),
size: 16.0,
}
}
}
impl FontConfig {
pub fn modern() -> Self {
Self {
family: "Microsoft YaHei UI".to_string(),
size: 16.0,
}
}
}
impl Default for Options {
fn default() -> Self {
Self {
title: "Y901".to_string(),
width: 1200,
height: 800,
theme: None,
font: None,
fullscreen: false,
}
}
}
#[derive(Clone, Debug, PartialEq)]
pub enum RawEvent {
MouseMove {
x: f32,
y: f32,
},
MouseDown {
x: f32,
y: f32,
button: MouseButton,
},
MouseUp {
x: f32,
y: f32,
button: MouseButton,
},
Wheel {
x: f32,
y: f32,
delta: f32,
mods: Modifiers,
},
FileDrop {
paths: Vec<std::path::PathBuf>,
x: f32,
y: f32,
},
KeyDown {
key: Key,
mods: Modifiers,
},
SystemKeyDown {
key: Key,
mods: Modifiers,
},
Char {
c: char,
},
Ime {
text: String,
composition: bool,
},
Resize {
w: u32,
h: u32,
},
SetCursor {
x: f32,
y: f32,
},
Close,
}
pub fn translate(raw: &RawEvent, viewport: Size) -> Option<UiEvent> {
match raw {
RawEvent::MouseMove { x, y } => Some(UiEvent::MouseMove {
pos: y901_ui::Pos::new(*x, *y),
}),
RawEvent::MouseDown { x, y, button } => Some(UiEvent::MouseDown {
pos: y901_ui::Pos::new(*x, *y),
button: *button,
}),
RawEvent::MouseUp { x, y, button } => Some(UiEvent::MouseUp {
pos: y901_ui::Pos::new(*x, *y),
button: *button,
}),
RawEvent::FileDrop { paths, x, y } => Some(UiEvent::FileDrop {
paths: paths.clone(),
pos: y901_ui::Pos::new(*x, *y),
}),
RawEvent::Wheel { x, y, delta, mods } => Some(UiEvent::Wheel {
pos: y901_ui::Pos::new(*x, *y),
delta: *delta,
mods: *mods,
}),
RawEvent::SystemKeyDown { key, mods } => Some(UiEvent::Key {
key: *key,
modifiers: *mods,
}),
RawEvent::KeyDown { key, mods } => Some(UiEvent::Key {
key: *key,
modifiers: *mods,
}),
RawEvent::Char { c } => Some(UiEvent::Text(c.to_string())),
RawEvent::Ime { text, composition } => {
if *composition {
Some(UiEvent::Compose(text.clone()))
} else {
Some(UiEvent::Text(text.clone()))
}
}
RawEvent::Resize { w: _, h: _ } => {
let _ = viewport;
Some(UiEvent::Resize)
}
RawEvent::SetCursor { .. } => None,
RawEvent::Close => None,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn mouse_translates_to_positional_event() {
let ev = translate(
&RawEvent::MouseDown {
x: 10.0,
y: 20.0,
button: MouseButton::Left,
},
Size::new(100.0, 100.0),
)
.expect("event");
match ev {
UiEvent::MouseDown { pos, .. } => {
assert_eq!(pos.x, 10.0);
assert_eq!(pos.y, 20.0);
}
other => panic!("unexpected {other:?}"),
}
}
#[test]
fn char_becomes_text() {
let ev = translate(&RawEvent::Char { c: 'A' }, Size::new(1.0, 1.0)).unwrap();
assert!(matches!(ev, UiEvent::Text(t) if t == "A"));
}
#[test]
fn set_cursor_and_close_emit_nothing() {
assert!(translate(&RawEvent::SetCursor { x: 1.0, y: 2.0 }, Size::new(1.0, 1.0)).is_none());
assert!(translate(&RawEvent::Close, Size::new(1.0, 1.0)).is_none());
}
struct SnapshotHost {
requested: bool,
pixels: usize,
size: (u32, u32),
}
impl Host for SnapshotHost {
fn idle(&mut self, _tree: &mut UiTree) {}
fn command(&mut self, _tree: &mut UiTree, _cmd: Command) -> bool {
true
}
fn take_snapshot_request(&mut self) -> bool {
std::mem::take(&mut self.requested)
}
fn on_snapshot(&mut self, pixels: &[u8], width: u32, height: u32) {
self.pixels = pixels.len();
self.size = (width, height);
}
}
#[test]
fn snapshot_hooks_are_host_contract() {
let mut host = SnapshotHost {
requested: true,
pixels: 0,
size: (0, 0),
};
assert!(host.take_snapshot_request());
assert!(!host.take_snapshot_request(), "请求应只消费一次");
host.on_snapshot(&[1, 2, 3, 4], 1, 1);
assert_eq!(host.pixels, 4);
assert_eq!(host.size, (1, 1));
}
}