From cc6de120f2e711e3b7aa9fa50bd0598ee54b6013 Mon Sep 17 00:00:00 2001 From: meehl <12648828+meehl@users.noreply.github.com> Date: Sun, 23 Aug 2026 11:20:14 +0200 Subject: [PATCH] Refactor context handling and redraw requests Remove unsafe pointer shenanigans and give Lua instance ownership over `Context`. Event handlers now directly mutate Context instead of using a shared app state which is then hooked up to Context via unsafe pointers. The removal of a shared state means stages (previously called "modes") are now responsible for keeping their own internal state. Additionally, clean up draw request handling and module hierarchy. --- src/api/clipboard.rs | 13 - src/app.rs | 257 ++++++++-------- src/batcher.rs | 3 + src/gfx.rs | 10 +- src/input.rs | 10 +- src/installer.rs | 67 +++-- src/lua.rs | 329 -------------------- src/main.rs | 5 +- src/mode.rs | 73 ----- src/pob.rs | 465 +++++++++++++++++++++-------- src/{ => pob}/api.rs | 35 ++- src/{ => pob}/api/callback.rs | 11 +- src/pob/api/clipboard.rs | 13 + src/{ => pob}/api/compression.rs | 0 src/{ => pob}/api/console.rs | 0 src/{ => pob}/api/image_handle.rs | 16 +- src/{ => pob}/api/input.rs | 8 +- src/{ => pob}/api/lua.rs | 20 +- src/{ => pob}/api/paths.rs | 12 +- src/{ => pob}/api/rendering.rs | 62 ++-- src/{ => pob}/api/search_handle.rs | 0 src/pob/api/subscript.rs | 43 +++ src/{ => pob}/api/window.rs | 22 +- src/{ => pob}/subscript.rs | 90 +----- src/renderer.rs | 1 + src/stage.rs | 108 +++++++ src/window.rs | 6 - 27 files changed, 803 insertions(+), 876 deletions(-) delete mode 100644 src/api/clipboard.rs delete mode 100644 src/lua.rs delete mode 100644 src/mode.rs rename src/{ => pob}/api.rs (86%) rename src/{ => pob}/api/callback.rs (87%) create mode 100644 src/pob/api/clipboard.rs rename src/{ => pob}/api/compression.rs (100%) rename src/{ => pob}/api/console.rs (100%) rename src/{ => pob}/api/image_handle.rs (95%) rename src/{ => pob}/api/input.rs (77%) rename src/{ => pob}/api/lua.rs (74%) rename src/{ => pob}/api/paths.rs (87%) rename src/{ => pob}/api/rendering.rs (93%) rename src/{ => pob}/api/search_handle.rs (100%) create mode 100644 src/pob/api/subscript.rs rename src/{ => pob}/api/window.rs (63%) rename src/{ => pob}/subscript.rs (81%) create mode 100644 src/stage.rs diff --git a/src/api/clipboard.rs b/src/api/clipboard.rs deleted file mode 100644 index b5a0d52..0000000 --- a/src/api/clipboard.rs +++ /dev/null @@ -1,13 +0,0 @@ -use crate::lua::Context; -use mlua::{Lua, Result as LuaResult}; - -pub fn copy(l: &Lua, text: String) -> LuaResult<()> { - let ctx = l.app_data_ref::().unwrap(); - ctx.window().set_clipboard_text(text); - Ok(()) -} - -pub fn paste(l: &Lua, _: ()) -> LuaResult> { - let ctx = l.app_data_ref::().unwrap(); - Ok(ctx.window().get_clipboard_text()) -} diff --git a/src/app.rs b/src/app.rs index 5cb3ce4..c8e9e7c 100644 --- a/src/app.rs +++ b/src/app.rs @@ -1,19 +1,17 @@ use crate::{ args::Game, batcher::build_render_job, - dpi::{ConvertToLogical, PhysicalPoint, PhysicalSize}, + dpi::{PhysicalPoint, PhysicalSize}, fonts::{FontData, FontDefinitions, Fonts}, gfx::GraphicsContext, - input::InputState, - installer::InstallMode, - mode::{AppEvent, AppMode, ModeTransition}, - pob::PoBMode, + installer::Installer, + pob::PathOfBuilding, renderer::{RenderJob, textures::WrappedTextureManager}, - window::WindowState, + stage::{ActiveStage, StageEvent, StageTransition}, }; use anyhow::Result; -use std::path::PathBuf; use std::sync::Arc; +use std::{cell::RefCell, path::PathBuf, rc::Rc}; use winit::{ application::ApplicationHandler, event::*, event_loop::ActiveEventLoop, platform::modifier_supplement::KeyEventExtModifierSupplement, window::Window, @@ -21,32 +19,17 @@ use winit::{ struct FrameOutput { pub render_job: Option, - pub should_continue: bool, -} - -pub struct AppState { - pub window: WindowState, - pub input: InputState, - pub fonts: Fonts, - pub texture_manager: WrappedTextureManager, - pub script_dir: PathBuf, - pub should_exit: bool, -} - -impl AppState { - fn set_mouse_pos(&mut self, pos: PhysicalPoint) { - self.input - .set_mouse_pos(pos.to_logical(self.window.scale_factor())); - } + pub request_redraw: bool, } pub struct App { gfx_context: Option, - state: AppState, + fonts: Rc>, + texture_manager: Rc>, + stage: ActiveStage, game: Game, + script_dir: PathBuf, needs_reconfigure: bool, - force_render: bool, - current_mode: AppMode, } impl App { @@ -54,81 +37,86 @@ impl App { let uses_custom_script_dir = custom_script_dir.is_some(); let script_dir = custom_script_dir.unwrap_or_else(|| game.script_dir()); - let mut state = AppState { - window: WindowState::default(), - input: InputState::default(), - fonts: Fonts::new(pob_font_definitions()), - texture_manager: WrappedTextureManager::new(), - script_dir, - should_exit: false, - }; + let fonts = Rc::new(RefCell::new(Fonts::new(pob_font_definitions()))); + let texture_manager = Rc::new(RefCell::new(WrappedTextureManager::new())); - let current_mode = if uses_custom_script_dir { - // Skip installer if custom script dir is provided. - // Used for local testing - let pob_mode = PoBMode::new(&mut state)?; - AppMode::PoB(pob_mode) + let stage = if uses_custom_script_dir { + // skip installer if custom script dir is provided. used for local testing. + let pob = + PathOfBuilding::new(&script_dir, Rc::clone(&fonts), Rc::clone(&texture_manager))?; + ActiveStage::Main(pob) } else { - AppMode::Install(InstallMode::new(game)) + ActiveStage::Startup(Installer::new(game, Rc::clone(&fonts))) }; Ok(Self { gfx_context: None, - state, + fonts, + texture_manager, + stage, game, + script_dir, needs_reconfigure: true, - force_render: true, - current_mode, }) } - fn update(&mut self) -> anyhow::Result<()> { - let transition = self.current_mode.update(&mut self.state)?; - if let Some(transition) = transition { - self.current_mode = match transition { - ModeTransition::PoB => { - let pob_mode = PoBMode::new(&mut self.state)?; - AppMode::PoB(pob_mode) + fn update(&mut self, event_loop: &ActiveEventLoop) -> anyhow::Result<()> { + let transition = self.stage.update(); + if let Some(transition) = transition? { + match transition { + StageTransition::ToMain => { + self.stage = ActiveStage::Main(PathOfBuilding::new( + &self.script_dir, + Rc::clone(&self.fonts), + Rc::clone(&self.texture_manager), + )?); + if let Some(gfx) = &self.gfx_context { + self.stage.set_window(Arc::clone(&gfx.window)); + } + } + StageTransition::ToShutdown => { + self.handle_event(StageEvent::Exit); + event_loop.exit(); } }; } - Ok(()) } - fn frame(&mut self) -> anyhow::Result { - self.state.fonts.begin_frame(); + fn frame(&mut self, inhibit_elision: bool) -> anyhow::Result { + self.fonts.borrow_mut().begin_frame(); - let mode_output = self.current_mode.frame(&mut self.state)?; + let stage_output = self.stage.frame()?; - if let Some(font_image_delta) = self.state.fonts.font_atlas_delta() { - self.state - .texture_manager + if let Some(font_image_delta) = self.fonts.borrow_mut().font_atlas_delta() { + self.texture_manager + .borrow() .update_font_texture(font_image_delta); } - let textures_delta = self.state.texture_manager.take_delta(); + let textures_delta = self.texture_manager.borrow().take_delta(); - let render_job = if mode_output.can_elide && textures_delta.is_empty() && !self.force_render + let render_job = if stage_output.can_elide && textures_delta.is_empty() && !inhibit_elision { None } else { Some(build_render_job( - &mode_output.draw_commands, + &stage_output.draw_commands, textures_delta, - // TODO: find better way to determine this and how to pass it in + stage_output.scale_factor, + // TODO: find better way to determine this value and how to pass it in 32, )) }; Ok(FrameOutput { render_job, - should_continue: mode_output.should_continue, + request_redraw: stage_output.request_redraw, }) } - fn handle_event(&mut self, event: AppEvent) { - if let Err(err) = self.current_mode.handle_event(&mut self.state, event) { + fn handle_event(&mut self, event: StageEvent) { + if let Err(err) = self.stage.handle_event(event) { log::error!("{err}"); } } @@ -160,11 +148,17 @@ impl App { let window = event_loop.create_window(window_attributes)?; let window = Arc::new(window); - self.state.window.set_window(Arc::clone(&window)); + self.stage.set_window(Arc::clone(&window)); self.gfx_context = Some(pollster::block_on(GraphicsContext::new(window))?); Ok(()) } + + fn request_redraw(&self) { + if let Some(gfx) = &self.gfx_context { + gfx.window.request_redraw(); + } + } } impl ApplicationHandler for App { @@ -183,145 +177,130 @@ impl ApplicationHandler for App { ) { match event { WindowEvent::CloseRequested => { - self.state.should_exit = self.current_mode.can_exit(&mut self.state); - if !self.state.should_exit { - self.state.window.request_redraw(); + if self.stage.can_exit() { + self.handle_event(StageEvent::Exit); + event_loop.exit(); } } WindowEvent::RedrawRequested => { profiling::scope!("RedrawRequested"); - if let Err(err) = self.update() { + if let Err(err) = self.update(event_loop) { log::error!("{err}"); event_loop.exit(); return; } - if self.state.should_exit { - self.handle_event(AppEvent::Exit); - event_loop.exit(); - return; - } - + let mut inhibit_elision = false; if self.needs_reconfigure { if let Some(ref mut gfx) = self.gfx_context { let size = gfx.window.inner_size(); gfx.resize(size.width, size.height); + // resizing recreates the blip texture (previous frame) thus elision needs to + // be inhibited for at least one frame. + inhibit_elision = true; } self.needs_reconfigure = false; - // Render at least one frame after reconfigure - self.force_render = true; } - let is_focused = self.state.window.is_focused; - let is_hovered = self.state.window.is_hovered; - let should_render = is_focused || is_hovered || self.force_render; + let FrameOutput { + render_job, + request_redraw, + } = match self.frame(inhibit_elision) { + Ok(frame_output) => frame_output, + Err(err) => { + log::error!("{err}"); + event_loop.exit(); + return; + } + }; - if should_render { - let FrameOutput { - render_job, - should_continue, - } = match self.frame() { - Ok(frame_output) => frame_output, + if let Some(ref mut gfx) = self.gfx_context { + match gfx.render(render_job) { + Ok(_) => {} Err(err) => { - log::error!("{err}"); - event_loop.exit(); - return; - } - }; - - if let Some(ref mut gfx) = self.gfx_context { - match gfx.render(render_job, self.state.window.scale_factor()) { - Ok(_) => { - self.force_render = should_continue; - - if is_focused || is_hovered || should_continue { - self.state.window.request_redraw(); - } - } - Err(err) => { - log::error!("Unable to render: {err}"); - } + log::error!("Unable to render: {err}"); } } } + if request_redraw { + self.request_redraw(); + } + profiling::finish_frame!(); } WindowEvent::Resized(size) => { - self.state.window.size = PhysicalSize::new(size.width, size.height); self.needs_reconfigure = true; + self.handle_event(StageEvent::Resized(PhysicalSize::new( + size.width, + size.height, + ))); + self.request_redraw(); } WindowEvent::Focused(focused) => { - self.state.window.is_focused = focused; + self.handle_event(StageEvent::FocusChanged(focused)); if focused { - self.state.window.request_redraw(); + self.request_redraw(); } else { - // Clear inputs on lost focus to avoid "stuck" keys on Wayland - // systems. - self.state.input.clear_pressed(); + // Clear inputs on lost focus to avoid "stuck" keys on Wayland systems. + self.stage.clear_pressed(); } } WindowEvent::ScaleFactorChanged { scale_factor, .. } => { - self.state.window.set_scale_factor(scale_factor as f32); + self.handle_event(StageEvent::ScaleFactorChanged(scale_factor)); + self.request_redraw(); } WindowEvent::KeyboardInput { event, .. } => { let state = event.state; - // update input state - self.state - .input - .set_key_pressed(event.logical_key.clone(), state.is_pressed()); - // forward KeyUp/KeyDown events - let app_event = match state { - ElementState::Pressed => AppEvent::KeyDown { + let stage_event = match state { + ElementState::Pressed => StageEvent::KeyDown { key: event.logical_key.clone(), }, - ElementState::Released => AppEvent::KeyUp { + ElementState::Released => StageEvent::KeyUp { key: event.logical_key.clone(), }, }; - self.handle_event(app_event); + self.handle_event(stage_event); // handle text input if let Some(text) = event.text_with_all_modifiers() && state.is_pressed() { for ch in text.chars() { - let event = AppEvent::CharacterInput { ch }; + let event = StageEvent::CharacterInput { ch }; self.handle_event(event); } } + self.request_redraw(); } WindowEvent::ModifiersChanged(modifiers) => { - self.state.input.key_modifiers = modifiers.state(); + self.handle_event(StageEvent::ModifiersChanged { + state: modifiers.state(), + }); + self.request_redraw(); } WindowEvent::MouseInput { state, button, .. } => { - let is_double_click = self - .state - .input - .set_mouse_pressed(button, state.is_pressed()); - let event = match state { - ElementState::Pressed => AppEvent::MouseDown { - button, - is_double_click, - }, - ElementState::Released => AppEvent::MouseUp { button }, + ElementState::Pressed => StageEvent::MouseDown { button }, + ElementState::Released => StageEvent::MouseUp { button }, }; self.handle_event(event); + self.request_redraw(); } WindowEvent::CursorMoved { position, .. } => { let pos = PhysicalPoint::new(position.x as f32, position.y as f32); - self.state.set_mouse_pos(pos); + self.handle_event(StageEvent::MouseMoved { pos }); + self.request_redraw(); } WindowEvent::CursorEntered { .. } => { - self.state.window.is_hovered = true; - self.state.window.request_redraw(); + self.handle_event(StageEvent::HoverChanged(true)); + self.request_redraw(); } WindowEvent::CursorLeft { .. } => { - self.state.window.is_hovered = false; + self.handle_event(StageEvent::HoverChanged(false)); } WindowEvent::MouseWheel { delta, .. } => { let delta = match delta { @@ -330,8 +309,8 @@ impl ApplicationHandler for App { y as f32 } }; - let event = AppEvent::MouseWheel { delta }; - self.handle_event(event); + self.handle_event(StageEvent::MouseWheel { delta }); + self.request_redraw(); } _ => {} } diff --git a/src/batcher.rs b/src/batcher.rs index b0718ca..22770f0 100644 --- a/src/batcher.rs +++ b/src/batcher.rs @@ -68,6 +68,7 @@ impl BatchBuilder { pub fn build_render_job( commands: &[DrawCommand], textures_delta: TexturesDelta, + scale_factor: f32, max_slots: u32, ) -> RenderJob { profiling::scope!("build_render_job"); @@ -83,6 +84,7 @@ pub fn build_render_job( indices, batches, textures_delta, + scale_factor, }; }; @@ -159,5 +161,6 @@ pub fn build_render_job( indices, batches, textures_delta, + scale_factor, }; } diff --git a/src/gfx.rs b/src/gfx.rs index 22af340..a28e727 100644 --- a/src/gfx.rs +++ b/src/gfx.rs @@ -147,11 +147,7 @@ impl GraphicsContext { } } - pub fn render( - &mut self, - render_job: Option, - scale_factor: f32, - ) -> anyhow::Result<()> { + pub fn render(&mut self, render_job: Option) -> anyhow::Result<()> { profiling::scope!("render"); if !self.is_surface_configured { @@ -198,7 +194,7 @@ impl GraphicsContext { &self.queue, &render_job, screen_size, - scale_factor, + render_job.scale_factor, ); let rpass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { @@ -228,7 +224,7 @@ impl GraphicsContext { &mut rpass.forget_lifetime(), &render_job, screen_size, - scale_factor, + render_job.scale_factor, ); self.renderer.free_textures(&render_job.textures_delta); diff --git a/src/input.rs b/src/input.rs index d015fa1..9fb1c89 100644 --- a/src/input.rs +++ b/src/input.rs @@ -34,17 +34,17 @@ pub struct InputState { impl InputState { /// Updates [`Self::keys_pressed`] based on `is_pressed`. - pub fn set_key_pressed(&mut self, key: Key, is_pressed: bool) { + pub fn set_key_pressed(&mut self, key: &Key, is_pressed: bool) { if is_pressed { - self.keys_pressed.insert(key); + self.keys_pressed.insert(key.clone()); } else { - self.keys_pressed.remove(&key); + self.keys_pressed.remove(key); } } /// Returns if the key is pressed (`true`) or not pressed (`false`). - pub fn key_pressed(&self, key: Key) -> bool { - self.keys_pressed.contains(&key) + pub fn key_pressed(&self, key: &Key) -> bool { + self.keys_pressed.contains(key) } /// Updates [`Self::mouse_pressed`](field@Self::mouse_pressed) based on provided diff --git a/src/installer.rs b/src/installer.rs index acd6cfb..7285e78 100644 --- a/src/installer.rs +++ b/src/installer.rs @@ -1,29 +1,32 @@ use crate::{ - app::AppState, args::Game, color::Srgba, dpi::{LogicalPoint, LogicalRect}, draw_commands::DrawCommand, - fonts::{Alignment, FontStyle, LayoutJob}, + fonts::{Alignment, FontStyle, Fonts, LayoutJob}, installer::download::{ DownloadEvent, ExtractionRule, build_client, download_and_extract_tarball, download_file_to_disk, fetch_file_contents, }, - mode::{AppEvent, ModeFrameOutput, ModeTransition}, renderer::textures::TextureId, + stage::{StageEvent, StageFrameOutput, StageTransition}, util::replace_in_matching_lines, + window::WindowState, }; use parley::{FontFamily, FontFamilyName, GenericFamily}; use regex::Regex; use std::{ + cell::RefCell, fs, path::Path, + rc::Rc, sync::{ - LazyLock, + Arc, LazyLock, mpsc::{self, Receiver, TryRecvError}, }, thread, }; +use winit::window::Window; mod download; @@ -40,16 +43,15 @@ enum Progress { Error(anyhow::Error), } -/// Execution mode in which initial installation of PoB is performed. -/// -/// Immediately transitions into PoB mode if already installed. -pub struct InstallMode { +pub struct Installer { progress_rx: Option>, status: String, + window_state: WindowState, + fonts: Rc>, } -impl InstallMode { - pub fn new(game: Game) -> Self { +impl Installer { + pub fn new(game: Game, fonts: Rc>) -> Self { let script_dir = game.script_dir(); let (progress_tx, progress_rx) = mpsc::channel(); @@ -64,25 +66,28 @@ impl InstallMode { Self { progress_rx: Some(progress_rx), status: String::from("Starting installation..."), + window_state: WindowState::default(), + fonts, } } - pub fn frame(&mut self, app_state: &mut AppState) -> anyhow::Result { - let draw_commands = self.draw_current_progress(app_state); + pub fn frame(&mut self) -> anyhow::Result { + let draw_commands = self.draw_current_progress(); - Ok(ModeFrameOutput { + Ok(StageFrameOutput { draw_commands, can_elide: false, - should_continue: true, + request_redraw: true, + scale_factor: self.window_state.scale_factor(), }) } - pub fn update(&mut self, _app_state: &mut AppState) -> anyhow::Result> { + pub fn update(&mut self) -> anyhow::Result> { if let Some(progress_rx) = &self.progress_rx { loop { match progress_rx.try_recv() { Ok(Progress::Status(msg)) => self.status = msg, - Ok(Progress::Complete) => return Ok(Some(ModeTransition::PoB)), + Ok(Progress::Complete) => return Ok(Some(StageTransition::ToMain)), Ok(Progress::Error(err)) => { return Err(anyhow::anyhow!("Installation failed: {err}")); } @@ -99,18 +104,25 @@ impl InstallMode { Ok(None) } - pub fn handle_event( - &mut self, - _app_state: &mut AppState, - _event: AppEvent, - ) -> anyhow::Result<()> { - Ok(()) + pub fn handle_event(&mut self, event: StageEvent) -> anyhow::Result> { + match event { + StageEvent::Resized(size) => self.window_state.size = size, + StageEvent::ScaleFactorChanged(factor) => { + self.window_state.set_scale_factor(factor as f32) + } + _ => {} + } + Ok(None) } - fn draw_current_progress(&self, app_state: &mut AppState) -> Vec { + pub fn set_window(&mut self, window: Arc) { + self.window_state.set_window(window); + } + + fn draw_current_progress(&self) -> Vec { let mut draw_commands = Vec::new(); - let screen_size = app_state.window.logical_size().cast::(); + let screen_size = self.window_state.logical_size().cast::(); let pos = LogicalPoint::new(screen_size.width / 2.0, screen_size.height / 2.0); let mut job = LayoutJob::new( @@ -124,7 +136,10 @@ impl InstallMode { job.append(&self.status, Srgba::WHITE); - let layout = app_state.fonts.layout(job, app_state.window.scale_factor()); + let layout = self + .fonts + .borrow_mut() + .layout(job, self.window_state.scale_factor()); for glyph in &layout.glyphs { draw_commands.push(DrawCommand { positions: glyph.rect.translate(pos.to_vector()).into(), @@ -133,7 +148,7 @@ impl InstallMode { // font atlas always lives at default texture ID texture_id: TextureId::default(), texture_layer_idx: glyph.layer_idx, - clip_rect: LogicalRect::from_size(app_state.window.logical_size().cast()), + clip_rect: LogicalRect::from_size(screen_size), }); } diff --git a/src/lua.rs b/src/lua.rs deleted file mode 100644 index 4c77e5b..0000000 --- a/src/lua.rs +++ /dev/null @@ -1,329 +0,0 @@ -use crate::{ - api::{self, get_callback}, - app::AppState, - args::Args, - draw_commands::DrawCommandRecorder, - fonts::Fonts, - input::InputState, - pob::PoBState, - renderer::textures::WrappedTextureManager, - subscript::{NativeMultiValue, SubscriptManager, SubscriptResult, register_subscript_globals}, - util::change_working_directory, - window::WindowState, -}; -use clap::Parser; -use mlua::{Function, Lua, Result as LuaResult, Table, thread::ThreadStatus}; -use std::{ - cell::{Cell, RefCell}, - path::{Path, PathBuf}, - rc::Rc, -}; -use winit::keyboard::SmolStr; - -macro_rules! ctx_accessor { - ($field:ident: & $ty:ty) => { - pub fn $field(&self) -> &$ty { - let ptr = self.$field.get(); - assert!(!ptr.is_null()); - unsafe { &*ptr } - } - }; - - ($field:ident: &mut $ty:ty) => { - #[allow(clippy::mut_from_ref)] - pub fn $field(&self) -> &mut $ty { - let ptr = self.$field.get(); - assert!(!ptr.is_null()); - unsafe { &mut *ptr } - } - }; -} - -/// A collection of pointers needed by the API funtions. -/// -/// Before executing any lua code, we need to "plug" the references into -/// the Context and "unplug" them afterwards. -pub struct Context { - window: Cell<*mut WindowState>, - input: Cell<*const InputState>, - fonts: Cell<*mut Fonts>, - texture_manager: Cell<*mut WrappedTextureManager>, - script_dir: Cell<*const PathBuf>, - current_working_dir: Cell<*mut PathBuf>, - recorder: Cell<*mut DrawCommandRecorder>, - needs_restart: Cell<*mut bool>, - should_exit: Cell<*mut bool>, - is_dpi_aware: Cell<*mut bool>, -} - -impl Context { - pub fn new() -> Self { - Self { - window: Cell::new(std::ptr::null_mut()), - input: Cell::new(std::ptr::null()), - fonts: Cell::new(std::ptr::null_mut()), - texture_manager: Cell::new(std::ptr::null_mut()), - script_dir: Cell::new(std::ptr::null()), - current_working_dir: Cell::new(std::ptr::null_mut()), - recorder: Cell::new(std::ptr::null_mut()), - needs_restart: Cell::new(std::ptr::null_mut()), - should_exit: Cell::new(std::ptr::null_mut()), - is_dpi_aware: Cell::new(std::ptr::null_mut()), - } - } - - pub fn set(&self, ctx: &mut PoBContext) { - self.window.set(&mut ctx.app.window); - self.input.set(&ctx.app.input); - self.fonts.set(&mut ctx.app.fonts); - self.texture_manager.set(&mut ctx.app.texture_manager); - self.script_dir.set(&ctx.app.script_dir); - self.current_working_dir - .set(&mut ctx.pob.current_working_dir); - self.recorder.set(&mut ctx.pob.recorder); - self.needs_restart.set(&mut ctx.pob.needs_restart); - self.should_exit.set(&mut ctx.app.should_exit); - self.is_dpi_aware.set(&mut ctx.pob.is_dpi_aware); - } - - pub fn clear(&self) { - self.window.set(std::ptr::null_mut()); - self.input.set(std::ptr::null()); - self.fonts.set(std::ptr::null_mut()); - self.texture_manager.set(std::ptr::null_mut()); - self.script_dir.set(std::ptr::null()); - self.current_working_dir.set(std::ptr::null_mut()); - self.recorder.set(std::ptr::null_mut()); - self.needs_restart.set(std::ptr::null_mut()); - self.should_exit.set(std::ptr::null_mut()); - self.is_dpi_aware.set(std::ptr::null_mut()); - } - - ctx_accessor!(window: &mut WindowState); - ctx_accessor!(input: &InputState); - ctx_accessor!(fonts: &mut Fonts); - ctx_accessor!(texture_manager: &mut WrappedTextureManager); - ctx_accessor!(script_dir: &PathBuf); - ctx_accessor!(current_working_dir: &mut PathBuf); - ctx_accessor!(recorder: &mut DrawCommandRecorder); - ctx_accessor!(needs_restart: &mut bool); - ctx_accessor!(should_exit: &mut bool); - ctx_accessor!(is_dpi_aware: &mut bool); -} - -pub enum PoBEvent { - Init, - Exit, - Frame, - KeyDown(SmolStr, bool), - KeyUp(SmolStr), - Char(char), - SubFinished { - id: u64, - return_values: NativeMultiValue, - }, - SubError { - id: u64, - error: String, - }, -} - -impl std::fmt::Display for PoBEvent { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self { - Self::Init => write!(f, "Init"), - Self::Exit => write!(f, "Exit"), - Self::Frame => write!(f, "Frame"), - Self::KeyDown(_, _) => write!(f, "KeyDown"), - Self::KeyUp(_) => write!(f, "KeyUp"), - Self::Char(_) => write!(f, "Char"), - Self::SubFinished { .. } => write!(f, "SubFinished"), - Self::SubError { .. } => write!(f, "SubError"), - } - } -} - -pub struct PoBContext<'a> { - pub app: &'a mut AppState, - pub pob: &'a mut PoBState, -} - -impl<'a> PoBContext<'a> { - pub fn new(app_state: &'a mut AppState, pob_state: &'a mut PoBState) -> Self { - Self { - app: app_state, - pob: pob_state, - } - } -} - -/// Lua instance that runs the PoB application code and manages subscripts. -pub struct LuaInstance { - lua: Lua, - subscript_manager: Rc>, -} - -impl LuaInstance { - pub fn new(script_dir: &PathBuf) -> anyhow::Result { - let subscript_manager = Rc::new(RefCell::new(SubscriptManager::new(script_dir.to_owned()))); - - let lua = Self::create_lua_state(script_dir)?; - register_subscript_globals(&lua, &subscript_manager)?; - - Ok(Self { - lua, - subscript_manager, - }) - } - - fn create_lua_state(script_dir: &Path) -> LuaResult { - // SAFETY: use `unsafe_new` to allow loading of C modules - let lua = unsafe { Lua::unsafe_new() }; - - // expose import url to lua - let args = Args::parse(); - let args_table = lua.create_sequence_from(std::iter::once(args.import_url))?; - lua.globals().set("arg", args_table)?; - - Self::register_package_paths(&lua, script_dir)?; - - // register context - let ctx = Context::new(); - lua.set_app_data(ctx); - - // register callbacks - api::register_globals(&lua)?; - - Ok(lua) - } - - /// Loads and executes PoB's Launch.lua script - pub fn launch(&self, pob_ctx: &mut PoBContext) -> LuaResult<()> { - let ctx = self.lua.app_data_ref::().unwrap(); - ctx.set(pob_ctx); - - let script_dir = pob_ctx.app.script_dir.as_path(); - change_working_directory(script_dir)?; - self.load(script_dir.join("Launch.lua")).exec()?; - - ctx.clear(); - Ok(()) - } - - pub fn restart(&mut self, ctx: &mut PoBContext) -> LuaResult<()> { - self.lua = Self::create_lua_state(&ctx.app.script_dir)?; - register_subscript_globals(&self.lua, &self.subscript_manager)?; - self.launch(ctx)?; - Ok(()) - } - - /// Run functions for subscripts and handle their completion/failure. - pub fn handle_subscripts(&self, pob_ctx: &mut PoBContext) { - profiling::scope!("handle_subscripts"); - - let ctx = self.lua.app_data_ref::().unwrap(); - ctx.set(pob_ctx); - let subscript_events = self.subscript_manager.borrow_mut().process(self); - ctx.clear(); - - // Handle finished/errored subscripts. - for event in subscript_events { - match event { - SubscriptResult::SubscriptFinished { id, return_values } => { - self.handle_event(PoBEvent::SubFinished { id, return_values }, pob_ctx) - .unwrap(); - } - SubscriptResult::SubscriptError { id, error } => { - self.handle_event(PoBEvent::SubError { id, error }, pob_ctx) - .unwrap(); - } - } - } - } - - pub fn has_running_subscripts(&self) -> bool { - self.subscript_manager.borrow().has_running_subscripts() - } - - pub fn has_active_coroutine(&self) -> bool { - self.get_coroutines().is_ok_and(|coroutines| { - coroutines.pairs::().any(|pair| { - pair.is_ok_and(|(thread, _)| { - matches!( - thread.status(), - ThreadStatus::Resumable | ThreadStatus::Running - ) - }) - }) - }) - } - - fn get_coroutines(&self) -> LuaResult { - let coroutine_module: Table = self.lua.globals().get("coroutine")?; - let list_func: Function = coroutine_module.get("_list")?; - list_func.call::
(()) - } - - pub fn can_exit(&self, pob_ctx: &mut PoBContext) -> bool { - let ctx = self.lua.app_data_ref::().unwrap(); - ctx.set(pob_ctx); - - let can_exit = get_callback(&self.lua, "CanExit") - .and_then(|f| f.call(())) - .unwrap_or(true); - - ctx.clear(); - can_exit - } - - pub fn handle_event(&self, event: PoBEvent, pob_ctx: &mut PoBContext) -> LuaResult<()> { - profiling::scope!("handle_event", format!("{}", event)); - - // "Plug" references into context - let ctx = self.lua.app_data_ref::().unwrap(); - ctx.set(pob_ctx); - - // Call event handler in PoB application code - let handler_result = match event { - PoBEvent::Init => get_callback(&self.lua, "OnInit")?.call::<()>(()), - PoBEvent::Exit => get_callback(&self.lua, "OnExit")?.call::<()>(()), - PoBEvent::Frame => get_callback(&self.lua, "OnFrame")?.call::<()>(()), - PoBEvent::KeyDown(key, double_click) => { - get_callback(&self.lua, "OnKeyDown")?.call::<()>((key.as_str(), double_click)) - } - PoBEvent::KeyUp(key) => get_callback(&self.lua, "OnKeyUp")?.call::<()>(key.as_str()), - PoBEvent::Char(ch) => get_callback(&self.lua, "OnChar")?.call::<()>(ch), - PoBEvent::SubFinished { id, return_values } => { - get_callback(&self.lua, "OnSubFinished")?.call::<()>((id, return_values)) - } - PoBEvent::SubError { id, error } => { - get_callback(&self.lua, "OnSubError")?.call::<()>((id, error)) - } - }; - - // "Unplug" references from context - ctx.clear(); - - handler_result - } - - /// Adds "${script_dir}/lua" to package path - pub fn register_package_paths(lua: &Lua, script_dir: &Path) -> LuaResult<()> { - let package: Table = lua.globals().get("package")?; - let mut package_path: String = package.get("path")?; - package_path.push(';'); - package_path.push_str(script_dir.join("lua/?.lua").to_str().unwrap()); - package_path.push(';'); - package_path.push_str(script_dir.join("lua/?/init.lua").to_str().unwrap()); - package.set("path", package_path)?; - - Ok(()) - } -} - -impl std::ops::Deref for LuaInstance { - type Target = Lua; - fn deref(&self) -> &Self::Target { - &self.lua - } -} diff --git a/src/main.rs b/src/main.rs index c277150..0b81fe6 100644 --- a/src/main.rs +++ b/src/main.rs @@ -3,7 +3,6 @@ use clap::Parser; use std::path::{Path, PathBuf}; use winit::event_loop::EventLoop; -mod api; mod app; mod args; mod batcher; @@ -15,12 +14,10 @@ mod fonts; mod gfx; mod input; mod installer; -mod lua; mod math; -mod mode; mod pob; mod renderer; -mod subscript; +mod stage; mod util; mod window; mod worker_pool; diff --git a/src/mode.rs b/src/mode.rs deleted file mode 100644 index b70369c..0000000 --- a/src/mode.rs +++ /dev/null @@ -1,73 +0,0 @@ -use crate::{app::AppState, draw_commands::DrawCommand, installer::InstallMode, pob::PoBMode}; -use winit::{event::MouseButton, keyboard::Key}; - -pub enum AppEvent { - KeyDown { - key: Key, - }, - KeyUp { - key: Key, - }, - MouseDown { - button: MouseButton, - is_double_click: bool, - }, - MouseUp { - button: MouseButton, - }, - MouseWheel { - delta: f32, - }, - CharacterInput { - ch: char, - }, - Exit, -} - -/// Represents the transition to another mode -pub enum ModeTransition { - PoB, -} - -pub struct ModeFrameOutput { - pub draw_commands: Vec, - pub can_elide: bool, - /// Indicates that this should be redrawn again next frame even if user is not interacting with - /// window - pub should_continue: bool, -} - -pub enum AppMode { - Install(InstallMode), - PoB(PoBMode), -} - -impl AppMode { - pub fn frame(&mut self, state: &mut AppState) -> anyhow::Result { - match self { - Self::Install(mode) => mode.frame(state), - Self::PoB(mode) => mode.frame(state), - } - } - - pub fn update(&mut self, state: &mut AppState) -> anyhow::Result> { - match self { - Self::Install(mode) => mode.update(state), - Self::PoB(mode) => mode.update(state), - } - } - - pub fn handle_event(&mut self, state: &mut AppState, event: AppEvent) -> anyhow::Result<()> { - match self { - Self::Install(mode) => mode.handle_event(state, event), - Self::PoB(mode) => mode.handle_event(state, event), - } - } - - pub fn can_exit(&mut self, state: &mut AppState) -> bool { - match self { - Self::Install(_) => true, - Self::PoB(mode) => mode.can_exit(state), - } - } -} diff --git a/src/pob.rs b/src/pob.rs index a9a613c..c091cf2 100644 --- a/src/pob.rs +++ b/src/pob.rs @@ -1,161 +1,386 @@ -use crate::{ - app::AppState, - dpi::{LogicalRect, LogicalSize}, - draw_commands::DrawCommandRecorder, - input::{key_as_str, mousebutton_as_str}, - lua::{LuaInstance, PoBContext, PoBEvent}, - mode::{AppEvent, ModeFrameOutput, ModeTransition}, +use clap::Parser; +use mlua::{ + AppDataRef, AppDataRefMut, Function, Lua, Result as LuaResult, Table, thread::ThreadStatus, }; -use std::path::PathBuf; +use winit::window::Window; -pub struct PoBState { +use crate::{ + args::Args, + dpi::{ConvertToLogical, PhysicalPoint}, + draw_commands::DrawCommandRecorder, + fonts::Fonts, + input::{InputState, key_as_str, mousebutton_as_str}, + pob::{ + api::call_callback, + subscript::{NativeMultiValue, SubscriptManager, SubscriptResult}, + }, + renderer::textures::WrappedTextureManager, + stage::{StageEvent, StageFrameOutput, StageTransition}, + util::change_working_directory, + window::WindowState, +}; +use std::{ + cell::RefCell, + path::{Path, PathBuf}, + rc::Rc, + sync::Arc, +}; + +mod api; +mod subscript; + +/// Holds all state shared between Rust and the API functions exposed to Lua. +/// +/// Accessed via `lua.app_data_ref::()`/`app_data_mut::()`. +pub struct Context { + pub input_state: InputState, + pub window_state: WindowState, + /// Collects draw commands issued by API functions pub recorder: DrawCommandRecorder, + pub fonts: Rc>, + pub texture_manager: Rc>, + pub subscript_manager: RefCell, + /// Directory containing the PoB Lua scripts + pub script_dir: PathBuf, pub current_working_dir: PathBuf, + /// Set by Lua to request a full Lua restart pub needs_restart: bool, + /// Set by Lua to request application shutdown + pub should_exit: bool, pub is_dpi_aware: bool, } -/// Execution mode in which PoB's application code is run. +impl Context { + pub fn new( + script_dir: &Path, + fonts: Rc>, + texture_manager: Rc>, + ) -> Self { + Self { + input_state: InputState::default(), + window_state: WindowState::default(), + recorder: DrawCommandRecorder::default(), + fonts, + texture_manager, + subscript_manager: RefCell::new(SubscriptManager::default()), + script_dir: script_dir.to_owned(), + current_working_dir: PathBuf::default(), + needs_restart: false, + should_exit: false, + is_dpi_aware: false, + } + } + + /// Resizes the recorder's viewport to match the current window size. + /// Call at the start of every frame before any draw calls are recorded. + pub fn set_recorder_viewport_to_window_size(&mut self) { + self.recorder + .set_viewport_from_size(self.window_state.logical_size()); + } + + fn set_mouse_pos(&mut self, pos: PhysicalPoint) { + self.input_state + .set_mouse_pos(pos.to_logical(self.window_state.scale_factor())); + } +} + +/// Represents the interface to Path of Building's Lua code. /// -/// It forwards app events to PoB's application event handlers and outputs -/// the draw primitives created by PoB each frame. -pub struct PoBMode { - lua_instance: LuaInstance, - state: PoBState, +/// Exposes API, fowards events to Path of Building's event handlers, and manages subscripts. +pub struct PathOfBuilding { + lua: Lua, + /// Hash of the previous frame's draw commands. Used to skip rerendering identical frames. previous_layers_hash: u64, } -impl PoBMode { - pub fn new(app_state: &mut AppState) -> anyhow::Result { - let mut state = PoBState { - recorder: DrawCommandRecorder::default(), - current_working_dir: PathBuf::default(), - needs_restart: false, - is_dpi_aware: false, - }; +impl PathOfBuilding { + pub fn new( + script_dir: &Path, + fonts: Rc>, + texture_manager: Rc>, + ) -> anyhow::Result { + let ctx = Context::new(script_dir, fonts, texture_manager); + let lua = Self::create_lua(ctx)?; - let lua_instance = LuaInstance::new(&app_state.script_dir)?; - - let mut pob_ctx = PoBContext::new(app_state, &mut state); - lua_instance.launch(&mut pob_ctx)?; - lua_instance.handle_event(PoBEvent::Init, &mut pob_ctx)?; + Self::launch(&lua, script_dir)?; Ok(Self { - lua_instance, - state, + lua, previous_layers_hash: Default::default(), }) } - pub fn frame(&mut self, app_state: &mut AppState) -> anyhow::Result { - profiling::scope!("frame"); + /// Builds a `Lua` state with package paths, context, and all API functions registered. + fn create_lua(ctx: Context) -> LuaResult { + // `unsafe_new` needed to allow loading of C modules + let lua = unsafe { Lua::unsafe_new() }; - // reset layers and viewport - self.state.recorder.reset(); - self.reset_viewport(app_state.window.logical_size()); + // expose import url to lua + let args = Args::parse(); + let args_table = lua.create_sequence_from(std::iter::once(args.import_url))?; + lua.globals().set("arg", args_table)?; - let mut ctx = PoBContext::new(app_state, &mut self.state); + Self::register_package_paths(&lua, &ctx.script_dir)?; - // handle subscripts - self.lua_instance.handle_subscripts(&mut ctx); + // make context accessible to API functions + lua.set_app_data(ctx); - // run PoB's draw code. - // this will "fill up" up the layers with draw commands - self.lua_instance.handle_event(PoBEvent::Frame, &mut ctx)?; + // register API functions + api::register_globals(&lua)?; - // check if draw prmitives are identical to primitives from last frame - let (layers_hash, layers) = self.state.recorder.finish(); - //let layers_hash = self.state.layers.get_hash(); - let identical = layers_hash == self.previous_layers_hash; - self.previous_layers_hash = layers_hash; - - let has_active_subscript = self.lua_instance.has_running_subscripts(); - let has_active_coroutine = self.lua_instance.has_active_coroutine(); - let should_continue = has_active_subscript || has_active_coroutine; - - Ok(ModeFrameOutput { - draw_commands: layers.values().flatten().copied().collect(), - can_elide: identical, - should_continue, - }) + Ok(lua) } - pub fn update(&mut self, app_state: &mut AppState) -> anyhow::Result> { - if self.state.needs_restart { - let mut ctx = PoBContext::new(app_state, &mut self.state); - self.lua_instance.restart(&mut ctx)?; - self.lua_instance.handle_event(PoBEvent::Init, &mut ctx)?; - self.state.needs_restart = false; + /// Adds "${script_dir}/lua" to package path + pub fn register_package_paths(lua: &Lua, script_dir: &Path) -> LuaResult<()> { + let package: Table = lua.globals().get("package")?; + let mut package_path: String = package.get("path")?; + package_path.push(';'); + package_path.push_str(script_dir.join("lua/?.lua").to_str().unwrap()); + package_path.push(';'); + package_path.push_str(script_dir.join("lua/?/init.lua").to_str().unwrap()); + package.set("path", package_path)?; + Ok(()) + } + + /// Loads and runs `Launch.lua`, then calls PoB's `OnInit` handler. + fn launch(lua: &Lua, script_dir: &Path) -> LuaResult<()> { + change_working_directory(script_dir)?; + lua.load(script_dir.join("Launch.lua")).exec()?; + call_callback::<(), ()>(lua, "OnInit", ())?; + Ok(()) + } + + /// Rebuilds the Lua instance from scratch. Preserves the current `Context`. + fn restart(&mut self) -> LuaResult<()> { + // move context out of current lua instance... + let mut ctx = self.lua.remove_app_data::().unwrap(); + let script_dir = ctx.script_dir.to_owned(); + ctx.needs_restart = false; + + // and move it into new instance + self.lua = Self::create_lua(ctx)?; + Self::launch(&self.lua, &script_dir)?; + + Ok(()) + } + + /// Handles events by updating context and forwarding them to PoB's event handlers. + pub fn handle_event(&mut self, event: StageEvent) -> anyhow::Result> { + match event { + StageEvent::KeyDown { key } => { + self.ctx_mut().input_state.set_key_pressed(&key, true); + + if let Some(key) = key_as_str(key) { + call_callback::<(&str, bool), ()>( + &self.lua, + "OnKeyDown", + (key.as_str(), false), + )?; + } + } + StageEvent::KeyUp { key } => { + self.ctx_mut().input_state.set_key_pressed(&key, false); + + if let Some(key) = key_as_str(key) { + call_callback::<&str, ()>(&self.lua, "OnKeyUp", key.as_str())?; + } + } + StageEvent::ModifiersChanged { state } => { + self.ctx_mut().input_state.key_modifiers = state; + } + StageEvent::CharacterInput { ch } => { + let ch = if ch.is_ascii() { ch } else { '?' }; + call_callback::(&self.lua, "OnChar", ch)?; + } + StageEvent::MouseDown { button } => { + let is_double_click = self.ctx_mut().input_state.set_mouse_pressed(button, true); + + if let Some(button) = mousebutton_as_str(button) { + call_callback::<(&str, bool), ()>( + &self.lua, + // PoB treats mouse buttons as keys + "OnKeyDown", + (button.as_str(), is_double_click), + )?; + } + } + StageEvent::MouseUp { button } => { + self.ctx_mut().input_state.set_mouse_pressed(button, false); + + if let Some(button) = mousebutton_as_str(button) { + call_callback::<&str, ()>( + &self.lua, + // PoB treats mouse buttons as keys + "OnKeyUp", + button.as_str(), + )?; + } + } + StageEvent::MouseWheel { delta } => { + if delta > 0.0 { + call_callback::<(&str, bool), ()>(&self.lua, "OnKeyDown", ("WHEELUP", false))?; + call_callback::<&str, ()>(&self.lua, "OnKeyUp", "WHEELUP")?; + } else if delta < 0.0 { + call_callback::<(&str, bool), ()>( + &self.lua, + "OnKeyDown", + ("WHEELDOWN", false), + )?; + call_callback::<&str, ()>(&self.lua, "OnKeyUp", "WHEELDOWN")?; + } + } + StageEvent::Exit => call_callback(&self.lua, "OnExit", ())?, + StageEvent::MouseMoved { pos } => { + self.ctx_mut().set_mouse_pos(pos); + } + StageEvent::Resized(size) => { + self.ctx_mut().window_state.size = size; + } + StageEvent::ScaleFactorChanged(scale_factor) => { + self.ctx_mut() + .window_state + .set_scale_factor(scale_factor as f32); + } + StageEvent::FocusChanged(focused) => { + self.ctx_mut().window_state.is_focused = focused; + } + StageEvent::HoverChanged(hovered) => { + self.ctx_mut().window_state.is_hovered = hovered; + } } Ok(None) } - pub fn handle_event( - &mut self, - app_state: &mut AppState, - event: AppEvent, - ) -> anyhow::Result<()> { - let mut ctx = PoBContext::new(app_state, &mut self.state); + /// Applies any pending restart/exit requests set by Lua via `Context`. + /// Should be called once before `frame()`. + pub fn update(&mut self) -> anyhow::Result> { + let (needs_restart, should_exit) = { + let ctx = self.ctx(); + (ctx.needs_restart, ctx.should_exit) + }; - match event { - AppEvent::KeyDown { key } => { - if let Some(key_string) = key_as_str(key) { - let pob_event = PoBEvent::KeyDown(key_string, false); - self.lua_instance.handle_event(pob_event, &mut ctx)?; + if needs_restart { + self.restart()?; + } + + if should_exit { + return Ok(Some(StageTransition::ToShutdown)); + } + + Ok(None) + } + + /// Runs one PoB frame. + /// + /// Resets the draw command recorder, advances subscripts, calls `OnFrame` (which issues draw + /// calls via the API), then collects the resulting draw commands. + /// + /// Returns `can_elide: true` if the output is identical to the previous frame, letting the + /// caller skip rerendering. + pub fn frame(&mut self) -> anyhow::Result { + profiling::scope!("frame"); + + { + let mut ctx = self.ctx_mut(); + ctx.recorder.reset(); + ctx.set_recorder_viewport_to_window_size(); + } + + self.handle_subscripts()?; + + call_callback::<(), ()>(&self.lua, "OnFrame", ())?; + + let ctx = self.lua.app_data_mut::().unwrap(); + + let (layers_hash, layers) = ctx.recorder.finish(); + let identical = layers_hash == self.previous_layers_hash; + self.previous_layers_hash = layers_hash; + + // determine if another redraw needs to be requested after this frame. + // this mirrors SimpleGraphic's behavior. + let is_focused = ctx.window_state.is_focused; + let is_hovered = ctx.window_state.is_hovered; + let has_active_subscript = ctx.subscript_manager.borrow().has_running_subscripts(); + let has_active_coroutine = self.has_active_coroutine(); + let request_redraw = + is_focused || is_hovered || has_active_subscript || has_active_coroutine; + + Ok(StageFrameOutput { + draw_commands: layers.values().flatten().copied().collect(), + can_elide: identical, + request_redraw, + scale_factor: ctx.window_state.scale_factor(), + }) + } + + /// Advances all running subscripts and forwards their results to Lua handlers. + /// Call once per frame. + fn handle_subscripts(&self) -> LuaResult<()> { + profiling::scope!("handle_subscripts"); + + let subscript_events = self.ctx().subscript_manager.borrow_mut().process(&self.lua); + + // Handle finished/errored subscripts. + for event in subscript_events { + match event { + SubscriptResult::SubscriptFinished { id, return_values } => { + call_callback::<(u64, NativeMultiValue), ()>( + &self.lua, + "OnSubFinished", + (id, return_values), + )?; + } + SubscriptResult::SubscriptError { id, error } => { + call_callback::<(u64, String), ()>(&self.lua, "OnSubError", (id, error))?; } } - AppEvent::KeyUp { key } => { - if let Some(key_string) = key_as_str(key) { - let pob_event = PoBEvent::KeyUp(key_string); - self.lua_instance.handle_event(pob_event, &mut ctx)?; - } - } - AppEvent::MouseDown { - button, - is_double_click, - } => { - if let Some(button_string) = mousebutton_as_str(button) { - let pob_event = PoBEvent::KeyDown(button_string, is_double_click); - self.lua_instance.handle_event(pob_event, &mut ctx)?; - } - } - AppEvent::MouseUp { button } => { - if let Some(button_string) = mousebutton_as_str(button) { - let pob_event = PoBEvent::KeyUp(button_string); - self.lua_instance.handle_event(pob_event, &mut ctx)?; - } - } - AppEvent::MouseWheel { delta } => { - if delta > 0.0 { - self.lua_instance - .handle_event(PoBEvent::KeyDown("WHEELUP".into(), false), &mut ctx)?; - self.lua_instance - .handle_event(PoBEvent::KeyUp("WHEELUP".into()), &mut ctx)?; - } else if delta < 0.0 { - self.lua_instance - .handle_event(PoBEvent::KeyDown("WHEELDOWN".into(), false), &mut ctx)?; - self.lua_instance - .handle_event(PoBEvent::KeyUp("WHEELDOWN".into()), &mut ctx)?; - } - } - AppEvent::CharacterInput { ch } => { - let ch = if ch.is_ascii() { ch } else { '?' }; - self.lua_instance - .handle_event(PoBEvent::Char(ch), &mut ctx)?; - } - AppEvent::Exit => self.lua_instance.handle_event(PoBEvent::Exit, &mut ctx)?, } Ok(()) } - pub fn can_exit(&mut self, app_state: &mut AppState) -> bool { - let mut ctx = PoBContext::new(app_state, &mut self.state); - self.lua_instance.can_exit(&mut ctx) + fn has_active_coroutine(&self) -> bool { + self.get_coroutines().is_ok_and(|coroutines| { + coroutines.pairs::().any(|pair| { + pair.is_ok_and(|(thread, _)| { + matches!( + thread.status(), + ThreadStatus::Resumable | ThreadStatus::Running + ) + }) + }) + }) } - fn reset_viewport(&mut self, size: LogicalSize) { - self.state - .recorder - .set_viewport(LogicalRect::from_size(size).cast()); + fn get_coroutines(&self) -> LuaResult
{ + let coroutine_module: Table = self.lua.globals().get("coroutine")?; + let list_func: Function = coroutine_module.get("_list")?; + list_func.call::
(()) + } + + pub fn clear_pressed(&mut self) { + self.ctx_mut().input_state.clear_pressed(); + } + + /// Calls PoB's `CanExit` handler. Used for unsaved changes prompt. + pub fn can_exit(&self) -> bool { + call_callback::<(), bool>(&self.lua, "CanExit", ()).unwrap_or(false) + } + + /// Attaches the render-target window to the context + pub fn set_window(&mut self, window: Arc) { + self.ctx_mut().window_state.set_window(window); + } + + /// Helper for accessing `Context` + #[inline] + fn ctx(&self) -> AppDataRef<'_, Context> { + self.lua.app_data_ref().unwrap() + } + + /// Helper for getting mutable access to `Context` + #[inline] + fn ctx_mut(&self) -> AppDataRefMut<'_, Context> { + self.lua.app_data_mut().unwrap() } } diff --git a/src/api.rs b/src/pob/api.rs similarity index 86% rename from src/api.rs rename to src/pob/api.rs index 262c938..1a1ce9d 100644 --- a/src/api.rs +++ b/src/pob/api.rs @@ -1,6 +1,7 @@ -pub use crate::api::callback::get_callback; +pub use crate::pob::api::callback::{call_callback, get_callback}; use crate::{ - api::{ + pob::Context, + pob::api::{ callback::{get_custom_callback, set_custom_callback, set_main_object}, clipboard::{copy, paste}, compression::{deflate, inflate}, @@ -14,12 +15,12 @@ use crate::{ }, rendering::PoBString, search_handle::new_search_handle, + subscript::{abort_subscript, is_subscript_running, launch_subscript}, window::{ get_dpi_scale_override, get_screen_scale, get_screen_size, set_dpi_scale_override, set_foreground, set_window_title, }, }, - lua::Context, }; use mlua::{IntoLuaMulti, Lua, MultiValue, Result as LuaResult, Variadic}; use std::time::{SystemTime, UNIX_EPOCH}; @@ -34,6 +35,7 @@ mod lua; mod paths; mod rendering; mod search_handle; +mod subscript; mod window; /// Register functions that can be called from lua @@ -108,6 +110,17 @@ pub fn register_globals(lua: &Lua) -> LuaResult<()> { globals.set("LoadModule", lua.create_function(load_module)?)?; globals.set("PLoadModule", lua.create_function(protected_load_module)?)?; + // subscripts + globals.set( + "LaunchSubScript", + lua.create_function_mut(launch_subscript)?, + )?; + globals.set( + "IsSubScriptRunning", + lua.create_function(is_subscript_running)?, + )?; + globals.set("AbortSubScript", lua.create_function(abort_subscript)?)?; + // NOTE: not used by PoB let set_cursor_pos = |_: &Lua, ()| -> LuaResult<()> { unimplemented!() }; let show_cursor = |_: &Lua, ()| -> LuaResult<()> { unimplemented!() }; @@ -135,14 +148,14 @@ fn exit(l: &Lua, exit_msg: Option) -> LuaResult<()> { if let Some(exit_msg) = exit_msg { println!("{exit_msg}"); } - let ctx = l.app_data_ref::().unwrap(); - *ctx.should_exit() = true; + let mut ctx = l.app_data_mut::().unwrap(); + ctx.should_exit = true; Ok(()) } fn restart(l: &Lua, _: ()) -> LuaResult<()> { - let ctx = l.app_data_ref::().unwrap(); - *ctx.needs_restart() = true; + let mut ctx = l.app_data_mut::().unwrap(); + ctx.needs_restart = true; Ok(()) } @@ -154,11 +167,7 @@ fn open_url(l: &Lua, url: String) -> LuaResult { } fn render_init(l: &Lua, features: Variadic) -> LuaResult<()> { - let ctx = l.app_data_ref::().unwrap(); - for feature in features { - if feature == "DPI_AWARE" { - *ctx.is_dpi_aware() = true; - } - } + let mut ctx = l.app_data_mut::().unwrap(); + ctx.is_dpi_aware = features.iter().any(|feat| feat == "DPI_AWARE"); Ok(()) } diff --git a/src/api/callback.rs b/src/pob/api/callback.rs similarity index 87% rename from src/api/callback.rs rename to src/pob/api/callback.rs index 30f8efc..6cfd72d 100644 --- a/src/api/callback.rs +++ b/src/pob/api/callback.rs @@ -1,4 +1,4 @@ -use mlua::{Function, Lua, Result as LuaResult, Table, Value}; +use mlua::{FromLuaMulti, Function, IntoLuaMulti, Lua, Result as LuaResult, Table, Value}; // During initialization, PoB calls `SetMainObject` with a callback table. // Functions defined in this table are used to call back into Lua from Rust. @@ -41,3 +41,12 @@ pub fn get_custom_callback(l: &Lua, name: String) -> LuaResult { let callback_function: Function = callback_table.get(name)?; Ok(callback_function) } + +#[inline] +pub fn call_callback(lua: &Lua, name: &str, args: A) -> LuaResult +where + A: IntoLuaMulti, + R: FromLuaMulti, +{ + get_callback(lua, name)?.call(args) +} diff --git a/src/pob/api/clipboard.rs b/src/pob/api/clipboard.rs new file mode 100644 index 0000000..97f5984 --- /dev/null +++ b/src/pob/api/clipboard.rs @@ -0,0 +1,13 @@ +use crate::pob::Context; +use mlua::{Lua, Result as LuaResult}; + +pub fn copy(l: &Lua, text: String) -> LuaResult<()> { + let mut ctx = l.app_data_mut::().unwrap(); + ctx.window_state.set_clipboard_text(text); + Ok(()) +} + +pub fn paste(l: &Lua, _: ()) -> LuaResult> { + let mut ctx = l.app_data_mut::().unwrap(); + Ok(ctx.window_state.get_clipboard_text()) +} diff --git a/src/api/compression.rs b/src/pob/api/compression.rs similarity index 100% rename from src/api/compression.rs rename to src/pob/api/compression.rs diff --git a/src/api/console.rs b/src/pob/api/console.rs similarity index 100% rename from src/api/console.rs rename to src/pob/api/console.rs diff --git a/src/api/image_handle.rs b/src/pob/api/image_handle.rs similarity index 95% rename from src/api/image_handle.rs rename to src/pob/api/image_handle.rs index 6c33310..5a4f8ac 100644 --- a/src/api/image_handle.rs +++ b/src/pob/api/image_handle.rs @@ -6,7 +6,7 @@ use std::{ use mlua::{Lua, Result as LuaResult, ffi}; use crate::{ - lua::Context, + pob::Context, renderer::textures::{TextureHandle, TextureId, TextureOptions}, }; @@ -245,12 +245,18 @@ unsafe extern "C-unwind" fn image_handle_load(state: *mut ffi::lua_State) -> c_i match &mut handle.texture { Some(texture_handle) => { // Keep the existing TextureHandle and update underlying texture - let _ = - ctx.texture_manager() - .update_texture(texture_handle.id(), path, options, is_async); + let _ = ctx.texture_manager.borrow().update_texture( + texture_handle.id(), + path, + options, + is_async, + ); } None => { - if let Ok(texture_handle) = ctx.texture_manager().load_texture(path, options, is_async) + if let Ok(texture_handle) = ctx + .texture_manager + .borrow() + .load_texture(path, options, is_async) { handle.texture = Some(texture_handle); } diff --git a/src/api/input.rs b/src/pob/api/input.rs similarity index 77% rename from src/api/input.rs rename to src/pob/api/input.rs index 5a74ea0..5ac739d 100644 --- a/src/api/input.rs +++ b/src/pob/api/input.rs @@ -1,12 +1,12 @@ use crate::{ input::{str_as_key, str_as_mousebutton}, - lua::Context, + pob::Context, }; use mlua::{Lua, Result as LuaResult}; pub fn get_cursor_pos(l: &Lua, _: ()) -> LuaResult<(u32, u32)> { let ctx = l.app_data_ref::().unwrap(); - let pos = ctx.input().mouse_pos(); + let pos = ctx.input_state.mouse_pos(); Ok((pos.x as u32, pos.y as u32)) } @@ -14,9 +14,9 @@ pub fn is_key_down(l: &Lua, key_name: String) -> LuaResult { let ctx = l.app_data_ref::().unwrap(); if let Some(key) = str_as_key(&key_name) { - Ok(ctx.input().key_pressed(key)) + Ok(ctx.input_state.key_pressed(&key)) } else if let Some(button) = str_as_mousebutton(&key_name) { - Ok(ctx.input().mouse_pressed(button)) + Ok(ctx.input_state.mouse_pressed(button)) } else { Ok(false) } diff --git a/src/api/lua.rs b/src/pob/api/lua.rs similarity index 74% rename from src/api/lua.rs rename to src/pob/api/lua.rs index 507a7c9..9a1c5cd 100644 --- a/src/api/lua.rs +++ b/src/pob/api/lua.rs @@ -1,4 +1,4 @@ -use crate::{lua::Context, util::change_working_directory}; +use crate::{pob::Context, util::change_working_directory}; use mlua::{Function, IntoLuaMulti, Lua, MultiValue, Result as LuaResult, Value}; use std::env; @@ -12,28 +12,34 @@ pub fn protected_call(l: &Lua, (func, args): (Function, MultiValue)) -> LuaResul } pub fn load_module(l: &Lua, (name, args): (String, MultiValue)) -> LuaResult { - let ctx = l.app_data_ref::().unwrap(); - let mut module_path = ctx.script_dir().join(name); + let script_dir = { + let ctx = l.app_data_ref::().unwrap(); + ctx.script_dir.to_owned() + }; + let mut module_path = script_dir.join(name); if module_path.extension().is_none() { module_path.set_extension("lua"); } let current_dir = env::current_dir()?; - change_working_directory(ctx.script_dir().as_path())?; + change_working_directory(script_dir.as_path())?; let result = l.load(module_path).call::(args); change_working_directory(current_dir)?; result } pub fn protected_load_module(l: &Lua, (name, args): (String, MultiValue)) -> LuaResult { - let ctx = l.app_data_ref::().unwrap(); - let mut module_path = ctx.script_dir().join(name); + let script_dir = { + let ctx = l.app_data_ref::().unwrap(); + ctx.script_dir.to_owned() + }; + let mut module_path = script_dir.join(name); if module_path.extension().is_none() { module_path.set_extension("lua"); } let current_dir = env::current_dir()?; - change_working_directory(ctx.script_dir().as_path())?; + change_working_directory(script_dir.as_path())?; let result = match l.load(module_path).call::(args) { // on success, callers expect a Nil followed by return values Ok(res) => Ok(std::iter::once(Value::Nil).chain(res).collect()), diff --git a/src/api/paths.rs b/src/pob/api/paths.rs similarity index 87% rename from src/api/paths.rs rename to src/pob/api/paths.rs index 254d1aa..4a32385 100644 --- a/src/api/paths.rs +++ b/src/pob/api/paths.rs @@ -2,19 +2,19 @@ use mlua::{IntoLuaMulti, Lua, MultiValue, Result as LuaResult, Value}; use std::{fs, path::PathBuf}; use crate::{ - lua::Context, + pob::Context, util::{change_working_directory, get_executable_dir}, }; pub fn get_user_path(l: &Lua, _: ()) -> LuaResult { let ctx = l.app_data_ref::().unwrap(); - Ok(ctx.script_dir().join("userdata")) + Ok(ctx.script_dir.join("userdata")) } // parent directory of Launch.lua script pub fn get_script_path(l: &Lua, _: ()) -> LuaResult { let ctx = l.app_data_ref::().unwrap(); - Ok(ctx.script_dir().to_owned()) + Ok(ctx.script_dir.to_owned()) } // parent directory of executable @@ -27,14 +27,14 @@ pub fn get_runtime_path(_: &Lua, _: ()) -> LuaResult { pub fn get_work_dir(l: &Lua, _: ()) -> LuaResult { let ctx = l.app_data_ref::().unwrap(); - Ok(ctx.current_working_dir().clone()) + Ok(ctx.current_working_dir.to_owned()) } // NOTE: unused pub fn set_work_dir(l: &Lua, path: String) -> LuaResult<()> { - let ctx = l.app_data_ref::().unwrap(); + let mut ctx = l.app_data_mut::().unwrap(); if change_working_directory(&path).is_ok() { - *ctx.current_working_dir() = path.into(); + ctx.current_working_dir = path.into(); } Ok(()) } diff --git a/src/api/rendering.rs b/src/pob/api/rendering.rs similarity index 93% rename from src/api/rendering.rs rename to src/pob/api/rendering.rs index 104a789..4864dfc 100644 --- a/src/api/rendering.rs +++ b/src/pob/api/rendering.rs @@ -1,10 +1,10 @@ use crate::{ - api::image_handle::image_handle_texture_id, color::Srgba, dpi::{ConvertToLogical, ConvertToPhysical, LogicalPoint}, fonts::{Alignment, FontStyle, LayoutJob}, - lua::Context, math::{Point, Quad, Rect, Size}, + pob::Context, + pob::api::image_handle::image_handle_texture_id, }; use core::ffi::c_int; use mlua::{ @@ -80,7 +80,7 @@ macro_rules! i32_from_stack { unsafe extern "C-unwind" fn set_draw_color(state: *mut ffi::lua_State) -> c_int { //profiling::scope!("set_draw_color"); let lua_instance = unsafe { Lua::get_or_init_from_ptr(state) }; - let ctx = lua_instance.app_data_ref::().unwrap(); + let mut ctx = lua_instance.app_data_mut::().unwrap(); let nargs = unsafe { ffi::lua_gettop(state) }; match nargs { @@ -88,7 +88,7 @@ unsafe extern "C-unwind" fn set_draw_color(state: *mut ffi::lua_State) -> c_int 1 => { let esc_str = str_from_stack!(state, -nargs); let color = Srgba::from_escape_code(esc_str); - ctx.recorder().set_draw_color(color); + ctx.recorder.set_draw_color(color); } // rgb 3 => { @@ -96,7 +96,7 @@ unsafe extern "C-unwind" fn set_draw_color(state: *mut ffi::lua_State) -> c_int let g = f32_from_stack!(state, -nargs + 1); let b = f32_from_stack!(state, -nargs + 2); let color = Srgba::new_f32(r, g, b, 1.0); - ctx.recorder().set_draw_color(color); + ctx.recorder.set_draw_color(color); } // rgba 4 => { @@ -105,7 +105,7 @@ unsafe extern "C-unwind" fn set_draw_color(state: *mut ffi::lua_State) -> c_int let b = f32_from_stack!(state, -nargs + 2); let a = f32_from_stack!(state, -nargs + 3); let color = Srgba::new_f32(r, g, b, a); - ctx.recorder().set_draw_color(color); + ctx.recorder.set_draw_color(color); } _ => panic!("Unexpected number of arguments"), } @@ -118,7 +118,7 @@ unsafe extern "C-unwind" fn get_draw_color(state: *mut ffi::lua_State) -> c_int let lua_instance = unsafe { Lua::get_or_init_from_ptr(state) }; let ctx = lua_instance.app_data_ref::().unwrap(); - let color: [f32; 4] = ctx.recorder().get_draw_color().into(); + let color: [f32; 4] = ctx.recorder.get_draw_color().into(); unsafe { ffi::lua_pushnumber(state, color[0] as f64) }; unsafe { ffi::lua_pushnumber(state, color[1] as f64) }; unsafe { ffi::lua_pushnumber(state, color[2] as f64) }; @@ -130,20 +130,18 @@ unsafe extern "C-unwind" fn get_draw_color(state: *mut ffi::lua_State) -> c_int unsafe extern "C-unwind" fn set_viewport(state: *mut ffi::lua_State) -> c_int { //profiling::scope!("set_viewport"); let lua_instance = unsafe { Lua::get_or_init_from_ptr(state) }; - let ctx = lua_instance.app_data_ref::().unwrap(); + let mut ctx = lua_instance.app_data_mut::().unwrap(); let nargs = unsafe { ffi::lua_gettop(state) }; match nargs { - 0 => ctx - .recorder() - .set_viewport_from_size(ctx.window().logical_size()), + 0 => ctx.set_recorder_viewport_to_window_size(), 4 => { let x = f32_from_stack!(state, -nargs); let y = f32_from_stack!(state, -nargs + 1); let w = f32_from_stack!(state, -nargs + 2); let h = f32_from_stack!(state, -nargs + 3); let rect = Rect::from_origin_and_size(Point::new(x, y), Size::new(w, h)); - ctx.recorder().set_viewport(rect); + ctx.recorder.set_viewport(rect); } _ => panic!("Unexpected number of arguments"), } @@ -154,14 +152,14 @@ unsafe extern "C-unwind" fn set_viewport(state: *mut ffi::lua_State) -> c_int { unsafe extern "C-unwind" fn set_draw_layer(state: *mut ffi::lua_State) -> c_int { //profiling::scope!("set_draw_layer"); let lua_instance = unsafe { Lua::get_or_init_from_ptr(state) }; - let ctx = lua_instance.app_data_ref::().unwrap(); + let mut ctx = lua_instance.app_data_mut::().unwrap(); let nargs = unsafe { ffi::lua_gettop(state) }; match nargs { 1 => { let layer = i32_from_stack!(state, -nargs); - ctx.recorder().set_draw_layer(layer, 0); + ctx.recorder.set_draw_layer(layer, 0); } 2 => { let layer = match unsafe { ffi::lua_type(state, -nargs) } { @@ -174,9 +172,9 @@ unsafe extern "C-unwind" fn set_draw_layer(state: *mut ffi::lua_State) -> c_int }; let sublayer = i32_from_stack!(state, -nargs + 1); if let Some(layer) = layer { - ctx.recorder().set_draw_layer(layer, sublayer); + ctx.recorder.set_draw_layer(layer, sublayer); } else { - ctx.recorder().set_draw_sublayer(sublayer); + ctx.recorder.set_draw_sublayer(sublayer); } } _ => panic!("Unexpected number of arguments"), @@ -188,7 +186,7 @@ unsafe extern "C-unwind" fn set_draw_layer(state: *mut ffi::lua_State) -> c_int unsafe extern "C-unwind" fn draw_image(state: *mut ffi::lua_State) -> c_int { //profiling::scope!("draw_image"); let lua_instance = unsafe { Lua::get_or_init_from_ptr(state) }; - let ctx = lua_instance.app_data_ref::().unwrap(); + let mut ctx = lua_instance.app_data_mut::().unwrap(); let nargs = unsafe { ffi::lua_gettop(state) }; if !matches!(nargs, 5 | 6 | 7 | 9 | 10 | 11) { @@ -228,7 +226,7 @@ unsafe extern "C-unwind" fn draw_image(state: *mut ffi::lua_State) -> c_int { 0 }; - ctx.recorder().draw_image(rect, texture_id, uv, layer_idx); + ctx.recorder.draw_image(rect, texture_id, uv, layer_idx); 0 } @@ -236,7 +234,7 @@ unsafe extern "C-unwind" fn draw_image(state: *mut ffi::lua_State) -> c_int { unsafe extern "C-unwind" fn draw_image_quad(state: *mut ffi::lua_State) -> c_int { //profiling::scope!("draw_image_quad"); let lua_instance = unsafe { Lua::get_or_init_from_ptr(state) }; - let ctx = lua_instance.app_data_ref::().unwrap(); + let mut ctx = lua_instance.app_data_mut::().unwrap(); let nargs = unsafe { ffi::lua_gettop(state) }; if !matches!(nargs, 9 | 10 | 11 | 17 | 18 | 19) { @@ -294,7 +292,7 @@ unsafe extern "C-unwind" fn draw_image_quad(state: *mut ffi::lua_State) -> c_int 0 }; - ctx.recorder() + ctx.recorder .draw_image_quad(quad, texture_id, uv, layer_idx); 0 @@ -303,7 +301,7 @@ unsafe extern "C-unwind" fn draw_image_quad(state: *mut ffi::lua_State) -> c_int unsafe extern "C-unwind" fn draw_string(state: *mut ffi::lua_State) -> c_int { //profiling::scope!("draw_string"); let lua_instance = unsafe { Lua::get_or_init_from_ptr(state) }; - let ctx = lua_instance.app_data_ref::().unwrap(); + let mut ctx = lua_instance.app_data_mut::().unwrap(); let nargs = unsafe { ffi::lua_gettop(state) }; @@ -324,7 +322,7 @@ unsafe extern "C-unwind" fn draw_string(state: *mut ffi::lua_State) -> c_int { let mut position = LogicalPoint::new(x, y); let mut is_absolute_position = false; // the position needs to be adjusted for some alignments to match PoBs behavior - let screen_size = ctx.window().logical_size(); + let screen_size = ctx.window_state.logical_size(); let halign = match alignment { PoBTextAlignment::Left => Alignment::Min, PoBTextAlignment::Center => { @@ -341,7 +339,7 @@ unsafe extern "C-unwind" fn draw_string(state: *mut ffi::lua_State) -> c_int { PoBTextAlignment::RightX => Alignment::Max, }; - let current_draw_color = ctx.recorder().get_draw_color(); + let current_draw_color = ctx.recorder.get_draw_color(); let job = build_layout_job( text, current_draw_color, @@ -353,19 +351,19 @@ unsafe extern "C-unwind" fn draw_string(state: *mut ffi::lua_State) -> c_int { // NOTE: color escape codes modify the current draw color. // set current draw color to color of last segment to match PoB's behavior if let Some(last_segment) = job.segments.last() { - ctx.recorder().set_draw_color(last_segment.color); + ctx.recorder.set_draw_color(last_segment.color); } // Align layout origin with the physical pixel grid to reduce blurriness - let pixels_per_point = ctx.window().scale_factor(); + let pixels_per_point = ctx.window_state.scale_factor(); let position = position .to_physical::(pixels_per_point) .round() .to_logical(pixels_per_point); - let layout = ctx.fonts().layout(job, ctx.window().scale_factor()); + let layout = ctx.fonts.borrow_mut().layout(job, pixels_per_point); for glyph in &layout.glyphs { - ctx.recorder().draw_glyph( + ctx.recorder.draw_glyph( glyph.rect.translate(position.to_vector()), glyph.uv, glyph.color, @@ -393,7 +391,10 @@ unsafe extern "C-unwind" fn get_string_width(state: *mut ffi::lua_State) -> c_in }; let job = build_layout_job(text, Srgba::WHITE, font_type, line_height, None); - let layout = ctx.fonts().layout(job, ctx.window().scale_factor()); + let layout = ctx + .fonts + .borrow_mut() + .layout(job, ctx.window_state.scale_factor()); let width = layout.width(); unsafe { ffi::lua_pushnumber(state, width as f64) }; @@ -410,7 +411,10 @@ fn get_index_at_cur( let font_type = font_type.parse::()?; let job = build_layout_job(&text, Srgba::WHITE, font_type, line_height, None); - let layout = ctx.fonts().layout(job, ctx.window().scale_factor()); + let layout = ctx + .fonts + .borrow_mut() + .layout(job, ctx.window_state.scale_factor()); let index_stripped = layout.cursor_index_at(Point::new(cur_x, cur_y)); // build_layout_job() strips all color escape strings from the original string. The diff --git a/src/api/search_handle.rs b/src/pob/api/search_handle.rs similarity index 100% rename from src/api/search_handle.rs rename to src/pob/api/search_handle.rs diff --git a/src/pob/api/subscript.rs b/src/pob/api/subscript.rs new file mode 100644 index 0000000..ace768c --- /dev/null +++ b/src/pob/api/subscript.rs @@ -0,0 +1,43 @@ +use mlua::{Lua, MultiValue, Result as LuaResult}; + +use crate::pob::Context; + +pub fn launch_subscript( + l: &Lua, + (script_text, func_list, sub_list, args): (String, String, String, MultiValue), +) -> LuaResult { + let blocking_calls = func_list + .split(',') + .map(str::trim) + .filter(|&s| !s.is_empty()) + .map(String::from) + .collect(); + let nonblocking_calls = sub_list + .split(',') + .map(str::trim) + .filter(|&s| !s.is_empty()) + .map(String::from) + .collect(); + let arguments = args.try_into()?; + + let ctx = l.app_data_ref::().unwrap(); + let script_dir = ctx.script_dir.to_owned(); + let subscript_id = ctx.subscript_manager.borrow_mut().push( + script_dir, + script_text, + blocking_calls, + nonblocking_calls, + arguments, + ); + + Ok(subscript_id) +} + +pub fn is_subscript_running(l: &Lua, subscript_id: u64) -> LuaResult { + let ctx = l.app_data_ref::().unwrap(); + Ok(ctx.subscript_manager.borrow().is_running(subscript_id)) +} + +pub fn abort_subscript(_: &Lua, _subscript_id: u64) -> LuaResult<()> { + unimplemented!() +} diff --git a/src/api/window.rs b/src/pob/api/window.rs similarity index 63% rename from src/api/window.rs rename to src/pob/api/window.rs index cac5922..e61c1ef 100644 --- a/src/api/window.rs +++ b/src/pob/api/window.rs @@ -1,16 +1,16 @@ use crate::{ dpi::{LogicalSize, PhysicalSize}, - lua::Context, + pob::Context, }; use mlua::{Lua, Result as LuaResult}; pub fn get_screen_size(l: &Lua, _: ()) -> LuaResult<(u32, u32)> { let ctx = l.app_data_ref::().unwrap(); - let size = if *ctx.is_dpi_aware() { - let PhysicalSize { width, height, .. } = ctx.window().size; + let size = if ctx.is_dpi_aware { + let PhysicalSize { width, height, .. } = ctx.window_state.size; (width, height) } else { - let LogicalSize { width, height, .. } = ctx.window().logical_size(); + let LogicalSize { width, height, .. } = ctx.window_state.logical_size(); (width, height) }; Ok(size) @@ -18,27 +18,27 @@ pub fn get_screen_size(l: &Lua, _: ()) -> LuaResult<(u32, u32)> { pub fn get_screen_scale(l: &Lua, _: ()) -> LuaResult { let ctx = l.app_data_ref::().unwrap(); - let scale_factor = ctx.window().scale_factor(); + let scale_factor = ctx.window_state.scale_factor(); Ok(scale_factor) } pub fn set_window_title(l: &Lua, title: String) -> LuaResult<()> { let ctx = l.app_data_ref::().unwrap(); - ctx.window().set_window_title(&title); + ctx.window_state.set_window_title(&title); Ok(()) } pub fn set_foreground(l: &Lua, _: ()) -> LuaResult<()> { let ctx = l.app_data_ref::().unwrap(); - ctx.window().focus(); + ctx.window_state.focus(); Ok(()) } pub fn set_dpi_scale_override(l: &Lua, percent: i32) -> LuaResult<()> { - let ctx = l.app_data_ref::().unwrap(); + let mut ctx = l.app_data_mut::().unwrap(); match percent { - 0 => ctx.window().scale_factor_override = None, - p if p > 0 => ctx.window().scale_factor_override = Some(p as f32 / 100.0), + 0 => ctx.window_state.scale_factor_override = None, + p if p > 0 => ctx.window_state.scale_factor_override = Some(p as f32 / 100.0), _ => {} } Ok(()) @@ -46,7 +46,7 @@ pub fn set_dpi_scale_override(l: &Lua, percent: i32) -> LuaResult<()> { pub fn get_dpi_scale_override(l: &Lua, _: ()) -> LuaResult { let ctx = l.app_data_ref::().unwrap(); - match ctx.window().scale_factor_override { + match ctx.window_state.scale_factor_override { Some(scale_factor) => Ok((scale_factor * 100.0) as i32), None => Ok(0), } diff --git a/src/subscript.rs b/src/pob/subscript.rs similarity index 81% rename from src/subscript.rs rename to src/pob/subscript.rs index 768e05b..58e0a1f 100644 --- a/src/subscript.rs +++ b/src/pob/subscript.rs @@ -1,11 +1,9 @@ -use crate::{api::get_callback, lua::LuaInstance}; +use crate::{pob::PathOfBuilding, pob::api::get_callback}; use anyhow::{Result, anyhow}; -use mlua::{Function, Integer, IntoLuaMulti, Lua, MultiValue, Number, Result as LuaResult, Value}; +use mlua::{Function, Integer, IntoLuaMulti, Lua, MultiValue, Number, Value}; use std::{ - cell::RefCell, collections::VecDeque, path::PathBuf, - rc::Rc, sync::mpsc::{Receiver, Sender, TryRecvError, channel}, thread::JoinHandle, }; @@ -22,23 +20,16 @@ pub enum SubscriptResult { }, } +#[derive(Default)] pub struct SubscriptManager { current_id: u64, scripts: Vec, - script_dir: PathBuf, } impl SubscriptManager { - pub fn new(script_dir: PathBuf) -> Self { - Self { - current_id: 0, - scripts: Vec::new(), - script_dir, - } - } - pub fn push( &mut self, + script_dir: PathBuf, script_text: String, blocking_calls: Vec, nonblocking_calls: Vec, @@ -53,13 +44,13 @@ impl SubscriptManager { blocking_calls, nonblocking_calls, arguments, - self.script_dir.clone(), + script_dir, ); self.scripts.push(subscript); id } - pub fn process(&mut self, lua: &LuaInstance) -> Vec { + pub fn process(&mut self, lua: &Lua) -> Vec { let mut results = vec![]; self.scripts.retain_mut(|subscript| { @@ -78,6 +69,10 @@ impl SubscriptManager { pub fn has_running_subscripts(&self) -> bool { !self.scripts.is_empty() } + + pub fn is_running(&self, subscript_id: u64) -> bool { + self.scripts.iter().any(|ss| ss.id == subscript_id) + } } enum SubscriptCall { @@ -130,7 +125,8 @@ impl Subscript { let lua = unsafe { Lua::unsafe_new() }; // add ./lua to package.path and package.cpath - LuaInstance::register_package_paths(&lua, &script_dir)?; + // TODO: this is awkward, move package path registration out of PoB? + PathOfBuilding::register_package_paths(&lua, &script_dir)?; for function_name in blocking_calls { let thread_tx = tx.clone(); @@ -247,68 +243,6 @@ impl Subscript { } } -pub fn register_subscript_globals( - lua: &Lua, - subscripts: &Rc>, -) -> LuaResult<()> { - let globals = lua.globals(); - - // ssID = LaunchSubScript("", "", ""[, ...]) - let subscripts_clone = Rc::clone(subscripts); - let launch_sub_script = move |_: &Lua, - (script_text, func_list, sub_list, args): ( - String, - String, - String, - MultiValue, - )| { - let blocking_calls = func_list - .split(',') - .map(str::trim) - .filter(|&s| !s.is_empty()) - .map(String::from) - .collect(); - - let nonblocking_calls = sub_list - .split(',') - .map(str::trim) - .filter(|&s| !s.is_empty()) - .map(String::from) - .collect(); - - let arguments = args.try_into()?; - let subscript_id = subscripts_clone.borrow_mut().push( - script_text, - blocking_calls, - nonblocking_calls, - arguments, - ); - Ok(subscript_id) - }; - - let subscripts_clone = Rc::clone(subscripts); - let is_subscript_running = move |_: &Lua, subscript_id: u64| { - Ok(subscripts_clone - .borrow() - .scripts - .iter() - .any(|ss| ss.id == subscript_id)) - }; - - let abort_subscript = |_: &Lua, _subscript_id: u64| -> LuaResult<()> { unimplemented!() }; - - globals.set( - "LaunchSubScript", - lua.create_function_mut(launch_sub_script)?, - )?; - globals.set( - "IsSubScriptRunning", - lua.create_function(is_subscript_running)?, - )?; - globals.set("AbortSubScript", lua.create_function(abort_subscript)?)?; - Ok(()) -} - // used to move arguments and return values between lua instances // some lua values are associated with their instance and using them with another // instance is not allowed. diff --git a/src/renderer.rs b/src/renderer.rs index 3d9f4ae..ed249e7 100644 --- a/src/renderer.rs +++ b/src/renderer.rs @@ -52,6 +52,7 @@ pub struct RenderJob { pub indices: Vec, pub batches: Vec, pub textures_delta: TexturesDelta, + pub scale_factor: f32, } #[derive(Debug)] diff --git a/src/stage.rs b/src/stage.rs new file mode 100644 index 0000000..b8fc6fd --- /dev/null +++ b/src/stage.rs @@ -0,0 +1,108 @@ +use std::sync::Arc; + +use winit::window::Window; + +use crate::{ + dpi::{PhysicalPoint, PhysicalSize}, + draw_commands::DrawCommand, + installer::Installer, + pob::PathOfBuilding, +}; + +pub type Key = winit::keyboard::Key; +pub type MouseButton = winit::event::MouseButton; +pub type ModifiersState = winit::keyboard::ModifiersState; + +pub enum StageEvent { + KeyDown { + key: Key, + }, + KeyUp { + key: Key, + }, + CharacterInput { + ch: char, + }, + ModifiersChanged { + state: ModifiersState, + }, + MouseDown { + button: MouseButton, + //is_double_click: bool, + }, + MouseUp { + button: MouseButton, + }, + MouseWheel { + delta: f32, + }, + MouseMoved { + pos: PhysicalPoint, + }, + Exit, + Resized(PhysicalSize), + ScaleFactorChanged(f64), + FocusChanged(bool), + HoverChanged(bool), +} + +pub enum StageTransition { + ToMain, + ToShutdown, +} + +pub struct StageFrameOutput { + pub draw_commands: Vec, + pub can_elide: bool, + pub request_redraw: bool, + pub scale_factor: f32, +} + +pub enum ActiveStage { + Startup(Installer), + Main(PathOfBuilding), +} + +impl ActiveStage { + pub fn update(&mut self) -> anyhow::Result> { + match self { + ActiveStage::Startup(s) => s.update(), + ActiveStage::Main(s) => s.update(), + } + } + + pub fn frame(&mut self) -> anyhow::Result { + match self { + ActiveStage::Startup(s) => s.frame(), + ActiveStage::Main(s) => s.frame(), + } + } + + pub fn handle_event(&mut self, event: StageEvent) -> anyhow::Result> { + match self { + ActiveStage::Startup(s) => s.handle_event(event), + ActiveStage::Main(s) => s.handle_event(event), + } + } + + pub fn set_window(&mut self, window: Arc) { + match self { + ActiveStage::Startup(s) => s.set_window(window), + ActiveStage::Main(s) => s.set_window(window), + } + } + + pub fn can_exit(&mut self) -> bool { + match self { + Self::Startup(_) => true, + Self::Main(s) => s.can_exit(), + } + } + + pub fn clear_pressed(&mut self) { + match self { + Self::Startup(_) => {} + Self::Main(s) => s.clear_pressed(), + } + } +} diff --git a/src/window.rs b/src/window.rs index ec645eb..89f129f 100644 --- a/src/window.rs +++ b/src/window.rs @@ -85,10 +85,4 @@ impl WindowState { .as_mut() .and_then(|clipboard| clipboard.get_text()) } - - pub fn request_redraw(&self) { - if let Some(ref window) = self.window { - window.request_redraw(); - } - } }