Release 0.3.6 with a game chooser and native installers
This commit is contained in:
1 parent
67cc995f78
commit
4118c3943f
17 files changed
+1869
-68
No files matched your search
+164
-50
@@ -1,6 +1,7 @@
|
||||
use crate::{
|
||||
args::Game,
|
||||
args::{Args, Game},
|
||||
batcher::build_render_job,
|
||||
chooser::Chooser,
|
||||
dpi::{PhysicalPoint, PhysicalSize},
|
||||
fonts::{FontData, FontDefinitions, Fonts},
|
||||
gfx::GraphicsContext,
|
||||
@@ -9,7 +10,7 @@ use crate::{
|
||||
renderer::{RenderJob, textures::TextureManager},
|
||||
stage::{ActiveStage, StageEvent, StageTransition},
|
||||
};
|
||||
use anyhow::Result;
|
||||
use anyhow::{Context, Result};
|
||||
use std::sync::Arc;
|
||||
use std::{cell::RefCell, path::PathBuf, rc::Rc};
|
||||
use winit::{
|
||||
@@ -25,57 +26,107 @@ struct FrameOutput {
|
||||
pub request_redraw: bool,
|
||||
}
|
||||
|
||||
struct GameLaunch {
|
||||
game: Game,
|
||||
script_dir: PathBuf,
|
||||
}
|
||||
|
||||
pub struct App {
|
||||
gfx_context: Option<GraphicsContext>,
|
||||
fonts: Rc<RefCell<Fonts>>,
|
||||
texture_manager: Rc<RefCell<TextureManager>>,
|
||||
stage: ActiveStage,
|
||||
game: Game,
|
||||
script_dir: PathBuf,
|
||||
launch: Option<GameLaunch>,
|
||||
custom_script_dir: Option<PathBuf>,
|
||||
import_url: Option<String>,
|
||||
pending_transition: Option<StageTransition>,
|
||||
needs_reconfigure: bool,
|
||||
stage_changed: bool,
|
||||
is_focused: bool,
|
||||
is_hovered: bool,
|
||||
}
|
||||
|
||||
impl App {
|
||||
pub fn new(game: Game, custom_script_dir: Option<PathBuf>) -> Result<Self> {
|
||||
let uses_custom_script_dir = custom_script_dir.is_some();
|
||||
let script_dir = custom_script_dir.unwrap_or_else(|| game.script_dir());
|
||||
|
||||
pub fn new(args: Args, custom_script_dir: Option<PathBuf>) -> Result<Self> {
|
||||
let fonts = Rc::new(RefCell::new(Fonts::new(pob_font_definitions())));
|
||||
let texture_manager = Rc::new(RefCell::new(TextureManager::new()));
|
||||
|
||||
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 {
|
||||
ActiveStage::Startup(Installer::new(game, Rc::clone(&fonts)))
|
||||
};
|
||||
|
||||
Ok(Self {
|
||||
let stage = ActiveStage::Chooser(Box::new(Chooser::new(Rc::clone(&fonts))));
|
||||
let mut app = Self {
|
||||
gfx_context: None,
|
||||
fonts,
|
||||
texture_manager,
|
||||
stage,
|
||||
game,
|
||||
script_dir,
|
||||
launch: None,
|
||||
custom_script_dir,
|
||||
import_url: args.import_url,
|
||||
pending_transition: None,
|
||||
needs_reconfigure: true,
|
||||
})
|
||||
stage_changed: true,
|
||||
is_focused: true,
|
||||
is_hovered: true,
|
||||
};
|
||||
if let Some(game) = args.game {
|
||||
app.start_game(game)?;
|
||||
}
|
||||
Ok(app)
|
||||
}
|
||||
|
||||
fn start_game(&mut self, game: Game) -> Result<()> {
|
||||
anyhow::ensure!(self.launch.is_none(), "A game has already been started");
|
||||
let launch = GameLaunch {
|
||||
game,
|
||||
script_dir: self
|
||||
.custom_script_dir
|
||||
.clone()
|
||||
.unwrap_or_else(|| game.script_dir()),
|
||||
};
|
||||
let stage = if self.custom_script_dir.is_some() {
|
||||
// Local scripts bypass installation, but only after a game is selected.
|
||||
ActiveStage::Main(self.create_pob(&launch)?)
|
||||
} else {
|
||||
ActiveStage::Startup(Installer::new(game, Rc::clone(&self.fonts)))
|
||||
};
|
||||
self.launch = Some(launch);
|
||||
self.set_stage(stage);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn create_pob(&self, launch: &GameLaunch) -> Result<PathOfBuilding> {
|
||||
PathOfBuilding::new(
|
||||
&launch.script_dir,
|
||||
Rc::clone(&self.fonts),
|
||||
Rc::clone(&self.texture_manager),
|
||||
self.import_url.clone(),
|
||||
)
|
||||
}
|
||||
|
||||
fn set_stage(&mut self, stage: ActiveStage) {
|
||||
self.stage = stage;
|
||||
if let Some(gfx) = &self.gfx_context {
|
||||
gfx.window.set_title(self.window_identity().0);
|
||||
self.stage.set_window(Arc::clone(&gfx.window));
|
||||
}
|
||||
self.handle_event(StageEvent::FocusChanged(self.is_focused));
|
||||
self.handle_event(StageEvent::HoverChanged(self.is_hovered));
|
||||
self.stage_changed = true;
|
||||
self.request_redraw();
|
||||
}
|
||||
|
||||
fn update(&mut self, event_loop: &ActiveEventLoop) -> anyhow::Result<()> {
|
||||
let transition = self.stage.update();
|
||||
if let Some(transition) = transition? {
|
||||
let transition = match self.pending_transition.take() {
|
||||
Some(transition) => Some(transition),
|
||||
None => self.stage.update()?,
|
||||
};
|
||||
if let Some(transition) = transition {
|
||||
match transition {
|
||||
StageTransition::StartGame(game) => self.start_game(game)?,
|
||||
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));
|
||||
}
|
||||
let launch = self
|
||||
.launch
|
||||
.as_ref()
|
||||
.context("No game selected for Lua startup")?;
|
||||
let pob = self.create_pob(launch)?;
|
||||
self.set_stage(ActiveStage::Main(pob));
|
||||
}
|
||||
StageTransition::ToShutdown => {
|
||||
self.handle_event(StageEvent::Exit);
|
||||
@@ -116,16 +167,27 @@ impl App {
|
||||
}
|
||||
|
||||
fn handle_event(&mut self, event: StageEvent) {
|
||||
if let Err(err) = self.stage.handle_event(event) {
|
||||
log::error!("{err}");
|
||||
match self.stage.handle_event(event) {
|
||||
Ok(Some(transition)) => {
|
||||
self.pending_transition.get_or_insert(transition);
|
||||
}
|
||||
Ok(None) => {}
|
||||
Err(err) => log::error!("{err}"),
|
||||
}
|
||||
// The chooser sleeps between events, including focus loss and cursor exit.
|
||||
self.request_redraw();
|
||||
}
|
||||
|
||||
fn window_identity(&self) -> (&'static str, &'static str) {
|
||||
match self.launch.as_ref().map(|launch| launch.game) {
|
||||
None => ("Rusty Path of Building", "rusty-path-of-building"),
|
||||
Some(Game::Poe1) => ("Path of Building 1", "rusty-path-of-building-1"),
|
||||
Some(Game::Poe2) => ("Path of Building 2", "rusty-path-of-building-2"),
|
||||
}
|
||||
}
|
||||
|
||||
fn create_window(&mut self, event_loop: &ActiveEventLoop) -> anyhow::Result<()> {
|
||||
let (title, _app_id) = match self.game {
|
||||
Game::Poe1 => ("Path of Building 1", "rusty-path-of-building-1"),
|
||||
Game::Poe2 => ("Path of Building 2", "rusty-path-of-building-2"),
|
||||
};
|
||||
let (title, _app_id) = self.window_identity();
|
||||
|
||||
#[allow(unused_mut)]
|
||||
let mut window_attributes = Window::default_attributes()
|
||||
@@ -185,13 +247,19 @@ impl ApplicationHandler<GraphicsContext> for App {
|
||||
WindowEvent::RedrawRequested => {
|
||||
profiling::scope!("RedrawRequested");
|
||||
|
||||
if event_loop.exiting() {
|
||||
return;
|
||||
}
|
||||
if let Err(err) = self.update(event_loop) {
|
||||
log::error!("{err}");
|
||||
event_loop.exit();
|
||||
return;
|
||||
}
|
||||
if event_loop.exiting() {
|
||||
return;
|
||||
}
|
||||
|
||||
let mut inhibit_elision = false;
|
||||
let mut inhibit_elision = std::mem::take(&mut self.stage_changed);
|
||||
if self.needs_reconfigure {
|
||||
if let Some(ref mut gfx) = self.gfx_context {
|
||||
let size = gfx.window.inner_size();
|
||||
@@ -236,20 +304,17 @@ impl ApplicationHandler<GraphicsContext> for App {
|
||||
size.width,
|
||||
size.height,
|
||||
)));
|
||||
self.request_redraw();
|
||||
}
|
||||
WindowEvent::Focused(focused) => {
|
||||
self.is_focused = focused;
|
||||
self.handle_event(StageEvent::FocusChanged(focused));
|
||||
if focused {
|
||||
self.request_redraw();
|
||||
} else {
|
||||
if !focused {
|
||||
// Clear inputs on lost focus to avoid "stuck" keys on Wayland systems.
|
||||
self.stage.clear_pressed();
|
||||
}
|
||||
}
|
||||
WindowEvent::ScaleFactorChanged { scale_factor, .. } => {
|
||||
self.handle_event(StageEvent::ScaleFactorChanged(scale_factor));
|
||||
self.request_redraw();
|
||||
}
|
||||
WindowEvent::KeyboardInput { event, .. } => {
|
||||
let state = event.state;
|
||||
@@ -274,13 +339,11 @@ impl ApplicationHandler<GraphicsContext> for App {
|
||||
self.handle_event(event);
|
||||
}
|
||||
}
|
||||
self.request_redraw();
|
||||
}
|
||||
WindowEvent::ModifiersChanged(modifiers) => {
|
||||
self.handle_event(StageEvent::ModifiersChanged {
|
||||
state: modifiers.state(),
|
||||
});
|
||||
self.request_redraw();
|
||||
}
|
||||
WindowEvent::MouseInput { state, button, .. } => {
|
||||
let event = match state {
|
||||
@@ -288,18 +351,17 @@ impl ApplicationHandler<GraphicsContext> for App {
|
||||
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.handle_event(StageEvent::MouseMoved { pos });
|
||||
self.request_redraw();
|
||||
}
|
||||
WindowEvent::CursorEntered { .. } => {
|
||||
self.is_hovered = true;
|
||||
self.handle_event(StageEvent::HoverChanged(true));
|
||||
self.request_redraw();
|
||||
}
|
||||
WindowEvent::CursorLeft { .. } => {
|
||||
self.is_hovered = false;
|
||||
self.handle_event(StageEvent::HoverChanged(false));
|
||||
}
|
||||
WindowEvent::MouseWheel { delta, .. } => {
|
||||
@@ -310,7 +372,6 @@ impl ApplicationHandler<GraphicsContext> for App {
|
||||
}
|
||||
};
|
||||
self.handle_event(StageEvent::MouseWheel { delta });
|
||||
self.request_redraw();
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
@@ -381,3 +442,56 @@ fn load_icon() -> Option<winit::window::Icon> {
|
||||
let (width, height) = image.dimensions();
|
||||
winit::window::Icon::from_rgba(image.into_raw(), width, height).ok()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use winit::keyboard::{Key, NamedKey};
|
||||
|
||||
#[test]
|
||||
fn chooser_defers_custom_scripts_and_allows_cancellation() {
|
||||
for script_dir in [None, Some(PathBuf::from("missing-launch-script"))] {
|
||||
let mut app = App::new(
|
||||
Args {
|
||||
game: None,
|
||||
import_url: None,
|
||||
},
|
||||
script_dir,
|
||||
)
|
||||
.unwrap();
|
||||
assert!(matches!(app.stage, ActiveStage::Chooser(_)));
|
||||
assert!(app.launch.is_none());
|
||||
assert_eq!(
|
||||
app.window_identity(),
|
||||
("Rusty Path of Building", "rusty-path-of-building")
|
||||
);
|
||||
assert!(app.stage.can_exit());
|
||||
|
||||
app.handle_event(StageEvent::KeyDown {
|
||||
key: Key::Named(NamedKey::Escape),
|
||||
});
|
||||
let transition = app
|
||||
.pending_transition
|
||||
.take()
|
||||
.or_else(|| app.stage.update().unwrap());
|
||||
assert!(matches!(transition, Some(StageTransition::ToShutdown)));
|
||||
assert!(app.launch.is_none());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_games_bypass_selection_and_report_invalid_custom_scripts() {
|
||||
for game in [Game::Poe1, Game::Poe2] {
|
||||
assert!(
|
||||
App::new(
|
||||
Args {
|
||||
game: Some(game),
|
||||
import_url: None
|
||||
},
|
||||
Some(PathBuf::from("missing-launch-script")),
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
+54
-3
@@ -7,9 +7,9 @@ use std::path::PathBuf;
|
||||
#[derive(Parser, Debug)]
|
||||
#[command(version, about, long_about = None)]
|
||||
pub struct Args {
|
||||
/// Used to determine which PoB to start. (PoE1 or PoE2)
|
||||
/// Which PoB to start. Opens the game chooser when omitted.
|
||||
#[arg(value_enum)]
|
||||
pub game: Game,
|
||||
pub game: Option<Game>,
|
||||
|
||||
/// Specify a build to load on start using a URL. (Optional)
|
||||
#[arg(
|
||||
@@ -19,7 +19,7 @@ pub struct Args {
|
||||
}
|
||||
|
||||
/// Enum representing the game version.
|
||||
#[derive(Debug, Clone, Copy, ValueEnum)]
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
|
||||
pub enum Game {
|
||||
/// Path of Exile 1
|
||||
#[value(name = "poe1")]
|
||||
@@ -45,3 +45,54 @@ impl Game {
|
||||
self.data_dir()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use clap::error::ErrorKind;
|
||||
|
||||
#[test]
|
||||
fn no_arguments_requests_game_selection() {
|
||||
let args = Args::try_parse_from(["rpob"]).unwrap();
|
||||
assert!(args.game.is_none());
|
||||
assert!(args.import_url.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_games_accept_an_optional_import_url() {
|
||||
for game in ["poe1", "poe2"] {
|
||||
for import_url in [None, Some("pob://pobbin/example")] {
|
||||
let args =
|
||||
Args::try_parse_from(["rpob", game].into_iter().chain(import_url)).unwrap();
|
||||
assert!(matches!(
|
||||
(game, args.game),
|
||||
("poe1", Some(Game::Poe1)) | ("poe2", Some(Game::Poe2))
|
||||
));
|
||||
assert_eq!(args.import_url.as_deref(), import_url);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_games_and_url_only_still_fail() {
|
||||
for game in ["poe3", "pob://pobbin/example"] {
|
||||
let error = Args::try_parse_from(["rpob", game]).unwrap_err();
|
||||
assert_eq!(error.kind(), ErrorKind::InvalidValue);
|
||||
assert_eq!(error.exit_code(), 2);
|
||||
}
|
||||
assert!(Args::try_parse_from(["rpob", "poe1", "url", "extra"]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn help_and_version_keep_successful_cli_exit_codes() {
|
||||
for (flag, kind) in [
|
||||
("--help", ErrorKind::DisplayHelp),
|
||||
("--version", ErrorKind::DisplayVersion),
|
||||
] {
|
||||
let error = Args::try_parse_from(["rpob", flag]).unwrap_err();
|
||||
assert_eq!(error.kind(), kind);
|
||||
assert_eq!(error.exit_code(), 0);
|
||||
assert!(!error.use_stderr());
|
||||
}
|
||||
}
|
||||
}
|
||||
+661
@@ -0,0 +1,661 @@
|
||||
use std::{cell::RefCell, rc::Rc, sync::Arc};
|
||||
|
||||
use parley::{FontFamily, FontFamilyName, GenericFamily};
|
||||
use winit::{keyboard::NamedKey, window::Window};
|
||||
|
||||
use crate::{
|
||||
args::Game,
|
||||
color::Srgba,
|
||||
dpi::{LogicalPoint, LogicalRect, LogicalSize, PhysicalPoint},
|
||||
draw_commands::DrawCommandRecorder,
|
||||
fonts::{FontStyle, Fonts, LayoutJob},
|
||||
input::{InputState, Key, MouseButton},
|
||||
stage::{StageEvent, StageFrameOutput, StageTransition},
|
||||
window::WindowState,
|
||||
};
|
||||
|
||||
impl Game {
|
||||
const ALL: [Self; 2] = [Self::Poe1, Self::Poe2];
|
||||
|
||||
fn other(self) -> Self {
|
||||
match self {
|
||||
Self::Poe1 => Self::Poe2,
|
||||
Self::Poe2 => Self::Poe1,
|
||||
}
|
||||
}
|
||||
|
||||
fn label(self) -> &'static str {
|
||||
match self {
|
||||
Self::Poe1 => "Path of Exile 1",
|
||||
Self::Poe2 => "Path of Exile 2",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// All drawing and hit testing share the same logical coordinates.
|
||||
struct ChooserLayout {
|
||||
center_x: f32,
|
||||
top: f32,
|
||||
scale: f32,
|
||||
}
|
||||
|
||||
impl ChooserLayout {
|
||||
fn new(size: LogicalSize<f32>) -> Self {
|
||||
let scale = (size.width / 520.0).min(size.height / 380.0).min(1.0);
|
||||
Self {
|
||||
center_x: size.width / 2.0,
|
||||
top: (size.height - 324.0 * scale) / 2.0,
|
||||
scale,
|
||||
}
|
||||
}
|
||||
|
||||
fn button(&self, choice: Game) -> LogicalRect<f32> {
|
||||
let offset = match choice {
|
||||
Game::Poe1 => 96.0,
|
||||
Game::Poe2 => 184.0,
|
||||
};
|
||||
LogicalRect::from_origin_and_size(
|
||||
LogicalPoint::new(self.center_x - 220.0 * self.scale, self.y(offset)),
|
||||
LogicalSize::new(440.0 * self.scale, 72.0 * self.scale),
|
||||
)
|
||||
}
|
||||
|
||||
fn hit_test(&self, pos: LogicalPoint<f32>) -> Option<Game> {
|
||||
Game::ALL
|
||||
.into_iter()
|
||||
.find(|&choice| self.button(choice).contains(pos))
|
||||
}
|
||||
|
||||
fn y(&self, offset: f32) -> f32 {
|
||||
self.top + offset * self.scale
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct Chooser {
|
||||
fonts: Rc<RefCell<Fonts>>,
|
||||
window_state: WindowState,
|
||||
input: InputState,
|
||||
cursor: Option<PhysicalPoint<f32>>,
|
||||
focused: Game,
|
||||
hovered: Option<Game>,
|
||||
mouse_armed: Option<Game>,
|
||||
key_armed: Option<(Key, Game)>,
|
||||
pending: Option<StageTransition>,
|
||||
finished: bool,
|
||||
previous_frame_hash: Option<u64>,
|
||||
}
|
||||
|
||||
impl Chooser {
|
||||
pub(crate) fn new(fonts: Rc<RefCell<Fonts>>) -> Self {
|
||||
Self {
|
||||
fonts,
|
||||
window_state: WindowState::default(),
|
||||
input: InputState::default(),
|
||||
cursor: None,
|
||||
focused: Game::Poe1,
|
||||
hovered: None,
|
||||
mouse_armed: None,
|
||||
key_armed: None,
|
||||
pending: None,
|
||||
finished: false,
|
||||
previous_frame_hash: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn update(&mut self) -> anyhow::Result<Option<StageTransition>> {
|
||||
Ok(self.pending.take())
|
||||
}
|
||||
|
||||
pub(crate) fn frame(&mut self) -> anyhow::Result<StageFrameOutput> {
|
||||
let size = self.window_state.logical_size();
|
||||
let layout = ChooserLayout::new(size);
|
||||
let mut recorder = DrawCommandRecorder::default();
|
||||
recorder.reset();
|
||||
recorder.set_viewport_from_size(size);
|
||||
|
||||
// A minimized/zero-sized surface has neither visible content nor hit targets.
|
||||
if size.width > 0.0 && size.height > 0.0 {
|
||||
recorder.set_draw_color(Srgba::from_rgb(18, 20, 25));
|
||||
recorder.draw_image(LogicalRect::from_size(size), None, None, 0);
|
||||
|
||||
let gold = Srgba::from_rgb(218, 185, 119);
|
||||
let muted = Srgba::from_rgb(180, 183, 191);
|
||||
self.draw_text(
|
||||
&mut recorder,
|
||||
"Path of Building",
|
||||
LogicalPoint::new(layout.center_x, layout.y(0.0)),
|
||||
34.0 * layout.scale,
|
||||
gold,
|
||||
true,
|
||||
);
|
||||
self.draw_text(
|
||||
&mut recorder,
|
||||
"Choose your game",
|
||||
LogicalPoint::new(layout.center_x, layout.y(48.0)),
|
||||
20.0 * layout.scale,
|
||||
muted,
|
||||
false,
|
||||
);
|
||||
|
||||
for choice in Game::ALL {
|
||||
let rect = layout.button(choice);
|
||||
let focused = self.window_state.is_focused && self.focused == choice;
|
||||
let hovered = self.hovered == Some(choice);
|
||||
let pressed = self.mouse_armed == Some(choice)
|
||||
|| self.key_armed.as_ref().is_some_and(|(_, c)| *c == choice);
|
||||
|
||||
recorder.set_draw_color(if focused {
|
||||
gold
|
||||
} else if hovered {
|
||||
Srgba::from_rgb(165, 172, 189)
|
||||
} else {
|
||||
Srgba::from_rgb(83, 86, 98)
|
||||
});
|
||||
recorder.draw_image(rect, None, None, 0);
|
||||
recorder.set_draw_color(if pressed {
|
||||
Srgba::from_rgb(88, 67, 36)
|
||||
} else if hovered {
|
||||
Srgba::from_rgb(47, 51, 62)
|
||||
} else if focused {
|
||||
Srgba::from_rgb(48, 43, 34)
|
||||
} else {
|
||||
Srgba::from_rgb(31, 34, 42)
|
||||
});
|
||||
recorder.draw_image(
|
||||
rect.inflate(-2.0 * layout.scale, -2.0 * layout.scale),
|
||||
None,
|
||||
None,
|
||||
0,
|
||||
);
|
||||
self.draw_text(
|
||||
&mut recorder,
|
||||
choice.label(),
|
||||
LogicalPoint::new(layout.center_x, rect.center().y - 17.0 * layout.scale),
|
||||
28.0 * layout.scale,
|
||||
Srgba::WHITE,
|
||||
true,
|
||||
);
|
||||
}
|
||||
|
||||
for (text, offset) in [
|
||||
("Tab / arrows to choose Enter / Space to start", 280.0),
|
||||
("Esc to quit", 304.0),
|
||||
] {
|
||||
self.draw_text(
|
||||
&mut recorder,
|
||||
text,
|
||||
LogicalPoint::new(layout.center_x, layout.y(offset)),
|
||||
15.0 * layout.scale,
|
||||
muted,
|
||||
false,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
let (hash, layers) = recorder.finish();
|
||||
let can_elide = self.previous_frame_hash == Some(hash);
|
||||
self.previous_frame_hash = Some(hash);
|
||||
Ok(StageFrameOutput {
|
||||
draw_commands: layers.values().flatten().copied().collect(),
|
||||
can_elide,
|
||||
request_redraw: false,
|
||||
scale_factor: self.window_state.scale_factor(),
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn handle_event(
|
||||
&mut self,
|
||||
event: StageEvent,
|
||||
) -> anyhow::Result<Option<StageTransition>> {
|
||||
match event {
|
||||
StageEvent::Exit
|
||||
| StageEvent::KeyDown {
|
||||
key: Key::Named(NamedKey::Escape),
|
||||
} => {
|
||||
// Cancellation supersedes a selection not yet consumed by update.
|
||||
if !self.finished || self.pending.is_some() {
|
||||
self.pending = Some(StageTransition::ToShutdown);
|
||||
self.finished = true;
|
||||
self.clear_pressed();
|
||||
}
|
||||
}
|
||||
StageEvent::Resized(size) => {
|
||||
self.window_state.size = size;
|
||||
self.disarm();
|
||||
}
|
||||
StageEvent::ScaleFactorChanged(factor) => {
|
||||
let factor = factor as f32;
|
||||
if factor.is_finite() && factor > 0.0 {
|
||||
self.window_state.set_scale_factor(factor);
|
||||
self.disarm();
|
||||
}
|
||||
}
|
||||
StageEvent::FocusChanged(focused) => {
|
||||
self.window_state.is_focused = focused;
|
||||
if !focused {
|
||||
self.clear_pressed();
|
||||
}
|
||||
}
|
||||
StageEvent::HoverChanged(hovered) => {
|
||||
self.window_state.is_hovered = hovered;
|
||||
if !hovered {
|
||||
self.disarm();
|
||||
}
|
||||
}
|
||||
_ if self.finished || !self.window_state.is_focused => {}
|
||||
StageEvent::KeyDown { key } => {
|
||||
if !self.input.key_pressed(&key) {
|
||||
self.input.set_key_pressed(&key, true);
|
||||
match key {
|
||||
Key::Named(
|
||||
NamedKey::Tab
|
||||
| NamedKey::ArrowLeft
|
||||
| NamedKey::ArrowRight
|
||||
| NamedKey::ArrowUp
|
||||
| NamedKey::ArrowDown,
|
||||
) => {
|
||||
// With two choices, forward and reverse traversal both toggle.
|
||||
self.focused = self.focused.other();
|
||||
self.hovered = None;
|
||||
self.mouse_armed = None;
|
||||
self.key_armed = None;
|
||||
}
|
||||
Key::Named(NamedKey::Enter | NamedKey::Space)
|
||||
if self.key_armed.is_none() =>
|
||||
{
|
||||
self.key_armed = Some((key, self.focused));
|
||||
self.mouse_armed = None;
|
||||
self.hovered = None;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
StageEvent::KeyUp { key } => {
|
||||
self.input.set_key_pressed(&key, false);
|
||||
if self
|
||||
.key_armed
|
||||
.as_ref()
|
||||
.is_some_and(|(armed, _)| *armed == key)
|
||||
{
|
||||
let (_, choice) = self.key_armed.take().unwrap();
|
||||
self.select(choice);
|
||||
}
|
||||
}
|
||||
StageEvent::MouseMoved { pos } => {
|
||||
self.cursor = Some(pos);
|
||||
self.hovered = self.pointer_target();
|
||||
if self.mouse_armed != self.hovered {
|
||||
self.mouse_armed = None;
|
||||
}
|
||||
}
|
||||
StageEvent::MouseDown {
|
||||
button: MouseButton::Left,
|
||||
} => {
|
||||
if !self.input.mouse_pressed(MouseButton::Left) {
|
||||
self.input.set_mouse_pressed(MouseButton::Left, true);
|
||||
self.mouse_armed = self.pointer_target();
|
||||
self.key_armed = None;
|
||||
self.hovered = self.mouse_armed;
|
||||
if let Some(choice) = self.mouse_armed {
|
||||
self.focused = choice;
|
||||
}
|
||||
}
|
||||
}
|
||||
StageEvent::MouseUp {
|
||||
button: MouseButton::Left,
|
||||
} => {
|
||||
self.input.set_mouse_pressed(MouseButton::Left, false);
|
||||
if let Some(choice) = self.mouse_armed.take()
|
||||
&& self.pointer_target() == Some(choice)
|
||||
{
|
||||
self.select(choice);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
// App advances the queued transition from update, outside event dispatch.
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
pub(crate) fn set_window(&mut self, window: Arc<Window>) {
|
||||
self.window_state.set_window(window);
|
||||
self.previous_frame_hash = None;
|
||||
self.clear_pressed();
|
||||
}
|
||||
|
||||
pub(crate) fn clear_pressed(&mut self) {
|
||||
self.input.clear_pressed();
|
||||
self.disarm();
|
||||
}
|
||||
|
||||
fn disarm(&mut self) {
|
||||
// Keep held-key/button tracking across pointer exit or layout changes so
|
||||
// repeats cannot rearm a cancelled press before its matching release.
|
||||
self.mouse_armed = None;
|
||||
self.key_armed = None;
|
||||
self.hovered = None;
|
||||
self.cursor = None;
|
||||
}
|
||||
|
||||
fn select(&mut self, choice: Game) {
|
||||
if !self.finished {
|
||||
self.pending = Some(StageTransition::StartGame(choice));
|
||||
self.finished = true;
|
||||
self.clear_pressed();
|
||||
}
|
||||
}
|
||||
|
||||
fn pointer_target(&self) -> Option<Game> {
|
||||
if !self.window_state.is_hovered || !self.window_state.is_focused {
|
||||
return None;
|
||||
}
|
||||
let pos = self.cursor? / self.window_state.scale_factor();
|
||||
ChooserLayout::new(self.window_state.logical_size()).hit_test(pos)
|
||||
}
|
||||
|
||||
fn draw_text(
|
||||
&self,
|
||||
recorder: &mut DrawCommandRecorder,
|
||||
text: &str,
|
||||
center_top: LogicalPoint<f32>,
|
||||
size: f32,
|
||||
color: Srgba,
|
||||
bold: bool,
|
||||
) {
|
||||
let mut job = LayoutJob::new(
|
||||
FontFamily::Single(FontFamilyName::Generic(GenericFamily::SansSerif)),
|
||||
size,
|
||||
size * 1.2,
|
||||
None,
|
||||
Some(if bold { 700.0 } else { 400.0 }),
|
||||
FontStyle::Normal,
|
||||
);
|
||||
job.append(text, color);
|
||||
let scale = self.window_state.scale_factor();
|
||||
let layout = self.fonts.borrow_mut().layout(job, scale);
|
||||
let origin = LogicalPoint::new(center_top.x - layout.width() / 2.0, center_top.y);
|
||||
recorder.draw_glyphs(&layout, origin, true, scale);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{
|
||||
dpi::PhysicalSize,
|
||||
fonts::{FontData, FontDefinitions},
|
||||
};
|
||||
|
||||
fn chooser() -> Chooser {
|
||||
let mut definitions = FontDefinitions::default();
|
||||
definitions.font_data.insert(
|
||||
"liberation-sans".to_owned(),
|
||||
Arc::new(FontData::from_static(include_bytes!(
|
||||
"../assets/fonts/LiberationSans-Regular.ttf"
|
||||
))),
|
||||
);
|
||||
definitions
|
||||
.generic_families
|
||||
.insert(GenericFamily::SansSerif, vec!["Liberation Sans".to_owned()]);
|
||||
let mut chooser = Chooser::new(Rc::new(RefCell::new(Fonts::new(definitions))));
|
||||
send(
|
||||
&mut chooser,
|
||||
StageEvent::Resized(PhysicalSize::new(800, 600)),
|
||||
);
|
||||
chooser
|
||||
}
|
||||
|
||||
fn send(chooser: &mut Chooser, event: StageEvent) {
|
||||
assert!(chooser.handle_event(event).unwrap().is_none());
|
||||
}
|
||||
|
||||
fn key(chooser: &mut Chooser, key: NamedKey, down: bool) {
|
||||
send(
|
||||
chooser,
|
||||
if down {
|
||||
StageEvent::KeyDown {
|
||||
key: Key::Named(key),
|
||||
}
|
||||
} else {
|
||||
StageEvent::KeyUp {
|
||||
key: Key::Named(key),
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
fn move_to(chooser: &mut Chooser, choice: Game) {
|
||||
let pos = ChooserLayout::new(chooser.window_state.logical_size())
|
||||
.button(choice)
|
||||
.center()
|
||||
* chooser.window_state.scale_factor();
|
||||
send(chooser, StageEvent::MouseMoved { pos });
|
||||
}
|
||||
|
||||
fn mouse(chooser: &mut Chooser, down: bool) {
|
||||
send(
|
||||
chooser,
|
||||
if down {
|
||||
StageEvent::MouseDown {
|
||||
button: MouseButton::Left,
|
||||
}
|
||||
} else {
|
||||
StageEvent::MouseUp {
|
||||
button: MouseButton::Left,
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chooser_keyboard_selects_both_games_once_on_release() {
|
||||
for (choice, activation) in [(Game::Poe1, NamedKey::Enter), (Game::Poe2, NamedKey::Space)] {
|
||||
let mut chooser = chooser();
|
||||
if choice == Game::Poe2 {
|
||||
key(&mut chooser, NamedKey::Tab, true);
|
||||
key(&mut chooser, NamedKey::Tab, true); // repeat does not cycle again
|
||||
key(&mut chooser, NamedKey::Tab, false);
|
||||
}
|
||||
key(&mut chooser, activation, true);
|
||||
key(&mut chooser, activation, true);
|
||||
assert!(chooser.update().unwrap().is_none());
|
||||
key(&mut chooser, activation, false);
|
||||
assert!(matches!(
|
||||
(choice, chooser.update().unwrap()),
|
||||
(Game::Poe1, Some(StageTransition::StartGame(Game::Poe1)))
|
||||
| (Game::Poe2, Some(StageTransition::StartGame(Game::Poe2)))
|
||||
));
|
||||
key(&mut chooser, activation, true);
|
||||
key(&mut chooser, activation, false);
|
||||
assert!(chooser.update().unwrap().is_none());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chooser_arrow_navigation_works_after_hover_and_cursor_departure() {
|
||||
let mut chooser = chooser();
|
||||
move_to(&mut chooser, Game::Poe1);
|
||||
for arrow in [
|
||||
NamedKey::ArrowRight,
|
||||
NamedKey::ArrowDown,
|
||||
NamedKey::ArrowLeft,
|
||||
NamedKey::ArrowUp,
|
||||
] {
|
||||
key(&mut chooser, arrow, true);
|
||||
key(&mut chooser, arrow, false);
|
||||
}
|
||||
assert_eq!(chooser.focused, Game::Poe1);
|
||||
send(&mut chooser, StageEvent::HoverChanged(false));
|
||||
key(&mut chooser, NamedKey::Tab, true);
|
||||
key(&mut chooser, NamedKey::Tab, false);
|
||||
key(&mut chooser, NamedKey::Space, true);
|
||||
key(&mut chooser, NamedKey::Space, false);
|
||||
assert!(matches!(
|
||||
chooser.update().unwrap(),
|
||||
Some(StageTransition::StartGame(Game::Poe2))
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chooser_pointer_uses_display_scale_and_selects_each_game_once() {
|
||||
for choice in Game::ALL {
|
||||
let mut chooser = chooser();
|
||||
send(&mut chooser, StageEvent::ScaleFactorChanged(2.0));
|
||||
move_to(&mut chooser, choice);
|
||||
mouse(&mut chooser, true);
|
||||
mouse(&mut chooser, true);
|
||||
assert!(chooser.update().unwrap().is_none());
|
||||
mouse(&mut chooser, false);
|
||||
assert!(matches!(
|
||||
(choice, chooser.update().unwrap()),
|
||||
(Game::Poe1, Some(StageTransition::StartGame(Game::Poe1)))
|
||||
| (Game::Poe2, Some(StageTransition::StartGame(Game::Poe2)))
|
||||
));
|
||||
mouse(&mut chooser, false);
|
||||
assert!(chooser.update().unwrap().is_none());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chooser_rejects_unarmed_mismatched_and_departed_clicks() {
|
||||
let mut chooser = chooser();
|
||||
move_to(&mut chooser, Game::Poe1);
|
||||
mouse(&mut chooser, false);
|
||||
mouse(&mut chooser, true);
|
||||
move_to(&mut chooser, Game::Poe2);
|
||||
mouse(&mut chooser, false);
|
||||
assert!(chooser.update().unwrap().is_none());
|
||||
|
||||
move_to(&mut chooser, Game::Poe1);
|
||||
mouse(&mut chooser, true);
|
||||
send(
|
||||
&mut chooser,
|
||||
StageEvent::MouseMoved {
|
||||
pos: PhysicalPoint::new(0.0, 0.0),
|
||||
},
|
||||
);
|
||||
move_to(&mut chooser, Game::Poe1);
|
||||
mouse(&mut chooser, false);
|
||||
assert!(chooser.update().unwrap().is_none());
|
||||
|
||||
mouse(&mut chooser, true);
|
||||
send(&mut chooser, StageEvent::HoverChanged(false));
|
||||
send(&mut chooser, StageEvent::HoverChanged(true));
|
||||
move_to(&mut chooser, Game::Poe1);
|
||||
mouse(&mut chooser, false);
|
||||
assert!(chooser.update().unwrap().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chooser_focus_loss_and_navigation_disarm_activation() {
|
||||
let mut chooser = chooser();
|
||||
key(&mut chooser, NamedKey::Enter, true);
|
||||
send(&mut chooser, StageEvent::FocusChanged(false));
|
||||
key(&mut chooser, NamedKey::Space, true);
|
||||
send(&mut chooser, StageEvent::FocusChanged(true));
|
||||
key(&mut chooser, NamedKey::Enter, false);
|
||||
key(&mut chooser, NamedKey::Space, false);
|
||||
assert!(chooser.update().unwrap().is_none());
|
||||
|
||||
key(&mut chooser, NamedKey::Enter, true);
|
||||
key(&mut chooser, NamedKey::Tab, true);
|
||||
key(&mut chooser, NamedKey::Enter, false);
|
||||
assert!(chooser.update().unwrap().is_none());
|
||||
|
||||
move_to(&mut chooser, Game::Poe1);
|
||||
mouse(&mut chooser, true);
|
||||
send(&mut chooser, StageEvent::FocusChanged(false));
|
||||
send(&mut chooser, StageEvent::FocusChanged(true));
|
||||
move_to(&mut chooser, Game::Poe1);
|
||||
mouse(&mut chooser, false);
|
||||
assert!(chooser.update().unwrap().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chooser_departure_and_resize_cannot_rearm_a_held_key() {
|
||||
for event in [
|
||||
StageEvent::HoverChanged(false),
|
||||
StageEvent::Resized(PhysicalSize::new(640, 480)),
|
||||
StageEvent::ScaleFactorChanged(1.5),
|
||||
] {
|
||||
let mut chooser = chooser();
|
||||
key(&mut chooser, NamedKey::Enter, true);
|
||||
send(&mut chooser, event);
|
||||
key(&mut chooser, NamedKey::Enter, true);
|
||||
key(&mut chooser, NamedKey::Enter, false);
|
||||
assert!(chooser.update().unwrap().is_none());
|
||||
key(&mut chooser, NamedKey::Enter, true);
|
||||
key(&mut chooser, NamedKey::Enter, false);
|
||||
assert!(matches!(
|
||||
chooser.update().unwrap(),
|
||||
Some(StageTransition::StartGame(Game::Poe1))
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chooser_escape_overrides_a_pending_game_and_stays_cancelled() {
|
||||
let mut chooser = chooser();
|
||||
key(&mut chooser, NamedKey::Enter, true);
|
||||
key(&mut chooser, NamedKey::Enter, false);
|
||||
key(&mut chooser, NamedKey::Escape, true);
|
||||
assert!(matches!(
|
||||
chooser.update().unwrap(),
|
||||
Some(StageTransition::ToShutdown)
|
||||
));
|
||||
key(&mut chooser, NamedKey::Space, true);
|
||||
key(&mut chooser, NamedKey::Space, false);
|
||||
assert!(chooser.update().unwrap().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chooser_layout_fits_small_windows_and_zero_surfaces_are_inert() {
|
||||
for size in [
|
||||
LogicalSize::new(320.0, 240.0),
|
||||
LogicalSize::new(800.0, 600.0),
|
||||
] {
|
||||
let layout = ChooserLayout::new(size);
|
||||
let screen = LogicalRect::from_size(size);
|
||||
for choice in Game::ALL {
|
||||
let button = layout.button(choice);
|
||||
assert!(screen.contains_box(&button));
|
||||
assert_eq!(layout.hit_test(button.center()), Some(choice));
|
||||
}
|
||||
}
|
||||
let mut chooser = chooser();
|
||||
move_to(&mut chooser, Game::Poe1);
|
||||
mouse(&mut chooser, true);
|
||||
send(&mut chooser, StageEvent::Resized(PhysicalSize::new(0, 0)));
|
||||
mouse(&mut chooser, false);
|
||||
assert!(chooser.update().unwrap().is_none());
|
||||
let frame = chooser.frame().unwrap();
|
||||
assert!(frame.draw_commands.is_empty());
|
||||
assert!(!frame.request_redraw);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chooser_initial_and_interaction_frames_render_then_idle() {
|
||||
let mut chooser = chooser();
|
||||
let initial = chooser.frame().unwrap();
|
||||
assert!(!initial.can_elide);
|
||||
assert!(!initial.request_redraw);
|
||||
assert!(
|
||||
initial
|
||||
.draw_commands
|
||||
.iter()
|
||||
.filter(|cmd| cmd.color == Srgba::WHITE)
|
||||
.count()
|
||||
> 20,
|
||||
"both game labels must produce visible glyphs"
|
||||
);
|
||||
assert!(chooser.frame().unwrap().can_elide);
|
||||
move_to(&mut chooser, Game::Poe2);
|
||||
assert!(!chooser.frame().unwrap().can_elide);
|
||||
assert!(chooser.frame().unwrap().can_elide);
|
||||
mouse(&mut chooser, true);
|
||||
let pressed = chooser.frame().unwrap();
|
||||
assert!(!pressed.can_elide);
|
||||
assert!(!pressed.request_redraw);
|
||||
}
|
||||
}
|
||||
+2
-1
@@ -6,6 +6,7 @@ use winit::event_loop::EventLoop;
|
||||
mod app;
|
||||
mod args;
|
||||
mod batcher;
|
||||
mod chooser;
|
||||
mod clipboard;
|
||||
mod color;
|
||||
mod dpi;
|
||||
@@ -39,7 +40,7 @@ fn main() -> anyhow::Result<()> {
|
||||
let args = Args::parse();
|
||||
let script_dir = find_nearby_launch_script();
|
||||
|
||||
let mut app = App::new(args.game, script_dir)?;
|
||||
let mut app = App::new(args, script_dir)?;
|
||||
|
||||
let event_loop = EventLoop::with_user_event().build()?;
|
||||
event_loop.run_app(&mut app)?;
|
||||
|
||||
+105
-7
@@ -1,11 +1,9 @@
|
||||
use clap::Parser;
|
||||
use mlua::{
|
||||
AppDataRef, AppDataRefMut, Function, Lua, Result as LuaResult, Table, thread::ThreadStatus,
|
||||
};
|
||||
use winit::window::Window;
|
||||
|
||||
use crate::{
|
||||
args::Args,
|
||||
dpi::{PhysicalPoint, ScaleFactor},
|
||||
draw_commands::DrawCommandRecorder,
|
||||
fonts::Fonts,
|
||||
@@ -85,6 +83,7 @@ impl Context {
|
||||
/// Exposes API, forwards events to Path of Building's event handlers, and manages subscripts.
|
||||
pub struct PathOfBuilding {
|
||||
lua: Lua,
|
||||
import_url: Option<String>,
|
||||
/// Hash of the previous frame's draw commands. Used to skip rerendering identical frames.
|
||||
previous_layers_hash: u64,
|
||||
}
|
||||
@@ -94,27 +93,32 @@ impl PathOfBuilding {
|
||||
script_dir: &Path,
|
||||
fonts: Rc<RefCell<Fonts>>,
|
||||
texture_manager: Rc<RefCell<TextureManager>>,
|
||||
import_url: Option<String>,
|
||||
) -> anyhow::Result<Self> {
|
||||
let ctx = Context::new(script_dir, fonts, texture_manager);
|
||||
let lua = Self::create_lua(ctx, SubscriptManager::default())?;
|
||||
let lua = Self::create_lua(ctx, SubscriptManager::default(), import_url.as_deref())?;
|
||||
|
||||
Self::launch(&lua, script_dir)?;
|
||||
|
||||
Ok(Self {
|
||||
lua,
|
||||
import_url,
|
||||
previous_layers_hash: Default::default(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Builds a `Lua` state with package paths, context, and all API functions registered.
|
||||
fn create_lua(ctx: Context, subscript_manager: SubscriptManager) -> LuaResult<Lua> {
|
||||
fn create_lua(
|
||||
ctx: Context,
|
||||
subscript_manager: SubscriptManager,
|
||||
import_url: Option<&str>,
|
||||
) -> LuaResult<Lua> {
|
||||
// `unsafe_new` needed to allow loading of C modules
|
||||
let lua = unsafe { Lua::unsafe_new() };
|
||||
append_lua_package_dir(&lua, &ctx.script_dir.join("lua"))?;
|
||||
|
||||
// expose import url to lua
|
||||
let args = Args::parse();
|
||||
let args_table = lua.create_sequence_from(std::iter::once(args.import_url))?;
|
||||
let args_table = lua.create_sequence_from(import_url)?;
|
||||
lua.globals().set("arg", args_table)?;
|
||||
|
||||
// make context and subscript manager accessible to API functions
|
||||
@@ -154,7 +158,7 @@ impl PathOfBuilding {
|
||||
.unwrap_or_default();
|
||||
|
||||
// and move both into the new instance
|
||||
self.lua = Self::create_lua(ctx, subscript_manager)?;
|
||||
self.lua = Self::create_lua(ctx, subscript_manager, self.import_url.as_deref())?;
|
||||
Self::launch(&self.lua, &script_dir)?;
|
||||
|
||||
Ok(())
|
||||
@@ -377,3 +381,97 @@ impl PathOfBuilding {
|
||||
self.lua.app_data_mut().unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::fonts::FontDefinitions;
|
||||
use std::{fs, process::Command};
|
||||
|
||||
#[test]
|
||||
fn launch_and_restart_preserve_import_and_script_directory() {
|
||||
const CHILD_ENV: &str = "RPOB_LUA_RESTART_TEST_CHILD";
|
||||
// Launch changes the process CWD. Isolate it from concurrently running tests.
|
||||
if std::env::var_os(CHILD_ENV).is_none() {
|
||||
let output = Command::new(std::env::current_exe().unwrap())
|
||||
.args([
|
||||
"--exact",
|
||||
"pob::tests::launch_and_restart_preserve_import_and_script_directory",
|
||||
"--nocapture",
|
||||
])
|
||||
.env(CHILD_ENV, "1")
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"Lua fixture failed:\n{}\n{}",
|
||||
String::from_utf8_lossy(&output.stdout),
|
||||
String::from_utf8_lossy(&output.stderr),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
let original_dir = std::env::current_dir().unwrap();
|
||||
let fixture_dir =
|
||||
std::env::temp_dir().join(format!("rpob-lua-test-{}", std::process::id()));
|
||||
fs::create_dir(&fixture_dir).unwrap();
|
||||
let script_dir = fixture_dir.canonicalize().unwrap();
|
||||
fs::write(script_dir.join("relative.txt"), "script directory").unwrap();
|
||||
fs::write(
|
||||
script_dir.join("Launch.lua"),
|
||||
r#"
|
||||
SetMainObject({
|
||||
OnInit = function()
|
||||
local file = assert(io.open("relative.txt", "r"))
|
||||
assert(file:read("*a") == "script directory")
|
||||
file:close()
|
||||
initialized_arg = arg[1]
|
||||
end,
|
||||
CanExit = function() return allow_exit end,
|
||||
})
|
||||
allow_exit = true
|
||||
"#,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
for import_url in [Some("pob://pobbin/restart-test"), None] {
|
||||
let mut pob = PathOfBuilding::new(
|
||||
&script_dir,
|
||||
Rc::new(RefCell::new(Fonts::new(FontDefinitions::default()))),
|
||||
Rc::new(RefCell::new(TextureManager::new())),
|
||||
import_url.map(str::to_owned),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
pob.lua
|
||||
.globals()
|
||||
.get::<Option<String>>("initialized_arg")
|
||||
.unwrap()
|
||||
.as_deref(),
|
||||
import_url
|
||||
);
|
||||
assert!(pob.can_exit());
|
||||
pob.lua
|
||||
.load("arg[1] = 'modified'; allow_exit = false; Restart()")
|
||||
.exec()
|
||||
.unwrap();
|
||||
assert!(!pob.can_exit());
|
||||
assert!(pob.update().unwrap().is_none());
|
||||
assert_eq!(
|
||||
pob.lua
|
||||
.globals()
|
||||
.get::<Option<String>>("initialized_arg")
|
||||
.unwrap()
|
||||
.as_deref(),
|
||||
import_url
|
||||
);
|
||||
assert_eq!(std::env::current_dir().unwrap(), script_dir);
|
||||
assert_eq!(pob.ctx().script_dir, script_dir);
|
||||
assert!(!pob.ctx().needs_restart);
|
||||
assert!(pob.can_exit());
|
||||
}
|
||||
|
||||
std::env::set_current_dir(original_dir).unwrap();
|
||||
fs::remove_dir_all(fixture_dir).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,8 @@ use std::sync::Arc;
|
||||
use winit::window::Window;
|
||||
|
||||
use crate::{
|
||||
args::Game,
|
||||
chooser::Chooser,
|
||||
dpi::{PhysicalPoint, PhysicalSize, ScaleFactor},
|
||||
draw_commands::DrawCommand,
|
||||
input::{Key, ModifiersState, MouseButton},
|
||||
@@ -27,6 +29,7 @@ pub enum StageEvent {
|
||||
}
|
||||
|
||||
pub enum StageTransition {
|
||||
StartGame(Game),
|
||||
ToMain,
|
||||
ToShutdown,
|
||||
}
|
||||
@@ -39,6 +42,7 @@ pub struct StageFrameOutput {
|
||||
}
|
||||
|
||||
pub enum ActiveStage {
|
||||
Chooser(Box<Chooser>),
|
||||
Startup(Installer),
|
||||
Main(PathOfBuilding),
|
||||
}
|
||||
@@ -46,6 +50,7 @@ pub enum ActiveStage {
|
||||
impl ActiveStage {
|
||||
pub fn update(&mut self) -> anyhow::Result<Option<StageTransition>> {
|
||||
match self {
|
||||
Self::Chooser(s) => s.update(),
|
||||
Self::Startup(s) => s.update(),
|
||||
Self::Main(s) => s.update(),
|
||||
}
|
||||
@@ -53,6 +58,7 @@ impl ActiveStage {
|
||||
|
||||
pub fn frame(&mut self) -> anyhow::Result<StageFrameOutput> {
|
||||
match self {
|
||||
Self::Chooser(s) => s.frame(),
|
||||
Self::Startup(s) => s.frame(),
|
||||
Self::Main(s) => s.frame(),
|
||||
}
|
||||
@@ -60,6 +66,7 @@ impl ActiveStage {
|
||||
|
||||
pub fn handle_event(&mut self, event: StageEvent) -> anyhow::Result<Option<StageTransition>> {
|
||||
match self {
|
||||
Self::Chooser(s) => s.handle_event(event),
|
||||
Self::Startup(s) => s.handle_event(event),
|
||||
Self::Main(s) => s.handle_event(event),
|
||||
}
|
||||
@@ -67,6 +74,7 @@ impl ActiveStage {
|
||||
|
||||
pub fn set_window(&mut self, window: Arc<Window>) {
|
||||
match self {
|
||||
Self::Chooser(s) => s.set_window(window),
|
||||
Self::Startup(s) => s.set_window(window),
|
||||
Self::Main(s) => s.set_window(window),
|
||||
}
|
||||
@@ -74,6 +82,7 @@ impl ActiveStage {
|
||||
|
||||
pub fn can_exit(&mut self) -> bool {
|
||||
match self {
|
||||
Self::Chooser(_) => true,
|
||||
Self::Startup(_) => true,
|
||||
Self::Main(s) => s.can_exit(),
|
||||
}
|
||||
@@ -81,6 +90,7 @@ impl ActiveStage {
|
||||
|
||||
pub fn clear_pressed(&mut self) {
|
||||
match self {
|
||||
Self::Chooser(s) => s.clear_pressed(),
|
||||
Self::Startup(_) => {}
|
||||
Self::Main(s) => s.clear_pressed(),
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user