From 879e625a388fa25a21c6ca18e479487ba6d07de8 Mon Sep 17 00:00:00 2001 From: leonidarider <358984476+leonidarider@users.noreply.github.com> Date: Thu, 3 Dec 2026 02:57:44 +0100 Subject: [PATCH] refactor: decompose AppState into sub-structs, remove glob barrel, and encapsulate workbench chains (desloppify wave 5E-2) - Group AppState (99 -> 42 fields) into 10 cohesive sub-structs in src/state/app_clusters.rs (ErrorDialog, PendingPrompts, TextureResolutionState, Gta6Finders, DocumentIoQueue, FrameTelemetry, AnimationState, InstallReferenceData, BackgroundControllers, SearchState) and fold collision_bvh and ptfx_sinks onto SimSession. - Replace all 14 wildcard glob re-exports/imports (::*) in src/state/mod.rs with explicit symbol lists. - Move the remaining 3 impl AppState blocks out of src/audio/ and src/video/ into src/state/media_playback.rs (0 impl AppState blocks outside src/state/). - Group Dressed private fields (45 -> 34), add domain methods on Workbench, Dressed, WardrobeWork, and WeaponsWork, narrow UI panel helpers, and eliminate 81 deep 4-5 level workbench field chains across wardrobe/, weapons/, and os_drop.rs. --- src/app/editor_window.rs | 10 +- src/app/modals.rs | 19 +- src/audio/mod.rs | 265 +++-------- src/audio/opus_job.rs | 219 +-------- src/photo/mod.rs | 2 +- src/photo/serve.rs | 2 +- src/render/game_scene/mod.rs | 7 +- src/render/gta6_trace.rs | 2 +- src/render/meshes.rs | 4 +- src/render/viewport/bones.rs | 6 +- src/render/viewport/day.rs | 6 +- src/render/viewport/game_shaders.rs | 14 +- src/render/viewport/mod.rs | 12 +- src/render/viewport/pick.rs | 2 +- src/render/viewport/pick_lines.rs | 2 +- src/render/viewport/posing.rs | 5 +- src/render/viewport/retarget.rs | 10 +- src/self_check/mod.rs | 20 +- src/self_check/shots/lost_device.rs | 2 +- src/self_check/shots/perf.rs | 6 +- src/self_check/shots/waits.rs | 4 +- src/self_check/shots/world_fed.rs | 4 +- src/self_check/units.rs | 4 +- src/state/animation_session.rs | 53 ++- src/state/app_clusters.rs | 321 ++++++++++++++ src/state/batch.rs | 4 +- src/state/clipboard/mod.rs | 2 +- src/state/closing.rs | 34 +- src/state/clothing.rs | 4 +- src/state/compare/mod.rs | 19 +- src/state/convert.rs | 32 +- src/state/defrag_job.rs | 17 +- src/state/delete_prompt.rs | 4 +- src/state/dependencies.rs | 6 +- src/state/dlc_pack.rs | 42 +- src/state/extract_job.rs | 22 +- src/state/extract_planning.rs | 40 +- src/state/file_index/mod.rs | 12 +- src/state/file_io/mod.rs | 100 ++--- src/state/file_io/save_source.rs | 8 + src/state/files_view/mod.rs | 6 +- src/state/gltf.rs | 34 +- src/state/gta6/anim/gta6_anim_edit/tests.rs | 4 +- src/state/gta6/anim/gta6_bone_edit/tests.rs | 4 +- src/state/gta6/anim/gta6_clip_finding.rs | 15 +- src/state/gta6/anim/gta6_set_finding/mod.rs | 20 +- src/state/gta6/anim/gta6_set_finding/tests.rs | 14 +- src/state/gta6/bodies/gta6_meta_save/mod.rs | 4 +- .../bodies/gta6_other_bodies_save/cell.rs | 4 +- .../gta6/bodies/gta6_other_bodies_save/mod.rs | 6 +- .../gta6_resource_save/awc_in_extent.rs | 4 +- .../gta6/bodies/gta6_resource_save/mod.rs | 15 +- .../saving_an_edited_gta_vi_text_body.rs | 4 +- src/state/gta6/drawable/gta6_edit/tests.rs | 10 +- .../gta6/drawable/gta6_gltf_import/tests.rs | 14 +- .../drawable/gta6_material_layout/tests.rs | 6 +- src/state/gta6/install/gta6_first_entry.rs | 4 +- .../gta6/install/gta6_install_harvest.rs | 6 +- src/state/gta6/install/gta6_names.rs | 2 +- src/state/gta6/install/gta_vi.rs | 2 +- src/state/gta6/modding/batch_export.rs | 4 +- src/state/gta6/modding/model_replace/tests.rs | 2 +- src/state/gta6/modding/references.rs | 8 +- src/state/gta6/modding/texture_replace.rs | 2 +- .../gta6/particles/gta6_particle_models.rs | 11 +- src/state/gta6/physics/gta6_navmesh.rs | 11 +- .../gta6/physics/gta6_navmesh_delete/mod.rs | 4 +- src/state/gta6/physics/gta6_navmesh_edit.rs | 2 +- .../gta6/physics/gta6_physics_edit/tests.rs | 6 +- .../gta6/textures/gta6_dictionary_index.rs | 42 +- .../textures/gta6_dictionary_write/tests.rs | 6 +- .../gta6/textures/gta6_embedded_edit/mod.rs | 2 +- .../gta6/textures/gta6_embedded_edit/tests.rs | 4 +- src/state/gta6/textures/gta6_texture_index.rs | 66 +-- .../gta6/textures/gta6_texture_names_file.rs | 2 +- .../gta6/textures/gta6_texture_naming.rs | 26 +- src/state/gta6/world/gta6_map/mod.rs | 33 +- src/state/gta6/world/gta6_map/tests.rs | 12 +- src/state/install_lifecycle.rs | 56 ++- src/state/jobs.rs | 72 +-- src/state/media_playback.rs | 417 ++++++++++++++++++ src/state/memory.rs | 8 +- src/state/mod.rs | 283 ++++-------- src/state/mod_manager.rs | 26 +- src/state/move_network.rs | 4 +- src/state/navigation.rs | 4 +- src/state/os_drop.rs | 5 +- src/state/overlay_copy.rs | 18 +- src/state/overlay_loader.rs | 5 +- src/state/overlay_refresh.rs | 69 +-- .../the_cloth_painter_installs_as_a_plugin.rs | 2 +- src/state/project_io.rs | 2 +- src/state/project_shadow.rs | 6 +- src/state/reload_open_file.rs | 10 +- .../rpf/rpf9_scan/extracting_a_gta_vi_body.rs | 4 +- src/state/rpf/rpf9_scan/mod.rs | 4 +- .../rpf_archive_open/tree_open/bind/tests.rs | 4 +- .../rpf_archive_open/tree_open/names_tests.rs | 2 +- .../tree_verbs/adopt/tests.rs | 4 +- .../headerless_tests/saves_per_kind/mod.rs | 2 +- src/state/rpf/rpf_expansion.rs | 20 +- src/state/rpf/rpf_moves.rs | 2 +- src/state/rpf/rpf_tree.rs | 18 +- src/state/save_destination.rs | 12 +- src/state/search_session.rs | 11 +- src/state/sim.rs | 4 + src/state/tabs.rs | 11 +- .../tests/a_bones_numbers_can_be_edited.rs | 20 +- ...es_and_a_change_of_nothing_does_nothing.rs | 16 +- .../a_model_is_drawn_with_its_own_textures.rs | 6 +- .../tests/a_plugin_asks_before_it_runs.rs | 2 +- .../tests/a_recook_reloads_what_is_open.rs | 4 +- .../tests/a_save_names_its_destination.rs | 9 +- .../tests/a_self_check_keeps_to_itself.rs | 6 +- ...a_skeleton_is_seen_without_an_animation.rs | 5 +- src/state/tests/an_error_names_what_failed.rs | 4 +- ..._export_asks_before_it_alters_the_bytes.rs | 4 +- ...tion_holds_back_only_the_files_it_reads.rs | 9 +- .../tests/an_undo_finishes_or_says_why.rs | 9 +- .../tests/building_a_dlc_pack_from_the_app.rs | 8 +- .../comparing_every_resource_and_archive.rs | 3 +- src/state/tests/converting_from_the_app.rs | 10 +- .../tests/converting_in_a_modders_words.rs | 14 +- ...ng_is_listed_and_asked_inside_its_panel.rs | 15 +- src/state/tests/copy_cut_and_paste/files.rs | 7 +- src/state/tests/defragmenting_an_archive.rs | 29 +- .../tests/destructive_file_operations_ask.rs | 16 +- src/state/tests/editing_a_clip.rs | 4 +- .../every_question_fits_a_narrow_window.rs | 16 +- .../every_write_asks_the_jobs_reading_it.rs | 10 +- ...te_into_a_folder_a_job_reads_is_refused.rs | 6 +- .../tests/gltf_in_and_out_from_the_app.rs | 29 +- .../tests/gta6_textures_resolve_and_save.rs | 6 +- .../tests/nested_archives_survive_a_save.rs | 7 +- .../no_save_replaces_a_file_a_job_reads.rs | 4 +- .../tests/nothing_extracts_into_an_install.rs | 10 +- .../tests/one_place_for_background_jobs.rs | 41 +- src/state/tests/opening_a_dds.rs | 6 +- src/state/tests/opening_a_gta_vi_body.rs | 4 +- src/state/tests/opening_a_nametable.rs | 10 +- src/state/tests/opening_a_rel.rs | 6 +- src/state/tests/opening_a_ttpf.rs | 10 +- src/state/tests/opening_a_ydd.rs | 4 +- src/state/tests/opening_an_awc.rs | 10 +- src/state/tests/opening_an_rpf9_archive.rs | 6 +- src/state/tests/opening_an_unknown_file.rs | 10 +- .../opening_metadata_without_a_schema.rs | 2 +- src/state/tests/opening_world_dat.rs | 10 +- src/state/tests/opus_on_a_worker.rs | 2 +- src/state/tests/previewing_a_video.rs | 2 +- .../tests/reordering_mods_from_the_app.rs | 12 +- src/state/tests/search_results_that_open.rs | 23 +- ...settings_recents_and_small_editor_fixes.rs | 16 +- ...lts_in_the_default_views_menus_and_keys.rs | 2 +- .../tests/tabs_that_behave_like_an_editors.rs | 6 +- ...ion_preview_draws_what_its_sources_hold.rs | 101 +++-- .../the_default_views_in_a_modders_words.rs | 11 +- src/state/tests/the_dressed_ped.rs | 11 +- .../the_edit_mode_is_visible_and_honest.rs | 14 +- .../the_files_view_in_the_centre/keys.rs | 11 +- src/state/tests/the_front_door.rs | 5 +- .../tests/the_front_door_opens_and_closes.rs | 4 +- .../tests/the_gate_in_front_of_every_write.rs | 23 +- .../tests/the_map_screen_holds_a_session.rs | 16 +- .../the_map_screen_saves_with_the_project.rs | 2 +- ..._skeleton_files_own_model_can_be_hidden.rs | 10 +- .../the_unsaved_marker_tells_the_truth.rs | 4 +- .../the_viewport_picks_every_line_it_draws.rs | 12 +- .../tests/the_viewport_picks_what_it_draws.rs | 5 +- .../tests/what_a_comparison_still_missed.rs | 6 +- .../what_archive_rows_still_get_wrong.rs | 4 +- src/state/texture_edit.rs | 2 +- src/state/texture_resolution.rs | 87 ++-- src/state/undo.rs | 14 +- src/state/vfs_session.rs | 7 +- src/state/workbench/commands.rs | 8 +- src/state/workbench/dressed/alone.rs | 2 +- src/state/workbench/dressed/assemble.rs | 38 +- src/state/workbench/dressed/controls.rs | 203 +++++++++ src/state/workbench/dressed/first_person.rs | 10 +- src/state/workbench/dressed/mod.rs | 231 ++++++---- src/state/workbench/dressed/read.rs | 2 +- src/state/workbench/maps_edit.rs | 2 +- src/state/workbench/maps_session.rs | 4 +- src/state/workbench/mod.rs | 50 +++ src/state/workbench/wardrobe.rs | 75 +++- src/state/workbench/weapons.rs | 81 ++++ src/ui/commands/files.rs | 4 +- src/ui/commands/target.rs | 6 +- src/ui/commands/tools_and_help.rs | 16 +- src/ui/os_drop.rs | 6 +- src/ui/panels/command_palette.rs | 14 +- src/ui/panels/dlc_pack.rs | 8 +- src/ui/panels/edit_mode.rs | 4 +- src/ui/panels/file_prompts.rs | 19 +- src/ui/panels/gallery.rs | 4 +- src/ui/panels/game_picker.rs | 2 +- src/ui/panels/gxt2_table.rs | 4 +- src/ui/panels/hierarchy/defrag.rs | 2 +- src/ui/panels/hierarchy/files/folder_view.rs | 4 +- src/ui/panels/hierarchy/files/mod.rs | 4 +- src/ui/panels/hierarchy/navigation.rs | 4 +- src/ui/panels/hierarchy/rpf.rs | 11 +- src/ui/panels/hierarchy/rpf_tree.rs | 6 +- src/ui/panels/hierarchy/ycd.rs | 2 +- src/ui/panels/inspector/gta6/dialogue.rs | 2 +- src/ui/panels/inspector/gta6/text.rs | 2 +- src/ui/panels/inspector/gta6/text_entries.rs | 2 +- src/ui/panels/inspector/move_network.rs | 3 +- src/ui/panels/inspector/structure.rs | 8 +- src/ui/panels/inspector/ycd.rs | 6 +- src/ui/panels/inspector/ydd.rs | 2 +- src/ui/panels/inspector/yld.rs | 5 +- src/ui/panels/maps/mod.rs | 8 +- src/ui/panels/menu.rs | 4 +- src/ui/panels/meta_editor/mod.rs | 16 +- src/ui/panels/mods.rs | 10 +- src/ui/panels/overlay_copy.rs | 4 +- src/ui/panels/preview_settings.rs | 32 +- src/ui/panels/save_destination.rs | 2 +- src/ui/panels/search.rs | 67 +-- src/ui/panels/settings/editing.rs | 4 +- src/ui/panels/settings/materials.rs | 14 +- src/ui/panels/settings/overlay.rs | 6 +- src/ui/panels/statistics.rs | 16 +- src/ui/panels/status_bar.rs | 15 +- src/ui/panels/texture_preview/mod.rs | 8 +- src/ui/panels/timeline_ycd.rs | 31 +- src/ui/panels/viewport/mod.rs | 4 +- src/ui/panels/viewport/texture_badge.rs | 2 +- src/ui/panels/wardrobe/garment.rs | 17 +- src/ui/panels/wardrobe/header.rs | 31 +- src/ui/panels/wardrobe/keys.rs | 7 +- src/ui/panels/wardrobe/light.rs | 45 +- src/ui/panels/wardrobe/list.rs | 16 +- src/ui/panels/wardrobe/mesh.rs | 8 +- src/ui/panels/wardrobe/overlay.rs | 87 ++-- src/ui/panels/wardrobe/parts.rs | 49 +- src/ui/panels/wardrobe/preview.rs | 28 +- src/ui/panels/wardrobe/query_bar.rs | 8 +- src/ui/panels/wardrobe/quick.rs | 6 +- src/ui/panels/wardrobe/recover.rs | 4 +- src/ui/panels/wardrobe/tiles.rs | 28 +- src/ui/panels/wardrobe/tools.rs | 2 +- src/ui/panels/wardrobe/views.rs | 7 +- src/ui/panels/wardrobe/watched.rs | 14 +- src/ui/panels/wardrobe/wear.rs | 68 +-- src/ui/panels/weapons/list.rs | 6 +- src/ui/panels/weapons/preview.rs | 56 +-- src/ui/panels/weapons/weapon.rs | 9 +- src/ui/panels/world_viewer/plain.rs | 4 +- src/ui/panels/ycd_clips.rs | 7 +- ...ry_context_menu_draws_from_the_registry.rs | 4 +- ...nly_one_type_read_nothing_until_clicked.rs | 4 +- ...uestions_say_what_they_act_on_on_screen.rs | 8 +- src/ui/tests/the_maps_screen_on_screen.rs | 1 + .../the_top_flows_end_to_end/installs.rs | 6 +- src/ui/tests/the_top_flows_end_to_end/mod.rs | 12 +- src/video/mod.rs | 36 +- 259 files changed, 3130 insertions(+), 2219 deletions(-) create mode 100644 src/state/app_clusters.rs create mode 100644 src/state/media_playback.rs create mode 100644 src/state/workbench/dressed/controls.rs diff --git a/src/app/editor_window.rs b/src/app/editor_window.rs index 4b3e325bc..fa7306d81 100644 --- a/src/app/editor_window.rs +++ b/src/app/editor_window.rs @@ -94,7 +94,7 @@ impl App { .with_hardware_adapter(gpu.adapter.get_info().device_type != wgpu::DeviceType::Cpu) .warm_thumbnails(); - bridge.set_game_pack_path(self.app_state.game_pack.root()); + bridge.set_game_pack_path(self.app_state.install.game_pack.root()); self.editor = Some(EditorWindow { surface, bridge }); Ok(()) @@ -216,7 +216,7 @@ impl App { .with_instance(gpu.instance.clone()) .with_hardware_adapter(gpu.adapter.get_info().device_type != wgpu::DeviceType::Cpu) .warm_thumbnails(); - bridge.set_game_pack_path(self.app_state.game_pack.root()); + bridge.set_game_pack_path(self.app_state.install.game_pack.root()); bridge.set_mode(or_renderer::ShadingMode::Material); editor.bridge = bridge; self.device_retry = None; @@ -246,6 +246,7 @@ impl App { let started = Instant::now(); let acquired = surface.surface.get_current_texture(); self.app_state + .perf .frame_stats .record(FramePhase::Acquire, started.elapsed()); let output = match acquired { @@ -268,6 +269,7 @@ impl App { let started = Instant::now(); self.app_state.tick_previews(); self.app_state + .perf .frame_stats .record(FramePhase::Simulation, started.elapsed()); @@ -296,6 +298,7 @@ impl App { .egui_ctx .tessellate(full_output.shapes, full_output.pixels_per_point); self.app_state + .perf .frame_stats .record(FramePhase::UiLayout, started.elapsed()); @@ -372,6 +375,7 @@ impl App { } self.app_state + .perf .frame_stats .record(FramePhase::RenderEncode, started.elapsed()); @@ -379,6 +383,7 @@ impl App { queue.submit(std::iter::once(encoder.finish())); output.present(); self.app_state + .perf .frame_stats .record(FramePhase::Submit, started.elapsed()); @@ -457,6 +462,7 @@ impl App { editor.bridge.set_game_pack_path(&root); } self.app_state + .perf .frame_stats .record(FramePhase::Updates, started.elapsed()); self.app_state.tick_frame_stats(); diff --git a/src/app/modals.rs b/src/app/modals.rs index 53283fc3c..773c743eb 100644 --- a/src/app/modals.rs +++ b/src/app/modals.rs @@ -16,7 +16,7 @@ use crate::ui::theme; /// the same set the window does. The focus ring is last: a dialog paints its /// frame when it is drawn, over anything drawn into its layer before it. pub(crate) fn draw_editor_overlays(ctx: &Context, app_state: &mut AppState) { - if app_state.show_error_dialog { + if app_state.error_dialog.is_open() { draw_error_dialog(ctx, app_state); } crate::ui::panels::settings::draw_keys_prompt_modal(ctx, app_state); @@ -160,13 +160,13 @@ fn answered(ctx: &Context, key: &str) { } pub(super) fn draw_error_dialog(ctx: &Context, app_state: &mut AppState) { - let title = app_state.error_dialog_title.clone(); + let title = app_state.error_dialog.title.clone(); let mut close = false; question_titled(ctx, tr!("Error"), &title, 460.0, |ui| { ui.add_space(theme::SPACING_SNUG); // ⚠ The plain sentence when there is one; what the reader said is the details, and the Log's. let said = - (app_state.error_dialog_plain.as_ref()).unwrap_or(&app_state.error_dialog_message); + (app_state.error_dialog.plain.as_ref()).unwrap_or(&app_state.error_dialog.message); ui.add(egui::Label::new(said).wrap()); ui.add_space(theme::SPACING_RELAXED); ui.horizontal(|ui| { @@ -178,7 +178,7 @@ pub(super) fn draw_error_dialog(ctx: &Context, app_state: &mut AppState) { )) .clicked() { - let details = format!("{title}\n{}", app_state.error_dialog_message); + let details = format!("{title}\n{}", app_state.error_dialog.message); ui.ctx().copy_text(details); } }); @@ -190,7 +190,7 @@ pub(super) fn draw_error_dialog(ctx: &Context, app_state: &mut AppState) { } pub(super) fn draw_retail_edit_confirm_modal(ctx: &Context, app_state: &mut AppState) { - let prompt = match app_state.pending_retail_edit.as_ref() { + let prompt = match app_state.prompts.retail_edit.as_ref() { Some(p) => p.clone(), None => return, }; @@ -252,7 +252,7 @@ pub(super) fn draw_retail_edit_confirm_modal(ctx: &Context, app_state: &mut AppS } pub(super) fn draw_export_fixes_modal(ctx: &Context, app_state: &mut AppState) { - let Some(pending) = app_state.pending_export_fixes.as_ref() else { + let Some(pending) = app_state.prompts.export_fixes.as_ref() else { return; }; let drag_out = matches!(pending, PendingExportFixes::DragOut); @@ -301,7 +301,7 @@ pub(super) fn draw_export_fixes_modal(ctx: &Context, app_state: &mut AppState) { } pub(super) fn draw_enhanced_open_modal(ctx: &Context, app_state: &mut AppState) { - let prompt = match app_state.pending_enhanced_open.as_ref() { + let prompt = match app_state.prompts.enhanced_open.as_ref() { Some(p) => p.clone(), None => return, }; @@ -381,7 +381,7 @@ const STEPS_LISTED: usize = 3; /// ⚠ Hidden while the saves a Save answer started run, so the prompts they /// raise (where an archive entry goes, the edit gate) are the ones on top. pub(super) fn draw_close_prompt(ctx: &Context, app_state: &mut AppState) { - let Some(pending) = app_state.pending_close.as_ref().filter(|p| !p.saving) else { + let Some(pending) = app_state.prompts.close.as_ref().filter(|p| !p.saving) else { return; }; let before = match pending.then { @@ -485,12 +485,13 @@ pub(super) fn draw_close_prompt(ctx: &Context, app_state: &mut AppState) { /// A file changed on disk while it holds unsaved edits: reload over them, or keep them. pub(super) fn draw_reload_prompt(ctx: &Context, app_state: &mut AppState) { - if app_state.reload_conflicts.is_empty() { + if app_state.prompts.reload_conflicts.is_empty() { return; } let mut answer = None; // ⚠ A file OpenRage cooked itself from a saved source is refreshed, and nobody else changed it: the words say so. let (refreshed, changed): (Vec<&std::path::PathBuf>, Vec<&std::path::PathBuf>) = app_state + .prompts .reload_conflicts .iter() .partition(|path| app_state.workbench.refreshed.contains(*path)); diff --git a/src/audio/mod.rs b/src/audio/mod.rs index 052a4a5ca..ad6d293d2 100644 --- a/src/audio/mod.rs +++ b/src/audio/mod.rs @@ -3,15 +3,12 @@ use std::sync::Arc; -use or_io::awc::wav; -#[cfg(test)] -use or_io::awc::wav::read_wav; -use or_io::awc::{ogg, AwcFile, AwcKey}; +use or_io::awc::{AwcFile, AwcKey}; use or_media::{Codec, Decoders, MediaError}; -use crate::state::{AppState, Change, DocPayload, DocumentId, Swap}; +use crate::state::{Change, DocPayload, DocumentId, Swap}; -mod opus_job; +pub(crate) mod opus_job; /// An `.awc` as opened: its bytes, and its parse once the key it needs is known. #[derive(Clone)] @@ -99,6 +96,23 @@ impl Swap for StreamReplaced { } } +/// Builds an undo change for replacing `stream`, dropping untouched stream payloads from `before`. +pub(crate) fn stream_replaced_change(stream: usize, mut before: AwcFile) -> Change { + for (_, held) in (before.streams.iter_mut().enumerate()).filter(|(i, _)| *i != stream) { + held.chunks + .iter_mut() + .for_each(|chunk| chunk.payload = Vec::new()); + } + let replaced = StreamReplaced { + stream, + other: before, + }; + Change::Part { + key: None, + parts: vec![Box::new(replaced)], + } +} + /// One playable stream: a single-channel stream, or a multi-channel file's interleaved source. #[derive(Debug, Clone, PartialEq, Eq)] pub struct AwcStreamRow { @@ -172,7 +186,11 @@ pub fn refused_streams(file: &AwcFile, rows: &[AwcStreamRow]) -> Option<(usize, } /// Interleaved samples for a stream, with its rate and channel count. -fn stream_pcm(file: &AwcFile, stream: usize, key: AwcKey) -> Result<(Vec, u32, u16), String> { +pub(crate) fn stream_pcm( + file: &AwcFile, + stream: usize, + key: AwcKey, +) -> Result<(Vec, u32, u16), String> { let source = or_media::awc::open(file, key, stream).map_err(|e| e.to_string())?; let info = source .info() @@ -336,226 +354,45 @@ impl AudioOut { } } - /// Whether what plays goes to the silent stand-in rather than an output device. - #[cfg(test)] - pub fn is_silent(&self) -> bool { - let sink: &dyn std::any::Any = &*self.sink; - sink.is::() - } -} - -impl AppState { - fn awc_key(&self) -> AwcKey { - self.keys - .keys() - .map_or_else(AwcKey::default, |keys| AwcKey(keys.awc_key)) - } - - fn awc_file_mut(&mut self, doc: DocumentId) -> Result<&mut AwcFile, String> { - let key = self.awc_key(); - match self.document_mut(doc).map(|d| &mut d.payload) { - Some(DocPayload::Awc(awc)) => awc.file(key), - _ => Err("not an .awc document".to_string()), - } - } - - /// The container of `doc` as it was opened, before any edit. - fn awc_as_opened(&self, doc: DocumentId) -> Option { - match self.document(doc).map(|d| &d.payload) { - Some(DocPayload::Awc(awc)) => awc.as_opened(), - _ => None, - } - } - - /// The parsed container, once the AWC key, if it needs one, has unscrambled it. - pub fn awc_file(&mut self, doc: DocumentId) -> Result<&AwcFile, String> { - self.awc_file_mut(doc).map(|file| &*file) - } - - pub fn awc_streams(&mut self, doc: DocumentId) -> Result, String> { - self.awc_file(doc).map(stream_rows) - } - - /// Opens the GTA VI animation resource stream `stream` stores beside its audio, read on the loader. - pub fn awc_open_animation(&mut self, doc: DocumentId, stream: usize) -> Result<(), String> { - let path = self - .document(doc) - .and_then(|d| d.path.clone()) - .unwrap_or_default(); - let file = self.awc_file(doc)?; - let chunk = (file.streams.get(stream)) - .and_then(|s| Some((s.id, s.chunk(or_io::awc::AwcChunkKind::Animation)?))) - .ok_or_else(|| tr!("This stream stores no animation.").to_string())?; - let (id, chunk) = chunk; - let path = path.join(format!("0x{id:08X}.anim")); - let bytes = chunk.payload.clone(); - self.open_bytes(path, crate::state::DocumentKind::Gta6Anim, bytes); + /// Plays `samples` as `doc`'s `stream`, replacing whatever plays. + pub(crate) fn play_stream( + &mut self, + doc: DocumentId, + stream: usize, + rate: u32, + channels: u16, + samples: Vec, + ) -> Result<(), String> { + self.stop(); + self.sink.play(rate, channels, samples)?; + self.playing = Some((doc, stream)); Ok(()) } - /// Writes the edited animation opened from stream `stream` back as its chunk, a step of undo. - pub fn awc_put_animation(&mut self, doc: DocumentId, stream: usize) -> Result<(), String> { - if let Some(why) = self.document(doc).and_then(|d| d.read_only) { - return Err(crate::i18n::tr(why).to_string()); - } - let path = self - .document(doc) - .and_then(|d| d.path.clone()) - .unwrap_or_default(); - let id = (self.awc_file(doc)?.streams.get(stream)) - .filter(|s| s.chunk(or_io::awc::AwcChunkKind::Animation).is_some()) - .map(|s| s.id) - .ok_or_else(|| tr!("This stream stores no animation.").to_string())?; - let opened = path.join(format!("0x{id:08X}.anim")); - let (animation, sections) = (self.documents.iter()) - .find(|d| d.path.as_deref() == Some(opened.as_path())) - .and_then(|d| match &d.payload { - DocPayload::Gta6Anim(r) if r.edited => Some((d.id, r.sections.clone()?)), - _ => None, - }) - .ok_or_else(|| { - tr!("Open this stream's animation and edit it first: no edited animation of it is open.") - .to_string() - })?; - let bytes = - or_io::container::rpf::write_rpf9_resource(§ions).map_err(|e| e.to_string())?; - let file = self.awc_file_mut(doc)?; - let mut edited = file.clone(); - (edited.set_chunk_payload(stream, or_io::awc::AwcChunkKind::Animation, bytes)) - .map_err(|e| e.to_string())?; - let mut before = std::mem::replace(file, edited); - for (_, held) in (before.streams.iter_mut().enumerate()).filter(|(i, _)| *i != stream) { - held.chunks - .iter_mut() - .for_each(|chunk| chunk.payload = Vec::new()); + /// Silences `doc`'s `stream`, if it is what plays. + pub(crate) fn stop_stream(&mut self, doc: DocumentId, stream: usize) { + if self.playing == Some((doc, stream)) { + self.stop(); } - let replaced = StreamReplaced { - stream, - other: before, - }; - let change = Change::Part { - key: None, - parts: vec![Box::new(replaced)], - }; - self.record(doc, tr!("Write the edited animation back"), change); - self.say_the_animation_hashes_are_kept(animation); - Ok(()) } - /// [`refused_streams`] of `doc`, whose streams listed are `rows`. - pub fn awc_refused( - &mut self, - doc: DocumentId, - rows: &[AwcStreamRow], - ) -> Option<(usize, String)> { - refused_streams(self.awc_file(doc).ok()?, rows) + pub(crate) fn opus(&self) -> Option<&opus_job::OpusJob> { + self.opus.as_ref() } - /// A stream as a `.wav` file's bytes. - pub fn awc_wav(&mut self, doc: DocumentId, stream: usize) -> Result, String> { - let key = self.awc_key(); - let (samples, rate, channels) = stream_pcm(self.awc_file(doc)?, stream, key)?; - let pcm: Vec = samples.iter().flat_map(|s| s.to_le_bytes()).collect(); - Ok(wav::wav_from_pcm16(&pcm, rate, channels)) + pub(crate) fn set_opus(&mut self, job: opus_job::OpusJob) { + self.opus = Some(job); } - /// A GTA VI stream's Opus packets as `awc export` writes them: Ogg Opus files named for each stream's or channel's id. - pub fn awc_ogg_opus( - &mut self, - doc: DocumentId, - stream: usize, - ) -> Result)>, String> { - let groups = (self.awc_file(doc)?.opus_streams(stream)).map_err(|e| e.to_string())?; - groups - .iter() - .map(|g| { - // A stream that speaks a dialogue line found carries the line as comments. - let comments = crate::state::gta6_dialogue::comments(g.id); - Ok(( - format!("{:08X}.opus", g.id), - ogg::ogg_opus_tagged(g, &comments).map_err(|e| e.to_string())?, - )) - }) - .collect() + pub(crate) fn take_opus(&mut self) -> Option { + self.opus.take() } - pub fn awc_play(&mut self, doc: DocumentId, stream: usize) -> Result<(), String> { - let key = self.awc_key(); - let (samples, rate, channels) = stream_pcm(self.awc_file(doc)?, stream, key)?; - self.audio.stop(); - self.audio.sink.play(rate, channels, samples)?; - self.audio.playing = Some((doc, stream)); - Ok(()) - } - - /// Replace a stream's samples from a `.wav` file's bytes, re-encoded to the stream's codec. + /// Whether what plays goes to the silent stand-in rather than an output device. #[cfg(test)] - pub fn awc_replace( - &mut self, - doc: DocumentId, - stream: usize, - wav: &[u8], - ) -> Result<(), String> { - self.awc_writable(doc)?; - let (pcm, rate, channels) = read_wav(wav).map_err(|e| e.to_string())?; - let key = self.awc_key(); - let file = self.awc_file_mut(doc)?; - let rows = or_media::awc::streams(file); - let opus = rows - .iter() - .any(|r| r.stream == stream && r.info.codec == Codec::Opus); - let spectra = (rows.iter()).any(|r| r.stream == stream && r.info.codec == Codec::Spectra); - let edited = if opus { - let edited = or_media::opus::replaced(file, stream, &pcm, rate, channels); - edited.map_err(|e| e.to_string()) - } else if spectra { - let edited = or_media::spectra::replaced(file, stream, &pcm, rate, channels); - edited.map_err(|e| e.to_string()) - } else { - let edited = file.with_stream_replaced(stream, &pcm, rate, channels, key); - edited.map_err(|e| e.to_string()) - }?; - self.awc_replaced(doc, stream, edited) - } - - /// `Err` saying why `doc` takes no replace: read-only for any reason but being a body a scan - /// found, whose Save As writes the replaced container. - fn awc_writable(&self, doc: DocumentId) -> Result<(), String> { - match self.document(doc).and_then(|d| d.read_only) { - Some(why) if why != crate::state::rpf9_scan::READ_ONLY_BODY => { - Err(crate::i18n::tr(why).to_string()) - } - _ => Ok(()), - } - } - - /// `edited`, stream `stream` of `doc` replaced in it, made the document's container as an edit. - fn awc_replaced( - &mut self, - doc: DocumentId, - stream: usize, - edited: AwcFile, - ) -> Result<(), String> { - let file = self.awc_file_mut(doc)?; - let mut before = std::mem::replace(file, edited); - if self.audio.playing == Some((doc, stream)) { - self.audio.stop(); - } - for (_, held) in (before.streams.iter_mut().enumerate()).filter(|(i, _)| *i != stream) { - held.chunks - .iter_mut() - .for_each(|chunk| chunk.payload = Vec::new()); - } - let replaced = StreamReplaced { - stream, - other: before, - }; - let change = Change::Part { - key: None, - parts: vec![Box::new(replaced)], - }; - self.record(doc, format!("Replace stream {stream}"), change); - Ok(()) + pub fn is_silent(&self) -> bool { + let sink: &dyn std::any::Any = &*self.sink; + sink.is::() } } diff --git a/src/audio/opus_job.rs b/src/audio/opus_job.rs index be6c11633..9b42337ff 100644 --- a/src/audio/opus_job.rs +++ b/src/audio/opus_job.rs @@ -1,7 +1,7 @@ //! A GTA VI stream's Opus decoded to play or to export as WAV, or encoded anew from a WAV, on a //! worker as a row of the job list with its progress and Cancel. -use std::path::{Path, PathBuf}; +use std::path::PathBuf; use std::sync::{Arc, Mutex, MutexGuard}; use or_io::awc::opus::OpusStream; @@ -12,16 +12,15 @@ use or_io::awc::{AwcFile, AwcKey}; use or_job::{Cancel, Progress}; use or_media::replace::{replaced_with_markers, Length, Replaced, XmaMarkers}; -use crate::state::jobs::{JobKind, Outcome, RunningJob, Then}; -use crate::state::{AppState, DocumentId}; +use crate::state::DocumentId; /// The rate every Opus stream decodes and encodes at. -const RATE: u32 = 48_000; +pub(crate) const RATE: u32 = 48_000; /// What the worker makes of a stream. // One value a job, handed to its worker once: boxing its containers would buy nothing. #[allow(clippy::large_enum_variant)] -enum Work { +pub(crate) enum Work { /// Its samples, played, or written as a WAV at the path. Decode { groups: Vec, @@ -48,7 +47,7 @@ enum Work { } /// What the worker made. -enum Made { +pub(crate) enum Made { /// Interleaved samples and their channel count. Samples(Vec, u16), Written(PathBuf), @@ -60,19 +59,25 @@ enum Made { } /// One stream's decode or encode on a worker. -pub(super) struct OpusJob { - doc: DocumentId, - stream: usize, +pub(crate) struct OpusJob { + pub(crate) doc: DocumentId, + pub(crate) stream: usize, /// Where the document's history stood at the start, which a replace must still find. - at: u64, - doing: &'static str, - cancel: Cancel, - progress: Progress, + pub(crate) at: u64, + pub(crate) doing: &'static str, + pub(crate) cancel: Cancel, + pub(crate) progress: Progress, ended: Arc>>>, } impl OpusJob { - fn start(doc: DocumentId, stream: usize, at: u64, doing: &'static str, work: Work) -> Self { + pub(crate) fn start( + doc: DocumentId, + stream: usize, + at: u64, + doing: &'static str, + work: Work, + ) -> Self { let job = Self { doc, stream, @@ -101,7 +106,7 @@ impl OpusJob { } /// What the worker made, `None` while it runs. - fn ended(&self) -> MutexGuard<'_, Option>> { + pub(crate) fn ended(&self) -> MutexGuard<'_, Option>> { self.ended.lock().unwrap_or_else(|p| p.into_inner()) } } @@ -167,187 +172,3 @@ fn run(work: Work, watch: or_media::opus::Watch<'_>) -> Result { } } } - -impl AppState { - /// Plays Opus stream `stream` of `doc`, or writes it as a WAV at `wav`, decoded on a worker. - pub fn awc_opus_decode( - &mut self, - doc: DocumentId, - stream: usize, - wav: Option, - ) -> Result<(), String> { - if let Some(ref path) = wav { - match self.gate_permits(Some(path)) { - crate::state::GateOutcome::Proceed => {} - crate::state::GateOutcome::Refused => return Ok(()), - crate::state::GateOutcome::Confirm(_) => { - return Err(crate::state::gta6_modding::mod_package::in_game_folder( - path, - )); - } - } - } - let groups = or_media::awc::opus_groups(self.awc_file(doc)?, stream); - let groups = groups.map_err(|e| e.to_string())?; - let doing = if wav.is_some() { - tr!("Decoding an Opus stream to WAV") - } else { - tr!("Decoding an Opus stream to play it") - }; - self.start_opus(doc, stream, doing, Work::Decode { groups, wav }); - Ok(()) - } - - /// Replaces Opus stream `stream` of `doc` from the WAV at `from`, encoded on a worker. - #[cfg(test)] - pub fn awc_opus_replace( - &mut self, - doc: DocumentId, - stream: usize, - from: PathBuf, - ) -> Result<(), String> { - self.awc_writable(doc)?; - let file = self.awc_file(doc)?.clone(); - let doing = tr!("Encoding an Opus stream from a WAV"); - self.start_opus(doc, stream, doing, Work::Encode { file, stream, from }); - Ok(()) - } - - /// Replaces stream `stream` of `doc`, of any codec OpenRage encodes, from the WAV at `from`, - /// fitted to the stream and encoded on a worker. - pub fn awc_replace_from( - &mut self, - doc: DocumentId, - stream: usize, - from: PathBuf, - ) -> Result<(), String> { - self.awc_replace_with(doc, stream, from, XmaMarkers::Keep) - } - - /// [`Self::awc_replace_from`], an XMA stream's granular and marker chunks as `markers` says. - pub fn awc_replace_with( - &mut self, - doc: DocumentId, - stream: usize, - from: PathBuf, - markers: XmaMarkers, - ) -> Result<(), String> { - self.awc_writable(doc)?; - let key = self.awc_key(); - let file = self.awc_file(doc)?.clone(); - let target = or_media::replace::target(&file, stream).map_err(|e| e.to_string())?; - let length = crate::state::gta6_modding::audio_replace::length_for(&target); - let as_read = self.awc_as_opened(doc); - let doing = tr!("Encoding an audio stream from a WAV"); - let work = Work::Fit { - file, - stream, - from, - key, - length, - markers, - as_read, - }; - self.start_opus(doc, stream, doing, work); - Ok(()) - } - - fn start_opus(&mut self, doc: DocumentId, stream: usize, doing: &'static str, work: Work) { - let at = self.document(doc).map_or(0, |d| d.history.at()); - self.audio.opus = Some(OpusJob::start(doc, stream, at, doing, work)); - } - - /// The Opus job, while it runs, as the job list draws it. - pub(crate) fn awc_opus_job(&self) -> Option { - let job = self.audio.opus.as_ref()?; - if job.ended().is_some() { - return None; - } - Some(RunningJob { - kind: JobKind::OpusAudio, - doing: job.doing.to_string(), - fraction: Some(job.progress.snapshot().fraction()), - detail: String::new(), - stopping: job.cancel.is_set(), - }) - } - - /// Asks the Opus job to stop; [`Self::poll_awc_opus`] says how it ended. - pub(crate) fn stop_awc_opus(&self) { - if let Some(job) = &self.audio.opus { - job.cancel.set(); - } - } - - /// Plays, reports or applies what the Opus job made, once it has ended. - pub(crate) fn poll_awc_opus(&mut self) { - let Some(made) = (self.audio.opus.as_ref()).and_then(|job| job.ended().take()) else { - return; - }; - let Some(job) = self.audio.opus.take() else { - return; - }; - let kind = JobKind::OpusAudio; - if job.cancel.is_set() { - let said = tr!("Stopped before it finished"); - self.jobs - .record(kind, Outcome::Stopped(Then::Nothing), said); - return; - } - let at = self.document(job.doc).map(|d| d.history.at()); - let ended = match made { - Err(why) => Err(why), - // A stream of a document closed since is not played. - Ok(Made::Samples(..)) if at.is_none() => Ok(None), - Ok(Made::Samples(pcm, channels)) => { - self.audio.stop(); - let played = self.audio.sink.play(RATE, channels, pcm); - if played.is_ok() { - self.audio.playing = Some((job.doc, job.stream)); - } - played.map(|()| None) - } - Ok(Made::Written(path)) => { - let folder = path.parent().map(Path::to_path_buf).unwrap_or_default(); - let said = tr!("Wrote {path}", path = path.display()); - Ok(Some((Then::OpenFolder(folder), said))) - } - // An edit made or undone while the worker ran is not dropped by the replace. - #[cfg(test)] - Ok(Made::Replaced(..)) if at != Some(job.at) => { - let why = tr!( - "The container changed while its stream was encoded, so the replace is dropped: replace it again" - ); - Err(why.to_string()) - } - Ok(Made::Fitted(..)) if at != Some(job.at) => { - let why = tr!( - "The container changed while its stream was encoded, so the replace is dropped: replace it again" - ); - Err(why.to_string()) - } - #[cfg(test)] - Ok(Made::Replaced(edited, from)) => { - let said = tr!("Replaced the stream from {path}", path = from.display()); - let replaced = self.awc_replaced(job.doc, job.stream, edited); - replaced.map(|()| Some((Then::Show(job.doc), said))) - } - Ok(Made::Fitted(replaced, from)) => { - let said = crate::state::gta6_modding::audio_replace::said(&replaced, &from); - let edited = self.awc_replaced(job.doc, job.stream, replaced.file); - edited.map(|()| Some((Then::Show(job.doc), said))) - } - }; - match ended { - Ok(None) => {} - Ok(Some((then, said))) => { - self.show_toast(said.clone()); - self.jobs.record(kind, Outcome::Done(then), said); - } - Err(why) => { - self.show_error_toast(why.clone()); - self.jobs.record(kind, Outcome::Failed, why); - } - } - } -} diff --git a/src/photo/mod.rs b/src/photo/mod.rs index ff158b969..f739968fc 100644 --- a/src/photo/mod.rs +++ b/src/photo/mod.rs @@ -273,7 +273,7 @@ fn photograph_all(options: &Options) -> Result { or_title::config::set_config_dir_override(scratch.0.join("config")); } let mut bridge = timing::time("02 boot: gpu", crate::self_check::headless_bridge)?; - let pack = state.game_pack.root().to_path_buf(); + let pack = state.install.game_pack.root().to_path_buf(); match timing::time("03 boot: shader pack", || bridge.set_game_pack_path(&pack)) { true => { println!("drawn with the game's own shaders, from {}", pack.display()); diff --git a/src/photo/serve.rs b/src/photo/serve.rs index 8fc135e15..a4616638e 100644 --- a/src/photo/serve.rs +++ b/src/photo/serve.rs @@ -120,7 +120,7 @@ fn serve() -> Result<(), String> { // ⚠ Only once the state has read the user's keys and install: anything written is otherwise saved among the user's own. or_title::config::set_config_dir_override(scratch.join("config")); let mut bridge = crate::self_check::headless_bridge()?; - let pack = state.game_pack.root().to_path_buf(); + let pack = state.install.game_pack.root().to_path_buf(); if bridge.set_game_pack_path(&pack) { // A white sun and a grey ambient: a picture of a garment is of no hour of the day bridge.set_game_light(glam::Vec3::ONE, glam::Vec3::splat(0.3)); diff --git a/src/render/game_scene/mod.rs b/src/render/game_scene/mod.rs index ea0cf3651..376698711 100644 --- a/src/render/game_scene/mod.rs +++ b/src/render/game_scene/mod.rs @@ -188,7 +188,12 @@ fn surfaces_with_wheels( } } let mut surfaces = surfaces_of(scene, &found); - let bound = state.anim.binding.as_ref().map(|binding| &binding.skeleton); + let bound = state + .animation + .session + .binding + .as_ref() + .map(|binding| &binding.skeleton); rebind_joints(&mut surfaces, &skeleton_tags(scene), |tag| { bound.and_then(|skeleton| skeleton.index_for_tag(tag)) }); diff --git a/src/render/gta6_trace.rs b/src/render/gta6_trace.rs index aeea103b9..0c7d6ce69 100644 --- a/src/render/gta6_trace.rs +++ b/src/render/gta6_trace.rs @@ -186,7 +186,7 @@ impl Glue { } _ => building(), }; - match state.anim.skin_matrices.is_empty() { + match state.animation.session.skin_matrices.is_empty() { true => said, false => format!( "{said}\n{}", diff --git a/src/render/meshes.rs b/src/render/meshes.rs index 172c5de83..61b867e81 100644 --- a/src/render/meshes.rs +++ b/src/render/meshes.rs @@ -279,7 +279,7 @@ pub(crate) mod rows { DocPayload::Resource(or_io::Asset::Bounds(bound)) => { crate::render::bound_meshes::build_bound_meshes( bound, - req.state.materials_palette.palette_ref(), + req.state.install.materials_palette.palette_ref(), ) } _ => Vec::new(), @@ -297,7 +297,7 @@ pub(crate) mod rows { if let Some(bound) = cloth.bound_composite.as_ref() { meshes.extend(crate::render::bound_meshes::build_composite_meshes( bound, - req.state.materials_palette.palette_ref(), + req.state.install.materials_palette.palette_ref(), )); } meshes diff --git a/src/render/viewport/bones.rs b/src/render/viewport/bones.rs index e1658c548..393d0db50 100644 --- a/src/render/viewport/bones.rs +++ b/src/render/viewport/bones.rs @@ -157,17 +157,17 @@ pub(super) fn shown(state: &AppState) -> Vec> { }); (sources(state).into_iter()) .map(|(doc, named, data)| { - let posed = (state.anim.skeleton()).filter(|skeleton| { + let posed = (state.animation.session.skeleton()).filter(|skeleton| { animation && skeleton.bone_count() == data.bones.len() - && state.anim.world_matrices.len() == skeleton.bone_count() + && state.animation.session.world_matrices.len() == skeleton.bone_count() }); match posed { Some(skeleton) => Shown { doc, named, skeleton: Rest::Posed(skeleton), - posed: Some(&state.anim.world_matrices), + posed: Some(&state.animation.session.world_matrices), }, None => Shown { doc, diff --git a/src/render/viewport/day.rs b/src/render/viewport/day.rs index 63d46d6ae..b124864a0 100644 --- a/src/render/viewport/day.rs +++ b/src/render/viewport/day.rs @@ -201,7 +201,7 @@ impl RenderBridge { }; self.refresh_sky_textures(state); let (hour, weather) = (session.hour(), session.weather()); - let data = state.clip_regions.timecycle(); + let data = state.install.clip_regions.timecycle(); let key = (Arc::as_ptr(&data) as usize, hour.to_bits(), weather); if self.game_scene.world_day_key == Some(key) { return; @@ -248,7 +248,7 @@ impl RenderBridge { return; } self.game_scene.world_day_key = None; - let data = state.clip_regions.timecycle(); + let data = state.install.clip_regions.timecycle(); let hour = state.drivers.time_of_day.hour; let weather = state.drivers.weather.state; let days = state.drivers.time_of_day.days; @@ -294,7 +294,7 @@ impl RenderBridge { let light = state.workbench.wardrobe.dressed.light; let sun = light.sun.then(|| { let time = &state.drivers.time_of_day; - let data = state.clip_regions.timecycle(); + let data = state.install.clip_regions.timecycle(); sun_towards(&data, time.hour, time.days, state.drivers.weather.state) }); (sun.flatten().unwrap_or_else(|| light.way()), light.strength) diff --git a/src/render/viewport/game_shaders.rs b/src/render/viewport/game_shaders.rs index a3858c4db..8c1bbbf1b 100644 --- a/src/render/viewport/game_shaders.rs +++ b/src/render/viewport/game_shaders.rs @@ -179,13 +179,17 @@ impl RenderBridge { /// Give the game's passes the pose the animation holds, which is by bone of the skeleton the surfaces were bound to, when it has changed. fn refresh_skin(&mut self, state: &AppState) { - let key = (state.anim.skin_revision(), state.anim.skin_matrices.len()); + let key = ( + state.animation.session.skin_revision(), + state.animation.session.skin_matrices.len(), + ); if self.game_scene.skin_key == Some(key) { return; } self.game_scene.skin_key = Some(key); self.dressed.held.skin_key = None; - self.renderer.set_skin(state.anim.skin_matrices.clone()); + self.renderer + .set_skin(state.animation.session.skin_matrices.clone()); } pub(super) fn drop_game_scene(&mut self) { @@ -201,13 +205,13 @@ impl RenderBridge { /// Hand the renderer the stars, the moon's face and the water's maps of the install, when they were read again. pub(super) fn refresh_sky_textures(&mut self, state: &AppState) { - let revision = state.clip_regions.sky_revision(); + let revision = state.install.clip_regions.sky_revision(); if self.game_scene.sky_textures_of != revision { self.game_scene.sky_textures_of = revision; self.renderer - .set_sky_textures((*state.clip_regions.sky_textures()).clone()); + .set_sky_textures((*state.install.clip_regions.sky_textures()).clone()); self.renderer - .set_water_textures((*state.clip_regions.water_textures()).clone()); + .set_water_textures((*state.install.clip_regions.water_textures()).clone()); } } diff --git a/src/render/viewport/mod.rs b/src/render/viewport/mod.rs index 4f2608724..fc79bdb90 100644 --- a/src/render/viewport/mod.rs +++ b/src/render/viewport/mod.rs @@ -290,7 +290,7 @@ impl RenderBridge { crate::render::particles::gta6::prime(&mut self.particles.textures, state, doc_id); self.particles.model_meshes.invalidate_for_doc(doc_id); - let clip_regions = state.clip_regions.table(); + let clip_regions = state.install.clip_regions.table(); let retail_parity = matches!(self.frame.mode, ShadingMode::Shaded); let batches = crate::render::particles::build_batches( &mut self.particles.textures, @@ -323,7 +323,7 @@ impl RenderBridge { ); self.renderer.set_model_batches(model_batches); - crate::render::particle_air::give(&mut self.renderer, &state.ptfx_sinks); + crate::render::particle_air::give(&mut self.renderer, &state.sim.sinks); } pub fn texture_id(&self) -> Option { @@ -638,8 +638,8 @@ impl RenderBridge { self.doc_cache .gpu_textures .set_budget(state.prefs.gpu_texture_budget()); - state.gpu_usage = self.gpu_usage(); - state.gpu_stages = self.renderer.gpu_stages(); + state.perf.gpu_usage = self.gpu_usage(); + state.perf.gpu_stages = self.renderer.gpu_stages(); if !self.frame.visible { return false; @@ -980,14 +980,14 @@ mod tests { return; }; // The same pose as no pose: every bone where it is - state.anim.skin_matrices = vec![glam::Mat4::IDENTITY; 512]; + state.animation.session.skin_matrices = vec![glam::Mat4::IDENTITY; 512]; bridge.refresh_game_scene(&state); let same = bridge .render_pass(&camera, ShadingMode::Shaded, PX) .unwrap(); assert_eq!(same, rest, "{}: a pose at rest moved it", path.display()); // A pose that carries every bone far off carries the drawable with it; the session numbers its poses, which this test does not, so this one has a bone more - state.anim.skin_matrices = + state.animation.session.skin_matrices = vec![glam::Mat4::from_translation(glam::Vec3::splat(1.0e4)); 513]; bridge.refresh_game_scene(&state); let moved = bridge diff --git a/src/render/viewport/pick.rs b/src/render/viewport/pick.rs index 5e9984bab..5ff6ca53e 100644 --- a/src/render/viewport/pick.rs +++ b/src/render/viewport/pick.rs @@ -384,7 +384,7 @@ fn gta6_part(state: &AppState, doc: DocumentId, ray: &Ray) -> Option { /// The retarget and the pose the viewport's mesh cache and skinning give an upload. fn posed_as_drawn(upload: &mut MeshUpload, state: &AppState) { - if let Some(binding) = &state.anim.binding { + if let Some(binding) = &state.animation.session.binding { upload.retarget_onto(&binding.skeleton); } upload.apply_pose( diff --git a/src/render/viewport/pick_lines.rs b/src/render/viewport/pick_lines.rs index 109f51042..32137504e 100644 --- a/src/render/viewport/pick_lines.rs +++ b/src/render/viewport/pick_lines.rs @@ -125,7 +125,7 @@ pub(super) fn bound_mesh_under(state: &AppState, ray: &Ray) -> Option { let DocPayload::Resource(or_io::Asset::Bounds(bound)) = &state.document(doc)?.payload else { return None; }; - let palette = state.materials_palette.palette_ref(); + let palette = state.install.materials_palette.palette_ref(); let mut best: Option<(f32, u64)> = None; for (row, meshes) in bound_node_meshes(bound, palette) { for upload in &meshes { diff --git a/src/render/viewport/posing.rs b/src/render/viewport/posing.rs index b1239cf1a..634648038 100644 --- a/src/render/viewport/posing.rs +++ b/src/render/viewport/posing.rs @@ -38,5 +38,8 @@ pub(crate) fn skin_of(state: &AppState) -> (u64, &[glam::Mat4]) { return crate::state::gta6_anim_play::gta6_drawn(state) .map_or((0, &[][..]), |p| (p.revision, p.skin)); } - (state.anim.skin_revision(), &state.anim.skin_matrices) + ( + state.animation.session.skin_revision(), + &state.animation.session.skin_matrices, + ) } diff --git a/src/render/viewport/retarget.rs b/src/render/viewport/retarget.rs index fa93b2f81..ce3c941f6 100644 --- a/src/render/viewport/retarget.rs +++ b/src/render/viewport/retarget.rs @@ -43,7 +43,11 @@ pub(super) fn anim_scene_signature(state: &AppState) -> u64 { None => 0u8.hash(&mut hasher), } scene.draw_skeleton_model.hash(&mut hasher); - state.anim.skeleton_built_from().hash(&mut hasher); + state + .animation + .session + .skeleton_built_from() + .hash(&mut hasher); hasher.finish() | 1 } @@ -59,7 +63,7 @@ pub(super) fn retarget_uploads( uploads: &mut [MeshUpload], state: &AppState, ) -> Option { - let target = &state.anim.binding.as_ref()?.skeleton; + let target = &state.animation.session.binding.as_ref()?.skeleton; let mut total: Option = None; for upload in uploads.iter_mut() { let Some(one) = upload.retarget_onto(target) else { @@ -112,7 +116,7 @@ mod tests { fn bound_to(tags: &[u16]) -> AppState { let mut state = AppState::new(); - state.anim.binding = Some(or_anim::BoundClip { + state.animation.session.binding = Some(or_anim::BoundClip { skeleton: skeleton_of(tags), report: Default::default(), clip_name: "t".into(), diff --git a/src/self_check/mod.rs b/src/self_check/mod.rs index d674e041e..41a56f182 100644 --- a/src/self_check/mod.rs +++ b/src/self_check/mod.rs @@ -302,7 +302,7 @@ fn run_removing(options: Options, scratch: Option) -> i32 { let mut state = AppState::new(); // ⚠ The editor's frame records the installs discovery found; no frame here polls it. let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30); - while state.discovery.is_running() && std::time::Instant::now() < deadline { + while state.bg.discovery.is_running() && std::time::Instant::now() < deadline { std::thread::sleep(std::time::Duration::from_millis(10)); state.poll_game_discovery(); } @@ -504,15 +504,15 @@ fn run_removing(options: Options, scratch: Option) -> i32 { options.frames, |state| { let file = std::path::PathBuf::from("C:/mods/smoke.ypt"); - state.reload_conflicts.push(file); + state.prompts.reload_conflicts.push(file); }, - |state| state.reload_conflicts.clear(), + |state| state.prompts.reload_conflicts.clear(), ), ); report.record( "delete question", draw_file_prompt(&mut state, options.frames, |state| { - state.pending_delete = Some(crate::state::delete_prompt::PendingDelete { + state.prompts.delete = Some(crate::state::delete_prompt::PendingDelete { doc_id: crate::state::DocumentId(0), node_id: crate::state::RpfNodeId(0), name: "props".into(), @@ -526,7 +526,7 @@ fn run_removing(options: Options, scratch: Option) -> i32 { report.record( "extraction clash question", draw_file_prompt(&mut state, options.frames, |state| { - state.extract_jobs.clash = Some(crate::state::extract_job::ExtractClash { + state.bg.extract_jobs.clash = Some(crate::state::extract_job::ExtractClash { doc_id: crate::state::DocumentId(0), nodes: Vec::new(), dest: "out".into(), @@ -542,7 +542,7 @@ fn run_removing(options: Options, scratch: Option) -> i32 { report.record( "refused write prompt", draw_file_prompt(&mut state, options.frames, |state| { - state.refused_write = Some("C:/Games/GTAV/update/update.rpf".into()); + state.prompts.refused_write = Some("C:/Games/GTAV/update/update.rpf".into()); }), ); @@ -707,7 +707,7 @@ fn open_unit( else { report.record( what, - Err(format!("did not open: {}", state.error_dialog_message)), + Err(format!("did not open: {}", state.error_dialog.message)), ); return; }; @@ -877,9 +877,9 @@ fn draw_question( fn draw_file_prompt(state: &mut AppState, frames: usize, ask: fn(&mut AppState)) -> Outcome { let without = draw_unit(state, None, frames, |_| {})?; let with = draw_unit(state, None, frames, ask); - state.pending_delete = None; - state.extract_jobs.clash = None; - state.refused_write = None; + state.prompts.delete = None; + state.bg.extract_jobs.clash = None; + state.prompts.refused_write = None; let with = with?; if with.vertices > without.vertices { Ok(with) diff --git a/src/self_check/shots/lost_device.rs b/src/self_check/shots/lost_device.rs index 63721d827..c5c74cca9 100644 --- a/src/self_check/shots/lost_device.rs +++ b/src/self_check/shots/lost_device.rs @@ -17,7 +17,7 @@ impl Shell { pub(super) fn on(state: &AppState, device: Arc, queue: Arc) -> Self { let mut bridge = RenderBridge::new(device.clone(), queue.clone(), FORMAT); // A pack baked elsewhere is named by `OPENRAGE_GAME_PACK`; without one the mode is not offered - bridge.set_game_pack_path(state.game_pack.root()); + bridge.set_game_pack_path(state.install.game_pack.root()); Shell { bridge, renderer: egui_wgpu::Renderer::new( diff --git a/src/self_check/shots/perf.rs b/src/self_check/shots/perf.rs index 0308aac96..8b951f046 100644 --- a/src/self_check/shots/perf.rs +++ b/src/self_check/shots/perf.rs @@ -59,7 +59,7 @@ impl Shell { let drawn = self.bridge.world_drawn(); let sets = self.bridge.world_sets(); let stage = |name: &str| { - (state.gpu_stages.iter()) + (state.perf.gpu_stages.iter()) .find(|(s, _)| *s == name) .map(|s| s.1) }; @@ -74,11 +74,11 @@ impl Shell { "occlude_ms": ms(cost.occlude), "cull_ms": ms(cost.cull), "layout_ms": ms(cost.layout), - "gpu_ms": state.gpu_stages.iter().map(|(_, t)| f64::from(*t)).sum::(), + "gpu_ms": state.perf.gpu_stages.iter().map(|(_, t)| f64::from(*t)).sum::(), "gpu_gbuffer_ms": stage("g-buffer"), "gpu_shadows_ms": stage("shadows"), "gpu_lighting_ms": stage("lighting"), - "gpu_stages": state.gpu_stages.iter().map(|(s, t)| json!([s, t])).collect::>(), + "gpu_stages": state.perf.gpu_stages.iter().map(|(s, t)| json!([s, t])).collect::>(), "selected": drawn.selected, "seen": drawn.seen, "laid_instances": cost.laid_instances, diff --git a/src/self_check/shots/waits.rs b/src/self_check/shots/waits.rs index 823f77591..918f656d0 100644 --- a/src/self_check/shots/waits.rs +++ b/src/self_check/shots/waits.rs @@ -44,7 +44,7 @@ pub(crate) fn open_and_wait( { Some(doc) => println!(" opened as {:?}", doc.kind()), // Not an error: a script may open a broken file to draw the dialog. - None => println!(" did not open: {}", state.error_dialog_message), + None => println!(" did not open: {}", state.error_dialog.message), } Ok(()) } @@ -64,7 +64,7 @@ fn wait_for_rows( .documents .iter() .find(|d| d.path.as_deref() == Some(path)); - let reading = opened.is_some_and(|doc| state.expander.is_listing(doc.id)); + let reading = opened.is_some_and(|doc| state.bg.expander.is_listing(doc.id)); if !reading && !matches!(state.loading, LoadingState::Loading) { return Ok(()); } diff --git a/src/self_check/shots/world_fed.rs b/src/self_check/shots/world_fed.rs index 0a06bda27..f643dfa23 100644 --- a/src/self_check/shots/world_fed.rs +++ b/src/self_check/shots/world_fed.rs @@ -114,9 +114,9 @@ impl Shell { // A script's run reads the pack of the game's shaders when it first asks for a frame drawn by them, as the editor reads it when it is baked. if *mode == or_renderer::ShadingMode::Shaded && !self.bridge.game_shaders_available() - && !self.bridge.set_game_pack_path(state.game_pack.root()) + && !self.bridge.set_game_pack_path(state.install.game_pack.root()) { - let root = state.game_pack.root().display(); + let root = state.install.game_pack.root().display(); return Err(format!("no pack of the game's shaders is read at {root}")); } self.bridge.set_world_mode(*mode); diff --git a/src/self_check/units.rs b/src/self_check/units.rs index 7bb303455..71aef6916 100644 --- a/src/self_check/units.rs +++ b/src/self_check/units.rs @@ -723,14 +723,14 @@ fn texture_preview_units( ]; for (what, payload) in previewed { let outcome = payload.and_then(|payload| { - let before = state.texture_cache.bytes(); + let before = state.textures.cache.bytes(); kind_panel( state, bridge.as_deref_mut(), frames, ids::TEXTURE_PREVIEW, payload, - |state| state.texture_cache.bytes() > before, + |state| state.textures.cache.bytes() > before, ) }); report.record(what, outcome); diff --git a/src/state/animation_session.rs b/src/state/animation_session.rs index 002b94c0e..960bd155b 100644 --- a/src/state/animation_session.rs +++ b/src/state/animation_session.rs @@ -42,7 +42,7 @@ impl AppState { let suggestion = crate::state::preview_scene::suggest_skeleton(&tags, &candidates); if self.preview_scene.adopt_suggested_skeleton(suggestion) { - self.anim.invalidate(); + self.animation.session.invalidate(); } } @@ -53,7 +53,7 @@ impl AppState { .collect(); for id in stale { if self.preview_scene.forget_document(id) { - self.anim.invalidate(); + self.animation.session.invalidate(); } } @@ -63,20 +63,23 @@ impl AppState { self.resolve_skeleton_automatically(); if self - .anim + .animation + .session .needs_rebuild(&self.preview_scene, self.skeleton_epoch()) { self.rebuild_anim_session(); } let dt = self.sim.step_real_dt(); - let _ = self.anim_transport.take_seek(); - self.anim_transport.tick(dt); - let time = self.anim_transport.time; + let _ = self.animation.transport.take_seek(); + self.animation.transport.tick(dt); + let time = self.animation.transport.time; let apply_root_motion = self.preview_scene.apply_root_motion; - let edits = std::mem::take(&mut self.anim_edits); - self.anim.evaluate(time, apply_root_motion, &edits); - self.anim_edits = edits; + let edits = std::mem::take(&mut self.animation.edits); + self.animation + .session + .evaluate(time, apply_root_motion, &edits); + self.animation.edits = edits; } /// Record the pose layer as it stood `before` an edit, as a step of the clip's document. @@ -89,7 +92,7 @@ impl AppState { else { return; }; - if before == self.anim_edits { + if before == self.animation.edits { return; } self.record(document, label, Change::Pose(before)); @@ -153,17 +156,17 @@ impl AppState { } pub fn bake_anim_edits(&mut self) -> Result, String> { - if self.anim_edits.is_empty() { + if self.animation.edits.is_empty() { return Ok(None); } let Some(selection) = self.preview_scene.clip else { return Ok(None); }; - let Some(binding) = self.anim.binding.as_ref() else { + let Some(binding) = self.animation.session.binding.as_ref() else { return Err("no skeleton is bound, so edits cannot be baked".to_string()); }; let skeleton = binding.skeleton.clone(); - let edits = std::mem::take(&mut self.anim_edits); + let edits = std::mem::take(&mut self.animation.edits); let edit_count = edits.len(); // ⚠ Before the bake changes the clips: `mark_edited` after it would read them over. @@ -180,7 +183,7 @@ impl AppState { let baked = match baked { Ok(baked) => baked, Err(reason) => { - self.anim_edits = edits; + self.animation.edits = edits; return Err(reason); } }; @@ -202,7 +205,7 @@ impl AppState { if let Some(doc) = self.document_mut(selection.document) { doc.mark_edited(); } - self.anim.invalidate(); + self.animation.session.invalidate(); Ok(Some(summary)) } @@ -260,9 +263,9 @@ impl AppState { let epoch = self.skeleton_epoch(); // ⚠ Read before the install, which sets it: only another clip or skeleton source is a new choice. // Whatever else asks for a rebuild (a key, an edit, a bake, a toggle) leaves the user's working range and Loop. - let same_choice = self.anim.holds_the_transport_for(&scene); + let same_choice = self.animation.session.holds_the_transport_for(&scene); let Some((clip, skeleton_source)) = scene.clip.zip(scene.skeleton_source) else { - self.anim.clear(&scene, epoch); + self.animation.session.clear(&scene, epoch); return; }; @@ -294,19 +297,21 @@ impl AppState { tags = binding.report.clip_tags(), "clip does not match the selected skeleton; not playing" ); - self.anim.clear(&scene, epoch); - self.anim.binding = Some(binding); + self.animation.session.clear(&scene, epoch); + self.animation.session.binding = Some(binding); return; } if same_choice { - let looped_changed = self.anim.looped_changed(&player); - follow_the_clip(looped_changed, &player, &mut self.anim_transport); + let looped_changed = self.animation.session.looped_changed(&player); + follow_the_clip(looped_changed, &player, &mut self.animation.transport); } else { - player.configure_transport(&mut self.anim_transport); + player.configure_transport(&mut self.animation.transport); } - self.anim.install(&scene, epoch, player, binding); + self.animation + .session + .install(&scene, epoch, player, binding); } - None => self.anim.clear(&scene, epoch), + None => self.animation.session.clear(&scene, epoch), } } } diff --git a/src/state/app_clusters.rs b/src/state/app_clusters.rs new file mode 100644 index 000000000..a741d7e38 --- /dev/null +++ b/src/state/app_clusters.rs @@ -0,0 +1,321 @@ +//! Cohesive sub-state structs owned by [`super::AppState`]. + +use std::collections::{HashMap, HashSet, VecDeque}; +use std::path::{Path, PathBuf}; +use std::sync::mpsc::Receiver; + +use super::clip_regions::ClipRegionsController; +use super::closing::PendingClose; +use super::compare::Comparisons; +use super::convert::Conversions; +use super::defrag_job::DefragJobs; +use super::delete_prompt::PendingDelete; +use super::dependencies::Dependencies; +use super::dlc_pack::DlcPacks; +use super::expander::ExpansionWorker; +use super::extract_job::{ExtractJobs, PendingExportFixes}; +use super::file_index::FileIndex; +use super::file_io::SaveJob; +use super::file_watcher::FileWatcher; +use super::frame_stats::FrameStats; +use super::game_discovery::DiscoveryWorker; +use super::game_pack::GamePackController; +use super::gltf::Interchange; +use super::gta6::{ + anim::{gta6_clip_finding, gta6_set_finding}, + particles::gta6_particle_models, + physics::gta6_navmesh, + textures::{gta6_texture_index, gta6_texture_naming}, + world::gta6_map, +}; +use super::keys::KeysController; +use super::materials_palette::MaterialsPaletteController; +use super::mod_manager::ModManager; +use super::name_index::NameIndex; +use super::overlay_copy::OverlayCopy; +use super::overlay_loader::OverlayLoaderChecks; +use super::pending_prompts::{PendingEnhancedOpen, PendingRetailEditPrompt}; +use super::prefs::{Game, Prefs}; +use super::preview_scene::AnimSession; +use super::reference_names::{InstallInteriors, InstallTables}; +use super::save_destination::SaveDestinationChoice; +use super::search_session::{SearchQuery, SearchSession}; +use super::shader_defs::ShaderDefsController; +use super::texture_cache::TextureCache; +use super::texture_resolution::{AttachedDictionary, TextureResolutionReport}; +use super::vfs_session::VfsSession; +use super::{DocumentId, LoadResult}; +use or_title::KnownArchiveNames; + +/// Modal error window state on [`super::AppState`]. +#[derive(Default)] +pub struct ErrorDialog { + pub show: bool, + /// The operation that failed, as the error window's title names it, and the file when it was an open. + pub title: String, + /// What the reader said, which the window keeps for its details. + pub message: String, + /// One plain sentence in place of `message`, for an open that failed. + pub plain: Option, +} + +impl ErrorDialog { + /// Open the error dialog with a title and detailed message. + pub fn open(&mut self, title: impl Into, message: impl Into) { + self.title = title.into(); + self.message = message.into(); + self.plain = None; + self.show = true; + } + + /// Open the error dialog with a plain-language summary alongside the detailed message. + pub fn open_plain( + &mut self, + title: impl Into, + plain: Option, + message: impl Into, + ) { + self.title = title.into(); + self.message = message.into(); + self.plain = plain; + self.show = true; + } + + /// Hide the error dialog and clear its message state. + pub fn dismiss(&mut self) { + self.show = false; + self.message.clear(); + self.plain = None; + } + + /// Whether the error dialog is currently open. + pub fn is_open(&self) -> bool { + self.show + } +} + +/// Interactive confirmation and conflict prompts waiting on user answers. +#[derive(Default)] +pub struct PendingPrompts { + /// A delete in the archive tree waiting on its answer. + pub delete: Option, + pub retail_edit_session_allow: bool, + pub retail_edit: Option, + /// A write the edit mode refused, offering to change the mode until answered. + pub refused_write: Option, + /// An export waiting on whether to apply OpenRage's export fixes. + pub export_fixes: Option, + /// The answer a drag out asked for, held for the next drag out. + pub drag_out_fixes: Option, + pub enhanced_open: Option, + /// A save of an archive entry waiting on where it goes. + pub save_destination: Option, + /// A close waiting on whether to save what it would drop. + pub close: Option, + /// Files that changed on disk while they hold unsaved edits, waiting on whether to reload. + pub reload_conflicts: Vec, +} + +/// Decoded texture cache, attached/pinned dictionaries, automatic lookup tracking and report. +pub struct TextureResolutionState { + pub cache: TextureCache, + pub pinned_docs: HashMap>, + pub auto_opened_docs: HashSet, + pub attached_docs: Vec, + pub attempted_siblings: HashSet, + pub attempted_shared: HashSet<(DocumentId, &'static str)>, + pub attempted_search_paths: HashSet, + pub attempted_project: HashSet, + pub report: TextureResolutionReport, +} + +impl TextureResolutionState { + pub fn new(cache_budget: usize) -> Self { + Self { + cache: TextureCache::new(cache_budget), + pinned_docs: HashMap::new(), + auto_opened_docs: HashSet::new(), + attached_docs: Vec::new(), + attempted_siblings: HashSet::new(), + attempted_shared: HashSet::new(), + attempted_search_paths: HashSet::new(), + attempted_project: HashSet::new(), + report: TextureResolutionReport::default(), + } + } + + /// Clear cached textures, pins, attachments, search attempts and report entries for `doc_id`. + pub fn clear_for_document(&mut self, doc_id: DocumentId) { + self.cache.forget_document(doc_id); + self.pinned_docs.remove(&doc_id); + self.pinned_docs.retain(|_, pins| { + pins.retain(|pinned| *pinned != doc_id); + !pins.is_empty() + }); + self.auto_opened_docs.remove(&doc_id); + self.attached_docs + .retain(|attached| attached.document != doc_id); + self.attempted_siblings.remove(&doc_id); + self.attempted_shared.retain(|(doc, _)| *doc != doc_id); + self.attempted_search_paths.remove(&doc_id); + self.attempted_project.remove(&doc_id); + if self.report.document == Some(doc_id) { + self.report = TextureResolutionReport::default(); + } + } + + /// Allow automatic texture dictionary lookups to retry after attachments change. + pub fn clear_automatic_attempts(&mut self) { + self.attempted_siblings.clear(); + self.attempted_shared.clear(); + self.attempted_search_paths.clear(); + } +} + +/// Background GTA VI lookup and search sessions owned by [`super::AppState`]. +#[derive(Default)] +pub(super) struct Gta6Finders { + pub(super) texture_naming: Vec, + pub(super) texture_packs: gta6_texture_index::PackIndex, + pub(super) set_finding: Vec, + pub(super) clip_finding: Option, + pub(super) particle_model_finding: Option, + pub(super) map_search: Vec, + pub(super) neighbour_search: Option, +} + +/// Asynchronous document load/save channels and on-disk reload watcher. +#[derive(Default)] +pub(super) struct DocumentIoQueue { + /// The file being opened, and where its result arrives. + pub(super) load_receiver: Option<(PathBuf, Receiver)>, + pub(super) pending_loads: VecDeque, + pub(super) batch_loading: bool, + pub(super) save_receiver: Option, + pub(super) file_watcher: FileWatcher, +} + +impl DocumentIoQueue { + pub(super) fn has_active_or_queued_loads(&self) -> bool { + !self.pending_loads.is_empty() || self.load_receiver.is_some() + } +} + +/// Per-frame CPU and GPU timing and memory telemetry. +#[derive(Default)] +pub struct FrameTelemetry { + pub frame_stats: FrameStats, + /// What the viewport holds on the GPU, as the render bridge last published it. + pub gpu_usage: crate::render::gpu_budget::GpuUsage, + /// The stages of the last viewport frame the device timed, each with its milliseconds; none where it cannot time them. + pub gpu_stages: Vec<(&'static str, f32)>, +} + +/// Animation playback session, pose edits and transport clock. +pub struct AnimationState { + pub session: AnimSession, + pub edits: or_anim::PoseEdits, + pub transport: or_transport::Transport, +} + +impl Default for AnimationState { + fn default() -> Self { + Self { + session: AnimSession::default(), + edits: or_anim::PoseEdits::new(), + transport: or_transport::Transport::default(), + } + } +} + +/// Reference tables, palettes, indices and shader assets derived from the active install. +pub struct InstallReferenceData { + pub materials_palette: MaterialsPaletteController, + pub clip_regions: ClipRegionsController, + pub name_index: NameIndex, + pub interiors: InstallInteriors, + pub game_tables: InstallTables, + pub known_archive_names: KnownArchiveNames, + /// The game's shaders as a SPIR-V pack, which a helper program bakes. + pub game_pack: GamePackController, + pub shader_defs: ShaderDefsController, +} + +impl InstallReferenceData { + pub(super) fn from_install( + install_root: Option<&Path>, + keys: &KeysController, + prefs: &Prefs, + ) -> Self { + let mut materials_palette = MaterialsPaletteController::default(); + let mut clip_regions = ClipRegionsController::default(); + let game_pack = GamePackController::aimed(install_root); + let mut shader_defs = ShaderDefsController::default(); + shader_defs.start_staged(); + if let Some(root) = install_root { + if keys.has_keys() { + materials_palette.start_load(root.to_path_buf(), keys.provider()); + clip_regions.start_load( + root.to_path_buf(), + keys.provider(), + prefs.mount_options(), + None, + ); + } + } + Self { + materials_palette, + clip_regions, + name_index: NameIndex::new(), + interiors: InstallInteriors::default(), + game_tables: InstallTables::default(), + known_archive_names: KnownArchiveNames::with_stock(), + game_pack, + shader_defs, + } + } +} + +/// Background worker controllers owned by [`super::AppState`]. +pub struct BackgroundControllers { + pub discovery: DiscoveryWorker, + pub extract_jobs: ExtractJobs, + pub defrag: DefragJobs, + pub convert: Conversions, + pub dlc_pack: DlcPacks, + pub mod_manager: ModManager, + pub gltf: Interchange, + pub dependencies: Dependencies, + pub compare: Comparisons, + pub overlay_copy: OverlayCopy, + pub overlay_loader: OverlayLoaderChecks, + pub expander: ExpansionWorker, +} + +impl BackgroundControllers { + pub(super) fn spawn(known_game_paths: Vec<(Game, PathBuf)>) -> Self { + Self { + discovery: DiscoveryWorker::spawn(known_game_paths), + extract_jobs: ExtractJobs::default(), + defrag: DefragJobs::default(), + convert: Conversions::default(), + dlc_pack: DlcPacks::default(), + mod_manager: ModManager::default(), + gltf: Interchange::default(), + dependencies: Dependencies::default(), + compare: Comparisons::default(), + overlay_copy: OverlayCopy::default(), + overlay_loader: OverlayLoaderChecks::default(), + expander: ExpansionWorker::default(), + } + } +} + +/// Search query, session, deep-find VFS and archive file index. +#[derive(Default)] +pub struct SearchState { + pub session: SearchSession, + pub query: SearchQuery, + pub deep: VfsSession, + pub file_index: FileIndex, +} diff --git a/src/state/batch.rs b/src/state/batch.rs index 631f65c25..c442ac5f7 100644 --- a/src/state/batch.rs +++ b/src/state/batch.rs @@ -107,7 +107,7 @@ impl AppState { if read.is_empty() { return self.show_warning_toast(tr!("Nothing selected is a file this exports")); } - if let Some(what) = self.extract_jobs.running_noun() { + if let Some(what) = self.bg.extract_jobs.running_noun() { return self.show_error_toast(tr!( "{what} is running; export once it is done", what = what @@ -125,7 +125,7 @@ impl AppState { } let label = tr!("{count} file(s)", count = read.len()); let dest = folder.clone(); - self.extract_jobs.start( + self.bg.extract_jobs.start( JobKind::Export, label, folder, diff --git a/src/state/clipboard/mod.rs b/src/state/clipboard/mod.rs index bee7eec88..56b416219 100644 --- a/src/state/clipboard/mod.rs +++ b/src/state/clipboard/mod.rs @@ -134,7 +134,7 @@ impl AppState { } } if let Some(target_path) = ask { - self.pending_retail_edit = Some(PendingRetailEditPrompt { + self.prompts.retail_edit = Some(PendingRetailEditPrompt { action: PendingRetailEdit::PasteRows { doc_id: doc, folder_id: folder, diff --git a/src/state/closing.rs b/src/state/closing.rs index 848db9b48..5f2440839 100644 --- a/src/state/closing.rs +++ b/src/state/closing.rs @@ -64,7 +64,7 @@ impl AppState { /// Drop `documents`, then do `then`: at once when nothing unsaved goes with them, else once the user answers. pub fn request_close(&mut self, documents: Vec, then: AfterClose) { - if self.pending_close.is_some() { + if self.prompts.close.is_some() { self.show_warning_toast(tr!( "Answer the question about unsaved changes first, then try again" )); @@ -81,12 +81,12 @@ impl AppState { { self.finish_close(pending); } else { - self.pending_close = Some(pending); + self.prompts.close = Some(pending); } } pub fn answer_close(&mut self, answer: CloseAnswer) { - let Some(mut pending) = self.pending_close.take() else { + let Some(mut pending) = self.prompts.close.take() else { return; }; match answer { @@ -102,7 +102,7 @@ impl AppState { CloseAnswer::DontSave => self.finish_close(pending), CloseAnswer::Save => { pending.saving = true; - self.pending_close = Some(pending); + self.prompts.close = Some(pending); } } } @@ -114,7 +114,7 @@ impl AppState { saving: true, tried, .. - }) = &self.pending_close + }) = &self.prompts.close else { return; }; @@ -125,7 +125,7 @@ impl AppState { let unsaved = self.unsaved_documents(&documents); // ⚠ A save that failed, or was declined at one of its prompts, closes nothing. if let Some(failed) = tried.filter(|id| unsaved.contains(id)) { - self.pending_close = None; + self.prompts.close = None; let name = self.document(failed).map(Document::file_name); self.show_warning_toast(tr!( "{name} was not saved, so nothing was closed", @@ -134,7 +134,7 @@ impl AppState { return; } let Some(&next) = unsaved.first() else { - let Some(pending) = self.pending_close.take() else { + let Some(pending) = self.prompts.close.take() else { return; }; // ⚠ After the files: one saved for the first time has the path that makes it a member only now. @@ -145,7 +145,7 @@ impl AppState { self.finish_close(pending); return; }; - if let Some(pending) = &mut self.pending_close { + if let Some(pending) = &mut self.prompts.close { pending.tried = Some(next); } let previous = self.active_document.replace(next); @@ -160,9 +160,9 @@ impl AppState { /// A save, or a prompt one raised, that has not finished. fn save_in_flight(&self) -> bool { self.is_busy() - || self.pending_retail_edit.is_some() - || self.save_destination.is_some() - || self.pending_export_fixes.is_some() + || self.prompts.retail_edit.is_some() + || self.prompts.save_destination.is_some() + || self.prompts.export_fixes.is_some() } /// ⚠ With nothing left the window is the start page's, which Browse draws: a workspace left on screen drew its empty panels instead. @@ -231,7 +231,7 @@ impl AppState { /// Whether closing `doc` loses work. pub fn loses_work(&self, doc: &Document) -> bool { // ⚠ Pose keys stay a layer over their clip until a save bakes them in. - let unbaked = !self.anim_edits.is_empty() + let unbaked = !self.animation.edits.is_empty() && self .preview_scene .clip @@ -253,7 +253,7 @@ impl AppState { /// Answer the changed-on-disk question: reload over the unsaved edits, or keep them. pub fn answer_reload_conflicts(&mut self, reload: bool) { - for path in std::mem::take(&mut self.reload_conflicts) { + for path in std::mem::take(&mut self.prompts.reload_conflicts) { self.workbench.refreshed.remove(&path); if self.answer_for_a_map_source(&path, reload) { continue; @@ -304,7 +304,7 @@ mod tests { /// Polls as the editor's frame does until the close is answered for good. fn settle(state: &mut AppState, choose: impl Fn(&AppState, DocumentId) -> Option) { let deadline = Instant::now() + Duration::from_secs(30); - while state.pending_close.is_some() { + while state.prompts.close.is_some() { assert!(Instant::now() < deadline, "the saves never finished"); state.poll_save_result(); state.drive_close(&choose); @@ -381,7 +381,7 @@ mod tests { state.document(id).is_some_and(|d| d.dirty), "{path} dropped the document before the user answered" ); - assert!(state.pending_close.is_some(), "{path} asked nothing"); + assert!(state.prompts.close.is_some(), "{path} asked nothing"); state.answer_close(CloseAnswer::Cancel); assert!( state.document(id).is_some_and(|d| d.dirty) && !state.should_exit, @@ -407,7 +407,7 @@ mod tests { state.document(id).is_some_and(|d| d.dirty), "a change on disk replaced the edits before the user answered" ); - assert_eq!(state.reload_conflicts, std::slice::from_ref(&file)); + assert_eq!(state.prompts.reload_conflicts, std::slice::from_ref(&file)); state.answer_reload_conflicts(false); assert!(state.document(id).is_some_and(|d| d.dirty)); state.reload_ypt_from_disk(&file, false); @@ -416,7 +416,7 @@ mod tests { state.document(id).is_some_and(|d| !d.dirty), "Reload kept the edits" ); - assert!(state.reload_conflicts.is_empty()); + assert!(state.prompts.reload_conflicts.is_empty()); } #[test] diff --git a/src/state/clothing.rs b/src/state/clothing.rs index 4a65c509d..07c415546 100644 --- a/src/state/clothing.rs +++ b/src/state/clothing.rs @@ -216,7 +216,7 @@ impl AppState { Some(open) => open, None => { let id = self.open_archive_entry_now(row)?; - self.auto_opened_texture_docs.insert(id); + self.textures.auto_opened_docs.insert(id); id } }; @@ -244,7 +244,7 @@ impl AppState { .chosen .values() .any(|c| c.dictionary == dictionary); - if !in_use && self.auto_opened_texture_docs.contains(&dictionary) { + if !in_use && self.textures.auto_opened_docs.contains(&dictionary) { self.drop_document(dictionary); } } diff --git a/src/state/compare/mod.rs b/src/state/compare/mod.rs index 2676144b1..8b15ab31f 100644 --- a/src/state/compare/mod.rs +++ b/src/state/compare/mod.rs @@ -444,7 +444,7 @@ fn file_row( impl AppState { /// The name of the file Select for compare chose, while its row is open. pub fn selected_for_compare(&self) -> Option { - let (doc, row) = self.compare.selected?; + let (doc, row) = self.bg.compare.selected?; file_row(self, doc, row).map(|(_, name, _)| name) } @@ -459,7 +459,7 @@ impl AppState { (name, kind) }); if let Some((name, kind)) = chosen { - self.compare.selected = Some((doc, row)); + self.bg.compare.selected = Some((doc, row)); self.show_info_toast(tr!( "{name} is selected: Compare with selected on another {kind} compares the two", name = name, @@ -500,7 +500,7 @@ impl AppState { // ⚠ A defragment rewrites its archive under any offset read here. The menus are off while // one holds it, and compare_with_selected asks again; compare_with_original does not, so // this is its refusal, for a defragment begun since its menu drew. - if let Some(held) = reads.iter().find(|path| self.defrag.holds(path)) { + if let Some(held) = reads.iter().find(|path| self.bg.defrag.holds(path)) { self.show_error_toast(tr!( "`{held}` is being defragmented; compare once that is done", held = held.display() @@ -508,12 +508,12 @@ impl AppState { return; } let work = move |stop: &AtomicBool| compare_sides(headings, places, names, sides, stop); - self.compare.start(title, reads, work); + self.bg.compare.start(title, reads, work); } /// Whether a defragment is rewriting, or has on offer, the archive `side` is read out of. fn is_defragmenting(&self, side: &Side) -> bool { - side.file().is_some_and(|file| self.defrag.holds(&file)) + side.file().is_some_and(|file| self.bg.defrag.holds(&file)) } /// Whether `row` of `doc` is read out of an archive a defragment holds. @@ -529,6 +529,7 @@ impl AppState { row: RpfNodeId, ) -> Result<(), &'static str> { let selected = self + .bg .compare .selected .ok_or(tr!("Select for compare on another file first"))?; @@ -564,7 +565,7 @@ impl AppState { self.show_error_toast(why); return; } - let Some((selected, at)) = self.compare.selected else { + let Some((selected, at)) = self.bg.compare.selected else { return; }; let (Some(left), Some(right)) = (self.side(selected, at), self.side(doc, row)) else { @@ -670,7 +671,7 @@ impl AppState { } fn idle_comparing(&self) -> Result<(), &'static str> { - match self.compare.running { + match self.bg.compare.running { Some(_) => Err(crate::i18n::tr(RUNNING)), None => Ok(()), } @@ -688,14 +689,14 @@ impl AppState { /// Where a finished comparison lands: a document of its own, or what stopped it. pub(super) fn poll_compare(&mut self) { - let received = match &self.compare.running { + let received = match &self.bg.compare.running { Some(running) => running.receiver.try_recv(), None => return, }; if matches!(received, Err(TryRecvError::Empty)) { return; } - let Some(running) = self.compare.running.take() else { + let Some(running) = self.bg.compare.running.take() else { return; }; let (outcome, said) = match received { diff --git a/src/state/convert.rs b/src/state/convert.rs index 07a836eb1..9873662fb 100644 --- a/src/state/convert.rs +++ b/src/state/convert.rs @@ -302,7 +302,7 @@ impl AppState { return; } }; - if self.convert.running.is_some() || self.convert.done.is_some() { + if self.bg.convert.running.is_some() || self.bg.convert.done.is_some() { self.show_error_toast("A conversion is already under way"); return; } @@ -311,8 +311,10 @@ impl AppState { }; // ⚠ Each lands under its own name in one folder, so two of one name keep the first. let (items, collided) = plan_named_rows(&rpf.session, &rows, &TypeFilter::All); - let held = (items.iter()) - .find_map(|item| item.archive_read().filter(|path| self.defrag.holds(path))); + let held = (items.iter()).find_map(|item| { + item.archive_read() + .filter(|path| self.bg.defrag.holds(path)) + }); if let Some(held) = held { self.show_error_toast(format!( "`{}` is being defragmented; convert once that is done", @@ -366,7 +368,7 @@ impl AppState { Ok(to) => to, Err(why) => return self.show_error_toast(why), }; - if self.convert.running.is_some() || self.convert.done.is_some() { + if self.bg.convert.running.is_some() || self.bg.convert.done.is_some() { return self.show_error_toast("A conversion is already under way"); } let bytes = match self.saved_bytes(doc) { @@ -388,9 +390,9 @@ impl AppState { reads: Vec, of_document: bool, ) { - let remap = Arc::clone(&self.shader_defs.remap); + let remap = Arc::clone(&self.install.shader_defs.remap); let without_database = remap.shader_count() == 0; - self.convert.start( + self.bg.convert.start( label, without_database, of_document, @@ -416,7 +418,7 @@ impl AppState { /// Answer the question about files a conversion's folder already holds; `None` keeps the conversion's question, to choose another place. pub fn answer_conversion_clash(&mut self, answer: Option) { - let Some(clash) = self.convert.clash.take() else { + let Some(clash) = self.bg.convert.clash.take() else { return; }; if let Some(on_clash) = answer { @@ -435,7 +437,7 @@ impl AppState { /// Skip or Keep both once, as an extraction into it does, and is written /// again with the answer as `on_clash`. pub fn write_conversion(&mut self, dest: PathBuf, on_clash: Option) { - let Some(done) = &self.convert.done else { + let Some(done) = &self.bg.convert.done else { return; }; let names: Vec = done.made().map(|(name, _)| name.to_string()).collect(); @@ -443,7 +445,7 @@ impl AppState { return; } let several = names.len() > 1; - if let Some(what) = self.extract_jobs.running_noun() { + if let Some(what) = self.bg.extract_jobs.running_noun() { self.show_error_toast(format!("{what} is running; write once it is done")); return; } @@ -474,7 +476,7 @@ impl AppState { let on_clash = match (on_clash, taken.first()) { (Some(answer), _) => answer, (None, Some(first)) => { - self.convert.clash = Some(ConvertClash { + self.bg.convert.clash = Some(ConvertClash { dest, clashes: taken.len(), planned: names.len(), @@ -487,7 +489,7 @@ impl AppState { (None, None) if several => OnClash::Skip, (None, None) => OnClash::Replace, }; - let Some(done) = self.convert.done.take() else { + let Some(done) = self.bg.convert.done.take() else { return; }; let writes: Vec<(PathBuf, Vec)> = (done.files.into_iter()) @@ -505,7 +507,7 @@ impl AppState { _ => (format!("{} files", writes.len()), dest), }; // The write runs as the extraction's machinery, named as the conversion's job. - self.extract_jobs.start( + self.bg.extract_jobs.start( JobKind::Conversion, label, folder, @@ -534,19 +536,19 @@ impl AppState { /// Where a finished conversion lands: its question waits on an answer, and a stopped one leaves nothing. pub(super) fn poll_conversion(&mut self) { - let received = match &self.convert.running { + let received = match &self.bg.convert.running { Some(running) => running.receiver.try_recv(), None => return, }; if matches!(received, Err(TryRecvError::Empty)) { return; } - let Some(running) = self.convert.running.take() else { + let Some(running) = self.bg.convert.running.take() else { return; }; let (outcome, said) = match received { Ok(Some(files)) => { - self.convert.done = Some(Converted { + self.bg.convert.done = Some(Converted { files, without_database: running.without_database, of_document: running.of_document, diff --git a/src/state/defrag_job.rs b/src/state/defrag_job.rs index 050f50d26..649767d05 100644 --- a/src/state/defrag_job.rs +++ b/src/state/defrag_job.rs @@ -219,7 +219,7 @@ impl AppState { /// while its worker still writes; a base-game prompt can be confirmed /// long after it was raised, so the tail asks again. fn defrag_busy(&mut self) -> bool { - let busy = self.defrag.is_running() || self.defrag.offer.is_some(); + let busy = self.bg.defrag.is_running() || self.bg.defrag.offer.is_some(); if busy { self.show_error_toast(tr!("A defragment is already under way")); } @@ -242,7 +242,7 @@ impl AppState { "Working out what defragmenting {path} reclaims", path = file_name(&path) ); - self.defrag.start(path, doing, move |progress, cancel| { + self.bg.defrag.start(path, doing, move |progress, cancel| { let planned = plan_from_disk(&worker_path, &crypto, progress); if cancel.is_set() { return Outcome::Stopped; @@ -261,7 +261,7 @@ impl AppState { /// Rebuild and write the offered archive, or drop the offer; the gate and the refusals are asked again. pub fn answer_defrag(&mut self, accept: bool) { - let Some(offer) = self.defrag.offer.take() else { + let Some(offer) = self.bg.defrag.offer.take() else { return; }; if !accept { @@ -279,7 +279,8 @@ impl AppState { return; } let doing = tr!("Defragmenting {path}", path = file_name(&offer.path)); - self.defrag + self.bg + .defrag .start(offer.path.clone(), doing, move |progress, cancel| { let path = &offer.path; let previewed = (offer.before, offer.modified); @@ -311,7 +312,7 @@ impl AppState { /// Where a finished preview or write lands, each frame. pub fn poll_defrag(&mut self) { - let Some(job) = &self.defrag.running else { + let Some(job) = &self.bg.defrag.running else { return; }; let outcome = match job.receiver.try_recv() { @@ -322,9 +323,9 @@ impl AppState { ) .to_string())), }; - self.defrag.running = None; + self.bg.defrag.running = None; match outcome { - Outcome::Planned(Ok(offer)) => self.defrag.offer = Some(offer), + Outcome::Planned(Ok(offer)) => self.bg.defrag.offer = Some(offer), Outcome::Stopped => { self.jobs.record( JobKind::Defragment, @@ -334,7 +335,7 @@ impl AppState { } Outcome::Written(Ok(done)) => { // ⚠ Every offset the session read from this file is stale now. - self.expander.files_replaced(); + self.bg.expander.files_replaced(); self.file_replaced(&done.path); if let Some(DocPayload::Rpf(rpf)) = self.document_mut(done.doc_id).map(|d| &mut d.payload) diff --git a/src/state/delete_prompt.rs b/src/state/delete_prompt.rs index ad2ca66ae..ddea50493 100644 --- a/src/state/delete_prompt.rs +++ b/src/state/delete_prompt.rs @@ -149,7 +149,7 @@ impl AppState { Some(path) => (on_disk(path), DeleteFrom::Disk), None => (in_session(&rpf.session, node_id), DeleteFrom::Session(file)), }; - self.pending_delete = Some(PendingDelete { + self.prompts.delete = Some(PendingDelete { doc_id, node_id, name: node.name.clone(), @@ -163,7 +163,7 @@ impl AppState { /// Answer the pending delete; a yes asks the edit gate again, since the mode can change while the question is up. pub fn answer_delete(&mut self, confirmed: bool) { - let Some(asked) = self.pending_delete.take() else { + let Some(asked) = self.prompts.delete.take() else { return; }; if !confirmed { diff --git a/src/state/dependencies.rs b/src/state/dependencies.rs index 508d3c822..9ae923123 100644 --- a/src/state/dependencies.rs +++ b/src/state/dependencies.rs @@ -267,7 +267,7 @@ impl AppState { self.prefs.mount_options(), self.keys.has_keys(), ); - let deps = &mut self.dependencies; + let deps = &mut self.bg.dependencies; if deps.install.as_ref() != Some(&install) { deps.begin_again(Some(install.clone())); } @@ -331,7 +331,7 @@ impl AppState { /// `path` was written over, renamed, moved or deleted: what Uses and Placed by read of an install holding it, and the texture pack index of a folder holding it, is read again at the next ask. pub(super) fn file_replaced(&mut self, path: &Path) { self.texture_packs_changed(path); - if self.dependencies.replaced(path) { + if self.bg.dependencies.replaced(path) { let said = format!( "{} changed, so the install is read again when Uses or Placed by next asks", file_name(path) @@ -343,7 +343,7 @@ impl AppState { /// Where a finished read lands: the menus answer from it, or say why it failed. pub(super) fn poll_dependencies(&mut self) { - let deps = &mut self.dependencies; + let deps = &mut self.bg.dependencies; let install = (deps.install.as_ref()).map_or_else(String::new, |(root, ..)| file_name(root)); let ended = [ diff --git a/src/state/dlc_pack.rs b/src/state/dlc_pack.rs index 96f0833f8..579e60826 100644 --- a/src/state/dlc_pack.rs +++ b/src/state/dlc_pack.rs @@ -145,7 +145,7 @@ impl AppState { /// ponytail: lists the folder on the UI thread, as the command does before /// it builds; a job of its own if a folder of many thousand files stalls it. pub fn ask_dlc_pack(&mut self, folder: PathBuf) { - if self.dlc_pack.running.is_some() { + if self.bg.dlc_pack.running.is_some() { self.show_error_toast(tr!("A DLC pack is already being built")); return; } @@ -165,7 +165,7 @@ impl AppState { focus_name: true, }; asked.recheck(); - self.dlc_pack.asked = Some(asked); + self.bg.dlc_pack.asked = Some(asked); } /// Build the asked pack as `//dlc.rpf` on a worker, as the command builds it. @@ -175,11 +175,11 @@ impl AppState { /// gate is asked all the same, as every write asks it. A refusal keeps the /// question, so another folder can be chosen. pub fn create_dlc_pack(&mut self, dest: PathBuf) { - let Some(asked) = &self.dlc_pack.asked else { + let Some(asked) = &self.bg.dlc_pack.asked else { return; }; let archive = dest.join(&asked.spec.name).join("dlc.rpf"); - if self.dlc_pack.running.is_some() { + if self.bg.dlc_pack.running.is_some() { self.show_error_toast(tr!("A DLC pack is already being built")); return; } @@ -199,35 +199,37 @@ impl AppState { // ⚠ Only an install asks, and an install was refused above. GateOutcome::Refused | GateOutcome::Confirm(_) => return, } - let Some(asked) = self.dlc_pack.asked.take() else { + let Some(asked) = self.bg.dlc_pack.asked.take() else { return; }; let (name, encryption) = (asked.spec.name.clone(), encryption(asked.encryption)); let folder = asked.folder.clone(); - self.dlc_pack.start(name, folder, move |cancel, progress| { - // ponytail: bytes written against the folder's size, which - // compression and padding make approximate. - let total = (asked.spec.files.iter()) - .filter_map(|file| std::fs::metadata(&file.source).ok()) - .map(|meta| meta.len()) - .sum(); - or_cli::create_dlc_pack(&asked.spec, &dest, encryption, &mut |written| { - progress.reached(written, total); - !cancel.is_set() - }) - }); + self.bg + .dlc_pack + .start(name, folder, move |cancel, progress| { + // ponytail: bytes written against the folder's size, which + // compression and padding make approximate. + let total = (asked.spec.files.iter()) + .filter_map(|file| std::fs::metadata(&file.source).ok()) + .map(|meta| meta.len()) + .sum(); + or_cli::create_dlc_pack(&asked.spec, &dest, encryption, &mut |written| { + progress.reached(written, total); + !cancel.is_set() + }) + }); } /// Where a finished build lands: the pack's window and its line, or why it stopped. pub(super) fn poll_dlc_pack(&mut self) { - let received = match &self.dlc_pack.running { + let received = match &self.bg.dlc_pack.running { Some(running) => running.receiver.try_recv(), None => return, }; if matches!(received, Err(TryRecvError::Empty)) { return; } - let Some(running) = self.dlc_pack.running.take() else { + let Some(running) = self.bg.dlc_pack.running.take() else { return; }; let (outcome, said) = match received { @@ -241,7 +243,7 @@ impl AppState { line = line, archive = archive.display() ); - self.dlc_pack.built = Some(Built { + self.bg.dlc_pack.built = Some(Built { folder: folder.clone(), line, }); diff --git a/src/state/extract_job.rs b/src/state/extract_job.rs index 545fd2892..7a610d808 100644 --- a/src/state/extract_job.rs +++ b/src/state/extract_job.rs @@ -819,14 +819,14 @@ impl AppState { form: BodyForm, filter: TypeFilter, ) -> ExtractStart { - if let Some(what) = self.extract_jobs.running_noun() { + if let Some(what) = self.bg.extract_jobs.running_noun() { self.show_error_toast(tr!("{what} is already running", what = what)); return ExtractStart::AlreadyRunning; } match self.gate_permits(Some(&dest)) { GateOutcome::Refused => return ExtractStart::Refused, GateOutcome::Confirm(target) => { - self.pending_retail_edit = Some(PendingRetailEditPrompt { + self.prompts.retail_edit = Some(PendingRetailEditPrompt { action: PendingRetailEdit::ExtractInto { doc_id, nodes, @@ -846,7 +846,7 @@ impl AppState { /// Answer the question about files already in an extraction's destination; `None` drops the extraction. pub fn answer_extract_clash(&mut self, answer: Option) { - let Some(clash) = self.extract_jobs.clash.take() else { + let Some(clash) = self.bg.extract_jobs.clash.take() else { return; }; if let Some(on_clash) = answer { @@ -873,7 +873,7 @@ impl AppState { /// Answer the pending export-fixes question, and remember the answer when asked to. pub fn apply_export_fixes(&mut self, apply: bool, remember: bool) { - let Some(pending) = self.pending_export_fixes.take() else { + let Some(pending) = self.prompts.export_fixes.take() else { return; }; if remember { @@ -894,7 +894,7 @@ impl AppState { } => { self.extract_rpf_nodes_inner(doc_id, &nodes, dest, form, filter, Some(apply), None); } - PendingExportFixes::DragOut => self.drag_out_fixes = Some(apply), + PendingExportFixes::DragOut => self.prompts.drag_out_fixes = Some(apply), PendingExportFixes::SaveEntry { doc_id, path } => self.save_entry_to_inner( doc_id, super::save_destination::SaveDestination::LooseFile(path), @@ -942,7 +942,7 @@ impl AppState { .map(Path::to_path_buf) .collect(); // ⚠ A defragment rewrites its archive under any offset planned here. - if let Some(held) = reads.iter().find(|path| self.defrag.holds(path)) { + if let Some(held) = reads.iter().find(|path| self.bg.defrag.holds(path)) { self.show_error_toast(tr!( "`{held}` is being defragmented; extract once that is done", held = held.display() @@ -960,7 +960,7 @@ impl AppState { } } let Some(fixes) = fixes.or_else(|| self.export_fixes_for(&items, form)) else { - self.pending_export_fixes = Some(PendingExportFixes::Extract { + self.prompts.export_fixes = Some(PendingExportFixes::Extract { doc_id, nodes: nodes.to_vec(), dest, @@ -993,7 +993,7 @@ impl AppState { let on_clash = match (on_clash, clashing.first()) { (Some(answer), _) => answer, (None, Some(first)) => { - self.extract_jobs.clash = Some(ExtractClash { + self.bg.extract_jobs.clash = Some(ExtractClash { doc_id, nodes: nodes.to_vec(), first: first.to_string(), @@ -1017,7 +1017,7 @@ impl AppState { } let worker_dest = dest.clone(); - self.extract_jobs.start( + self.bg.extract_jobs.start( JobKind::Extraction, label, dest, @@ -1044,14 +1044,14 @@ impl AppState { self.advance_planning(); self.advance_drag_opening(); self.advance_census(); - let Some(job) = &self.extract_jobs.active else { + let Some(job) = &self.bg.extract_jobs.active else { return; }; let Ok(report) = job.receiver.try_recv() else { return; }; let (kind, dest, saves) = (job.kind, job.dest.clone(), job.saves); - self.extract_jobs.active = None; + self.bg.extract_jobs.active = None; if let Some((doc, at)) = saves.filter(|_| !report.cancelled && report.counts.failed == 0) { // An edit made while it wrote is not in the file, so it stays unsaved. if let Some(doc) = self.document_mut(doc).filter(|d| d.history.at() == at) { diff --git a/src/state/extract_planning.rs b/src/state/extract_planning.rs index 2928cdcd4..47073a8b0 100644 --- a/src/state/extract_planning.rs +++ b/src/state/extract_planning.rs @@ -95,7 +95,7 @@ impl OpenUnder { fn look(&mut self, state: &mut AppState, id: RpfNodeId, depth: usize, busy: usize) -> Look { let doc_id = self.doc_id; - let in_flight = state.expander.is_in_flight(doc_id, id); + let in_flight = state.bg.expander.is_in_flight(doc_id, id); let Some(DocPayload::Rpf(rpf)) = state.document(doc_id).map(|d| &d.payload) else { return Look::Open(Vec::new()); }; @@ -257,13 +257,13 @@ impl AppState { if planning.walk.step(self) { return planning.start(self); } - self.extract_jobs.planning = Some(planning); + self.bg.extract_jobs.planning = Some(planning); ExtractStart::Planning } /// The per-frame tick of an extraction still opening its rows. pub(super) fn advance_planning(&mut self) { - let Some(mut planning) = self.extract_jobs.planning.take() else { + let Some(mut planning) = self.bg.extract_jobs.planning.take() else { return; }; if self.document(planning.walk.doc_id).is_none() { @@ -272,7 +272,7 @@ impl AppState { if planning.walk.step(self) { planning.start(self); } else { - self.extract_jobs.planning = Some(planning); + self.bg.extract_jobs.planning = Some(planning); } } @@ -288,19 +288,19 @@ impl AppState { node: RpfNodeId, ) -> (Vec<(String, usize)>, Counting) { let told = self.told_not_to_list(doc_id); - let opening = match self.extract_jobs.census.take() { + let opening = match self.bg.extract_jobs.census.take() { Some((doc, root, mut walk)) if (doc, root) == (doc_id, node) => { if walk.step(self) { self.finish_census_walk(doc, &walk); None } else { let left = walk.left(); - self.extract_jobs.census = Some((doc, root, walk)); + self.bg.extract_jobs.census = Some((doc, root, walk)); Some(Counting::Opening { left }) } } other => { - self.extract_jobs.census = other; + self.bg.extract_jobs.census = other; None } }; @@ -316,7 +316,7 @@ impl AppState { /// The per-frame tick of a count of "Only one type", so that closing the menu that shows it does not park it. pub(super) fn advance_census(&mut self) { - let Some((doc, root, mut walk)) = self.extract_jobs.census.take() else { + let Some((doc, root, mut walk)) = self.bg.extract_jobs.census.take() else { return; }; if self.document(doc).is_none() { @@ -325,14 +325,14 @@ impl AppState { if walk.step(self) { self.finish_census_walk(doc, &walk); } else { - self.extract_jobs.census = Some((doc, root, walk)); + self.bg.extract_jobs.census = Some((doc, root, walk)); } } /// A count that has opened what it can: what would not open is told, and not asked for again. fn finish_census_walk(&mut self, doc: DocumentId, walk: &OpenUnder) { let failed = walk.skip.iter().map(|&row| (doc, row)); - self.extract_jobs.census_failed.extend(failed); + self.bg.extract_jobs.census_failed.extend(failed); self.tell_unopened(&walk.failed, "counted"); } @@ -340,19 +340,19 @@ impl AppState { pub fn count_types_under(&mut self, doc_id: DocumentId, node: RpfNodeId) { let mut walk = OpenUnder::new(doc_id, &[node]); walk.skip = self.told_not_to_list(doc_id); - self.extract_jobs.census = Some((doc_id, node, walk)); + self.bg.extract_jobs.census = Some((doc_id, node, walk)); } /// The rows of `doc_id` a count told would not open, less the folders that list again since, which are asked for afresh. fn told_not_to_list(&mut self, doc_id: DocumentId) -> HashSet { - let mended: Vec<_> = (self.extract_jobs.census_failed.iter()) + let mended: Vec<_> = (self.bg.extract_jobs.census_failed.iter()) .filter(|(doc, row)| *doc == doc_id && self.may_read_again(doc_id, *row)) .copied() .collect(); for row in mended { - self.extract_jobs.census_failed.remove(&row); + self.bg.extract_jobs.census_failed.remove(&row); } - (self.extract_jobs.census_failed.iter()) + (self.bg.extract_jobs.census_failed.iter()) .filter(|(doc, _)| *doc == doc_id) .map(|(_, row)| *row) .collect() @@ -374,11 +374,11 @@ impl AppState { doc_id: DocumentId, nodes: &[RpfNodeId], ) -> Result<(), String> { - let mut walk = match self.extract_jobs.drag_opening.take() { + let mut walk = match self.bg.extract_jobs.drag_opening.take() { Some((doc, rows, walk)) if doc == doc_id && rows == nodes => walk, _ => { let mut walk = OpenUnder::new(doc_id, nodes); - let told = (self.extract_jobs.drag_told.as_ref()) + let told = (self.bg.extract_jobs.drag_told.as_ref()) .filter(|(doc, rows, _)| *doc == doc_id && rows == nodes) .map(|(_, _, told)| told.clone()); // ⚠ A folder that lists again was mended since, and is asked for afresh: an archive cannot be told so without opening it @@ -393,7 +393,7 @@ impl AppState { return Ok(()); } let left = walk.left(); - self.extract_jobs.drag_opening = Some((doc_id, nodes.to_vec(), walk)); + self.bg.extract_jobs.drag_opening = Some((doc_id, nodes.to_vec(), walk)); Err(format!( "{left} folder(s) or archive(s) under the selection are opening: \ drag it again once they have, or use Extract… instead" @@ -419,14 +419,14 @@ impl AppState { /// The per-frame tick of the rows a drag out asked to open. pub(super) fn advance_drag_opening(&mut self) { - let Some((doc, nodes, mut walk)) = self.extract_jobs.drag_opening.take() else { + let Some((doc, nodes, mut walk)) = self.bg.extract_jobs.drag_opening.take() else { return; }; if self.document(doc).is_none() { return; } if !walk.step(self) { - self.extract_jobs.drag_opening = Some((doc, nodes, walk)); + self.bg.extract_jobs.drag_opening = Some((doc, nodes, walk)); return; } self.finish_drag_walk(doc, &nodes, walk); @@ -436,7 +436,7 @@ impl AppState { /// Tell what would not open, and remember it for the next drag of the same rows. fn finish_drag_walk(&mut self, doc: DocumentId, nodes: &[RpfNodeId], walk: OpenUnder) { self.tell_unopened(&walk.failed, "dragged out"); - self.extract_jobs.drag_told = + self.bg.extract_jobs.drag_told = (!walk.skip.is_empty()).then(|| (doc, nodes.to_vec(), walk.skip)); } diff --git a/src/state/file_index/mod.rs b/src/state/file_index/mod.rs index 3d7a378e4..935a7fdc2 100644 --- a/src/state/file_index/mod.rs +++ b/src/state/file_index/mod.rs @@ -871,16 +871,16 @@ impl AppState { /// Index the active install and every install, folder and archive Files shows, and take what the walks found. pub fn tick_file_index(&mut self) { let keys = self.keys.has_keys(); - if self.file_index.keys != keys { + if self.find.file_index.keys != keys { // New keys open archives the last walks could not, and a walk again reopens only what changed. - self.file_index = FileIndex { + self.find.file_index = FileIndex { keys, ..FileIndex::default() }; } let wanted = self.index_roots(); - for at in self.file_index.sync(wanted) { - let root = &self.file_index.roots[at]; + for at in self.find.file_index.sync(wanted) { + let root = &self.find.file_index.roots[at]; let source = if root.archive { let doc = root.doc.and_then(|doc| self.document(doc)); match doc.map(|doc| &doc.payload) { @@ -892,13 +892,13 @@ impl AppState { } else { Some(Source::Disk(self.keys.provider())) }; - let root = &mut self.file_index.roots[at]; + let root = &mut self.find.file_index.roots[at]; match source { Some(source) => root.start(source), None => root.settle_empty(), } } - for root in &mut self.file_index.roots { + for root in &mut self.find.file_index.roots { if let Some(files) = root.drain() { let said = format!("{files} files of {}", file_name(&root.path)); self.jobs diff --git a/src/state/file_io/mod.rs b/src/state/file_io/mod.rs index bb06d3790..425eeeca1 100644 --- a/src/state/file_io/mod.rs +++ b/src/state/file_io/mod.rs @@ -1,16 +1,13 @@ +use super::document_io::{ + atomic_write_with_backup, parse_payload, parse_payload_from_path, read_file_generation, + resource_image_for, serialize_archive_records, +}; use super::jobs::{file_name, JobKind, Outcome, RunningJob, Then}; use super::*; mod save_source; use save_source::write_the_save; -pub(super) use save_source::SaveSource; - -/// A save on a worker: the file it writes, the flag that stops it before the write, and where its result arrives. -pub(super) struct SaveJob { - pub(super) path: PathBuf, - pub(super) cancel: or_job::Cancel, - pub(super) receiver: Receiver, -} +pub(super) use save_source::{SaveJob, SaveSource}; /// `payload`, read from `path`, with what its first frames make already made, on the loader rather than the UI thread. /// @@ -75,7 +72,7 @@ impl AppState { } pub fn load_file(&mut self, path: PathBuf) { - self.pending_loads.push_back(path); + self.io_queue.pending_loads.push_back(path); self.try_start_next_load(); } @@ -83,17 +80,17 @@ impl AppState { if paths.is_empty() { return; } - if paths.len() > 1 || !self.pending_loads.is_empty() || self.load_receiver.is_some() { - self.batch_loading = true; + if paths.len() > 1 || self.io_queue.has_active_or_queued_loads() { + self.io_queue.batch_loading = true; } for path in paths { - self.pending_loads.push_back(path); + self.io_queue.pending_loads.push_back(path); } self.try_start_next_load(); } fn needs_enhanced_switch_prompt(&mut self, path: &std::path::Path) -> bool { - if self.pending_enhanced_open.is_some() { + if self.prompts.enhanced_open.is_some() { return false; } @@ -114,7 +111,7 @@ impl AppState { return false; }; - self.pending_enhanced_open = Some(PendingEnhancedOpen { + self.prompts.enhanced_open = Some(PendingEnhancedOpen { path: path.to_path_buf(), game, version, @@ -124,14 +121,14 @@ impl AppState { } pub fn apply_pending_enhanced_open(&mut self, decision: EnhancedOpenDecision) { - let Some(prompt) = self.pending_enhanced_open.take() else { + let Some(prompt) = self.prompts.enhanced_open.take() else { return; }; match decision { EnhancedOpenDecision::Cancel => { - if self.pending_loads.front() == Some(&prompt.path) { - self.pending_loads.pop_front(); + if self.io_queue.pending_loads.front() == Some(&prompt.path) { + self.io_queue.pending_loads.pop_front(); } self.show_info_toast(tr!("Cancelled — the file was not opened")); } @@ -141,8 +138,8 @@ impl AppState { match self.prefs.game_paths.get(game).cloned() { Some(root) if root.exists() => { // ⚠ The file waits on the switch, which may wait on the user: it opens once the switch is made. - if self.pending_loads.front() == Some(&prompt.path) { - self.pending_loads.pop_front(); + if self.io_queue.pending_loads.front() == Some(&prompt.path) { + self.io_queue.pending_loads.pop_front(); } self.switch_game_then(game, root, Some(prompt.path)); } @@ -162,16 +159,16 @@ impl AppState { } fn try_start_next_load(&mut self) { - if self.load_receiver.is_some() { + if self.io_queue.load_receiver.is_some() { return; } if let Some((path, kind, data, row)) = self.next_waiting_load() { return self.spawn_inline_load(path, kind, data, row); } - let path = match self.pending_loads.pop_front() { + let path = match self.io_queue.pending_loads.pop_front() { Some(p) => p, None => { - self.batch_loading = false; + self.io_queue.batch_loading = false; return; } }; @@ -186,7 +183,7 @@ impl AppState { let kind = DocumentKind::from_path(&path).unwrap_or(DocumentKind::Hex); if self.needs_enhanced_switch_prompt(&path) { - self.pending_loads.push_front(path); + self.io_queue.pending_loads.push_front(path); return; } @@ -202,7 +199,7 @@ impl AppState { self.loading = LoadingState::Loading; let (tx, rx): (Sender, Receiver) = channel(); - self.load_receiver = Some((path.clone(), rx)); + self.io_queue.load_receiver = Some((path.clone(), rx)); let provider = self.keys.provider(); let path_clone = path.clone(); @@ -237,7 +234,7 @@ impl AppState { self.tabs.keep(row); if let Some(existing) = self.entry_document(row) { // A dictionary the app opened for itself is the user's once opened: it gets a tab and stays. - self.auto_opened_texture_docs.remove(&existing); + self.textures.auto_opened_docs.remove(&existing); self.set_active_document(existing); self.remember_recent(existing); return; @@ -327,13 +324,13 @@ impl AppState { binding: Option, ) { // ⚠ Never read here while the worker is busy: a parse on the UI thread froze the window for as long as it took. - if self.load_receiver.is_some() { + if self.io_queue.load_receiver.is_some() { return self.wait_for_the_loader((path, kind, data, binding)); } let provider = self.keys.provider(); self.loading = LoadingState::Loading; let (tx, rx): (Sender, Receiver) = channel(); - self.load_receiver = Some((path.clone(), rx)); + self.io_queue.load_receiver = Some((path.clone(), rx)); self.tabs.arriving = binding; let path_clone = path.clone(); thread::spawn(move || { @@ -360,39 +357,34 @@ impl AppState { /// A file that would not open: its name and one plain sentence are said, and the reader's own words are the window's details and the Log's. fn report_load_error(&mut self, path: &Path, message: String) { let headline = super::load_error::headline(path); - if self.batch_loading { + if self.io_queue.batch_loading { self.show_error_toast(headline); self.loading = LoadingState::Idle; } else { self.set_error(tr!("Could not open the file"), message.clone()); - self.error_dialog_title = headline; // A body a scan found says what it is and why it does not open, which no plain sentence says. - self.error_dialog_plain = (super::rpf9_scan::scanned_body(path).is_none()) + let plain = (super::rpf9_scan::scanned_body(path).is_none()) .then(|| super::load_error::plain_reason(&message).to_string()); + self.error_dialog.open_plain(headline, plain, message); } } /// Show the error window, titled with the operation that failed, as in `Could not save the file`. pub fn set_error(&mut self, title: &'static str, message: String) { self.loading = LoadingState::Error(message.clone()); - self.error_dialog_title = title.to_string(); - self.error_dialog_message = message; - self.error_dialog_plain = None; - self.show_error_dialog = true; + self.error_dialog.open(title, message); } pub fn clear_error(&mut self) { if matches!(self.loading, LoadingState::Error(_)) { self.loading = LoadingState::Idle; } - self.show_error_dialog = false; - self.error_dialog_message.clear(); - self.error_dialog_plain = None; + self.error_dialog.dismiss(); } pub fn poll_load_result(&mut self) { self.poll_gta6_scripts(); - let result = match &self.load_receiver { + let result = match &self.io_queue.load_receiver { Some((path, receiver)) => match receiver.try_recv() { Ok(result) => result, Err(std::sync::mpsc::TryRecvError::Empty) => return, @@ -403,7 +395,7 @@ impl AppState { }, None => return, }; - self.load_receiver = None; + self.io_queue.load_receiver = None; match result { LoadResult::Success { @@ -442,8 +434,8 @@ impl AppState { /// The open in flight, as the job list draws it. pub(super) fn load_job(&self) -> Option { - let (path, _) = self.load_receiver.as_ref()?; - let waiting = self.pending_loads.len(); + let (path, _) = self.io_queue.load_receiver.as_ref()?; + let waiting = self.io_queue.pending_loads.len(); Some(RunningJob { kind: JobKind::Load, doing: tr!("Opening {path}", path = file_name(path)), @@ -459,19 +451,19 @@ impl AppState { /// Drop the open in flight and every one waiting; `false` when none runs. pub(super) fn cancel_loads(&mut self) -> bool { // ⚠ A parse takes no cancel, so its worker finishes unheard and opens nothing. - if self.load_receiver.take().is_none() { + if self.io_queue.load_receiver.take().is_none() { return false; } - self.pending_loads.clear(); + self.io_queue.pending_loads.clear(); self.forget_waiting_loads(); - self.batch_loading = false; + self.io_queue.batch_loading = false; self.loading = LoadingState::Idle; true } /// The save in flight, as the job list draws it. pub(super) fn save_job(&self) -> Option { - let job = self.save_receiver.as_ref()?; + let job = self.io_queue.save_receiver.as_ref()?; Some(RunningJob { kind: JobKind::Save, doing: tr!("Saving {path}", path = file_name(&job.path)), @@ -483,14 +475,14 @@ impl AppState { /// ⚠ A save stops only before its write begins: once writing, it finishes, or the file would be half of each. pub(super) fn cancel_save(&mut self) { - if let Some(job) = &self.save_receiver { + if let Some(job) = &self.io_queue.save_receiver { job.cancel.set(); } } pub fn poll_save_result(&mut self) { self.poll_tree_row_saves(); - let Some(job) = &self.save_receiver else { + let Some(job) = &self.io_queue.save_receiver else { return; }; let result = match job.receiver.try_recv() { @@ -501,7 +493,7 @@ impl AppState { }, }; let name = file_name(&job.path); - self.save_receiver = None; + self.io_queue.save_receiver = None; match result { SaveResult::Success { doc_id, path, at } => { tracing::info!(path = %path.display(), "Save completed successfully"); @@ -586,7 +578,7 @@ impl AppState { match self.gate_permits(Some(&path)) { GateOutcome::Refused => return false, GateOutcome::Confirm(target) => { - self.pending_retail_edit = Some(PendingRetailEditPrompt { + self.prompts.retail_edit = Some(PendingRetailEditPrompt { action: PendingRetailEdit::SaveLooseFile { doc_id }, target_path: target, verb: "save", @@ -626,7 +618,7 @@ impl AppState { GateOutcome::Proceed => self.save_dirty_archives_inner(doc_id), GateOutcome::Refused => {} GateOutcome::Confirm(path) => { - self.pending_retail_edit = Some(PendingRetailEditPrompt { + self.prompts.retail_edit = Some(PendingRetailEditPrompt { action: PendingRetailEdit::SaveDirtyArchives { doc_id }, target_path: path, verb: "save", @@ -728,7 +720,7 @@ impl AppState { } atomic_write_with_backup(&fs_path, &bytes) .map_err(|e| tr!("Write '{fs_path}': {e}", e = e, fs_path = fs_path.display()))?; - self.expander.files_replaced(); + self.bg.expander.files_replaced(); self.file_replaced(&fs_path); let Some(doc) = self.document_mut(doc_id) else { return Ok(fs_path); @@ -788,7 +780,7 @@ impl AppState { archive_id = archive_id ) })?; - if self.defrag.holds(&fs_path) { + if self.bg.defrag.holds(&fs_path) { return Err(tr!( "`{fs_path}` is being defragmented; save once that is done", fs_path = fs_path.display() @@ -841,7 +833,7 @@ impl AppState { match self.gate_permits(Some(&path)) { GateOutcome::Refused => return false, GateOutcome::Confirm(target) => { - self.pending_retail_edit = Some(PendingRetailEditPrompt { + self.prompts.retail_edit = Some(PendingRetailEditPrompt { action: PendingRetailEdit::SaveAs { doc_id, path: path.clone(), @@ -1010,7 +1002,7 @@ impl AppState { thread::spawn(move || { let _ = tx.send(work(&worker_cancel)); }); - self.save_receiver = Some(SaveJob { + self.io_queue.save_receiver = Some(SaveJob { path, cancel, receiver, diff --git a/src/state/file_io/save_source.rs b/src/state/file_io/save_source.rs index 26bd0b28a..60d6855c2 100644 --- a/src/state/file_io/save_source.rs +++ b/src/state/file_io/save_source.rs @@ -1,7 +1,15 @@ //! What a save writes, and where its bytes go. +use super::super::document_io::{atomic_write_with_backup, serialize_payload_repairing}; use super::*; +/// A save on a worker: the file it writes, the flag that stops it before the write, and where its result arrives. +pub(in crate::state) struct SaveJob { + pub(in crate::state) path: PathBuf, + pub(in crate::state) cancel: or_job::Cancel, + pub(in crate::state) receiver: Receiver, +} + pub(in crate::state) enum SaveSource { Payload(Box), PatchedImage(Arc), diff --git a/src/state/files_view/mod.rs b/src/state/files_view/mod.rs index 8a7e72e0b..815874e91 100644 --- a/src/state/files_view/mod.rs +++ b/src/state/files_view/mod.rs @@ -547,7 +547,7 @@ impl AppState { ) { use or_io::container::rpf::BodyForm; - if let Some(what) = self.extract_jobs.running_noun() { + if let Some(what) = self.bg.extract_jobs.running_noun() { self.show_error_toast(tr!("{what} is already running", what = what)); return; } @@ -582,7 +582,7 @@ impl AppState { let Some(fixes) = fixes.or_else(|| self.export_fixes_for(std::slice::from_ref(&item), BodyForm::Decoded)) else { - self.pending_export_fixes = Some(super::extract_job::PendingExportFixes::ExportAs { + self.prompts.export_fixes = Some(super::extract_job::PendingExportFixes::ExportAs { doc_id: doc, node, path, @@ -595,7 +595,7 @@ impl AppState { ); let reads = item.archive_read().into_iter().collect(); let now_on = label.clone(); - self.extract_jobs.start( + self.bg.extract_jobs.start( super::jobs::JobKind::Export, label, folder, diff --git a/src/state/gltf.rs b/src/state/gltf.rs index 43f0001c7..7df7111d0 100644 --- a/src/state/gltf.rs +++ b/src/state/gltf.rs @@ -281,7 +281,7 @@ impl AppState { /// Why `model` cannot go out to glTF now, or its file name. pub fn exports_gltf(&self, model: Model) -> Result { let name = self.model_at(model)?; - if self.gltf.busy() { + if self.bg.gltf.busy() { return Err(crate::i18n::tr(BUSY)); } Ok(name) @@ -297,7 +297,7 @@ impl AppState { .ok_or(crate::i18n::tr(OPEN_IT))?, }; self.model_at(Model::Document(doc))?; - if self.gltf.busy() { + if self.bg.gltf.busy() { return Err(crate::i18n::tr(BUSY)); } Ok(doc) @@ -360,7 +360,7 @@ impl AppState { Ok(bytes) => bytes, Err(why) => return self.show_error_toast(why), }; - self.gltf.asked = Some(Asked::Export(Export { + self.bg.gltf.asked = Some(Asked::Export(Export { name, bytes, choice: ExportChoice { @@ -396,7 +396,7 @@ impl AppState { }; let drawables = drawables(&document.payload); let entry = drawables.first().map_or(0, |(entry, _)| *entry); - self.gltf.asked = Some(Asked::Import(Import { + self.bg.gltf.asked = Some(Asked::Import(Import { doc, name: model_name(document), mesh, @@ -429,7 +429,7 @@ impl AppState { let Some(document) = self.document(doc) else { return; }; - self.gltf.asked = Some(Asked::Import(Import { + self.bg.gltf.asked = Some(Asked::Import(Import { doc, name: document.file_name(), mesh, @@ -447,7 +447,7 @@ impl AppState { /// Work out the question's export or import again, for the choice it holds now. pub fn rerun_gltf(&mut self) { type Work = Box Option + Send>; - let (doing, work): (String, Work) = match &mut self.gltf.asked { + let (doing, work): (String, Work) = match &mut self.bg.gltf.asked { Some(Asked::Export(asked)) => { asked.made = None; let (name, bytes) = (asked.name.clone(), Arc::clone(&asked.bytes)); @@ -519,23 +519,23 @@ impl AppState { } None => return, }; - self.gltf.start(doing, work); + self.bg.gltf.start(doing, work); } /// Where a finished export or import lands: in the question waiting on its answer. pub(super) fn poll_gltf(&mut self) { - let received = match &self.gltf.running { + let received = match &self.bg.gltf.running { Some(running) => running.receiver.try_recv(), None => return, }; if matches!(received, Err(TryRecvError::Empty)) { return; } - let Some(running) = self.gltf.running.take() else { + let Some(running) = self.bg.gltf.running.take() else { return; }; let broke = tr!("It stopped on an internal error; nothing was written").to_string(); - let (outcome, said) = match (received, &mut self.gltf.asked) { + let (outcome, said) = match (received, &mut self.bg.gltf.asked) { (Ok(None), _) => ( Outcome::Stopped(Then::Nothing), tr!("Stopped before it finished; nothing was written").to_string(), @@ -589,7 +589,7 @@ impl AppState { pub fn write_gltf(&mut self, dest: PathBuf) { let Some(Asked::Export(Export { made: Some(Ok(_)), .. - })) = &self.gltf.asked + })) = &self.bg.gltf.asked else { return; }; @@ -603,7 +603,7 @@ impl AppState { )) } }; - if let Some(what) = self.extract_jobs.running_noun() { + if let Some(what) = self.bg.extract_jobs.running_noun() { return self .show_error_toast(tr!("{what} is running; write once it is done", what = what)); } @@ -624,7 +624,7 @@ impl AppState { let Some(Asked::Export(Export { made: Some(Ok(scene)), .. - })) = &self.gltf.asked + })) = &self.bg.gltf.asked else { return; }; @@ -639,8 +639,8 @@ impl AppState { { return self.show_error_toast(why); } - self.gltf.asked = None; - self.extract_jobs.start( + self.bg.gltf.asked = None; + self.bg.extract_jobs.start( JobKind::Export, file_name(&dest), folder, @@ -668,7 +668,7 @@ impl AppState { })) ) }; - if !made(&self.gltf.asked) { + if !made(&self.bg.gltf.asked) { return; } let Some(Asked::Import(Import { @@ -678,7 +678,7 @@ impl AppState { made: Some(Ok((payload, _))), gta6, .. - })) = self.gltf.asked.take() + })) = self.bg.gltf.asked.take() else { return; }; diff --git a/src/state/gta6/anim/gta6_anim_edit/tests.rs b/src/state/gta6/anim/gta6_anim_edit/tests.rs index c1d70cdec..49019616d 100644 --- a/src/state/gta6/anim/gta6_anim_edit/tests.rs +++ b/src/state/gta6/anim/gta6_anim_edit/tests.rs @@ -197,7 +197,7 @@ fn a_gta_vi_animation_s_key_and_clip_window_edit_undo_and_save_as_a_loose_resour settle(&mut state); let doc = state .active_document - .unwrap_or_else(|| panic!("opened: {}", state.error_dialog_message)); + .unwrap_or_else(|| panic!("opened: {}", state.error_dialog.message)); assert_eq!( state.document(doc).map(|d| d.kind()), Some(DocumentKind::Gta6Anim) @@ -243,7 +243,7 @@ fn a_gta_vi_animation_s_key_and_clip_window_edit_undo_and_save_as_a_loose_resour // Save writes the edited sections over the loose file, which reads back as edited. assert!(state.save_active_document()); let deadline = Instant::now() + Duration::from_secs(30); - while state.extract_jobs.is_running() { + while state.bg.extract_jobs.is_running() { state.poll_extract_job(); assert!(Instant::now() < deadline, "the save never ended"); std::thread::sleep(Duration::from_millis(5)); diff --git a/src/state/gta6/anim/gta6_bone_edit/tests.rs b/src/state/gta6/anim/gta6_bone_edit/tests.rs index e2b80f0cb..5346c8ecb 100644 --- a/src/state/gta6/anim/gta6_bone_edit/tests.rs +++ b/src/state/gta6/anim/gta6_bone_edit/tests.rs @@ -74,7 +74,7 @@ fn skinned_body() -> Vec { fn finished(state: &mut AppState) { let deadline = Instant::now() + Duration::from_secs(30); - while state.extract_jobs.is_running() { + while state.bg.extract_jobs.is_running() { state.poll_extract_job(); assert!(Instant::now() < deadline, "the save never ended"); std::thread::sleep(Duration::from_millis(5)); @@ -110,7 +110,7 @@ fn a_bone_edit_undoes_and_saves_over_its_loose_resource_with_the_inverse_binds_u state.load_file(path.clone()); settle(&mut state); let doc = - (state.active_document).unwrap_or_else(|| panic!("opened: {}", state.error_dialog_message)); + (state.active_document).unwrap_or_else(|| panic!("opened: {}", state.error_dialog.message)); let opened_as = held(&path); assert_eq!(opened_as.bones.len(), 2); diff --git a/src/state/gta6/anim/gta6_clip_finding.rs b/src/state/gta6/anim/gta6_clip_finding.rs index ccd56f7ea..47cac2c0d 100644 --- a/src/state/gta6/anim/gta6_clip_finding.rs +++ b/src/state/gta6/anim/gta6_clip_finding.rs @@ -152,7 +152,7 @@ fn dictionary_at(file: &File, offset: u64) -> Option { impl AppState { /// The job list's row for the search, while it runs. pub(in crate::state) fn clip_finding_job(&self) -> Option { - let finding = self.clip_finding.as_ref()?; + let finding = self.gta6_finders.clip_finding.as_ref()?; if finding.ended().is_some() { return None; } @@ -167,7 +167,7 @@ impl AppState { /// Ask the search to stop; it says it stopped once its worker sees the stop. pub(in crate::state) fn stop_clip_finding(&self) { - if let Some(finding) = &self.clip_finding { + if let Some(finding) = &self.gta6_finders.clip_finding { finding.cancel.set(); } } @@ -220,7 +220,7 @@ impl AppState { if bodies.is_empty() { return Err(tr!("Open the scan of an archive to look for clips in.").to_string()); } - self.clip_finding = Some(ClipFinding::start(bodies, wanted)); + self.gta6_finders.clip_finding = Some(ClipFinding::start(bodies, wanted)); Ok(()) } @@ -231,10 +231,15 @@ impl AppState { /// Say in the job list how the search ended, once it has, and drop it. pub(in crate::state) fn poll_clip_finding(&mut self) { - let Some(ended) = self.clip_finding.as_ref().and_then(ClipFinding::ended) else { + let Some(ended) = self + .gta6_finders + .clip_finding + .as_ref() + .and_then(ClipFinding::ended) + else { return; }; - self.clip_finding = None; + self.gta6_finders.clip_finding = None; let (outcome, said) = match ended { FindEnded::Found(found, of) => ( Outcome::Done(Then::Nothing), diff --git a/src/state/gta6/anim/gta6_set_finding/mod.rs b/src/state/gta6/anim/gta6_set_finding/mod.rs index 32bac766c..b17e2279f 100644 --- a/src/state/gta6/anim/gta6_set_finding/mod.rs +++ b/src/state/gta6/anim/gta6_set_finding/mod.rs @@ -182,21 +182,29 @@ impl AppState { archive = archive.display() )); } - self.set_finding + self.gta6_finders + .set_finding .push(SetFinding::start(archive, offsets, wanted)); Ok(()) } /// The searches still running, as the job list draws them. pub(in crate::state) fn set_finding_jobs(&self) -> impl Iterator + '_ { - (self.set_finding.iter().filter_map(SetFinding::job)) - .chain(self.clip_finding_job()) - .chain(self.particle_model_finding_job()) + (self + .gta6_finders + .set_finding + .iter() + .filter_map(SetFinding::job)) + .chain(self.clip_finding_job()) + .chain(self.particle_model_finding_job()) } /// Ask every search to stop; each says it stopped once its worker sees the stop. pub(in crate::state) fn stop_set_finding(&self) { - self.set_finding.iter().for_each(|f| f.cancel.set()); + self.gta6_finders + .set_finding + .iter() + .for_each(|f| f.cancel.set()); self.stop_clip_finding(); self.stop_particle_model_finding(); } @@ -206,7 +214,7 @@ impl AppState { self.poll_clip_finding(); self.poll_particle_model_finding(); let mut ended = Vec::new(); - self.set_finding.retain(|f| match f.ended() { + self.gta6_finders.set_finding.retain(|f| match f.ended() { Some(e) => { ended.push(e); false diff --git a/src/state/gta6/anim/gta6_set_finding/tests.rs b/src/state/gta6/anim/gta6_set_finding/tests.rs index 9154868fa..a8d6e205b 100644 --- a/src/state/gta6/anim/gta6_set_finding/tests.rs +++ b/src/state/gta6/anim/gta6_set_finding/tests.rs @@ -42,7 +42,7 @@ fn naming(keys: &[u32]) -> AnimResource { fn finished(state: &mut AppState) { let deadline = Instant::now() + Duration::from_secs(30); - while !state.set_finding.is_empty() { + while !state.gta6_finders.set_finding.is_empty() { state.poll_set_finding(); assert!(Instant::now() < deadline, "the search never ended"); std::thread::sleep(Duration::from_millis(5)); @@ -73,7 +73,11 @@ fn a_set_another_body_stores_is_found_among_the_animation_bodies_of_the_scan() { assert!(found_set(&archive, wanted[0]).is_none()); state.find_gta6_sets(doc).expect("a scan to look in"); - assert_eq!(state.set_finding.len(), 1, "the search is a job"); + assert_eq!( + state.gta6_finders.set_finding.len(), + 1, + "the search is a job" + ); finished(&mut state); let set = found_set(&archive, wanted[0]).expect("the set the scan holds"); assert_eq!(set.name, "sf_test-2"); @@ -102,7 +106,11 @@ fn a_set_another_body_stores_is_found_among_the_animation_bodies_of_the_scan() { None, ); state.find_gta6_sets(there).expect("a scan to look in"); - assert_eq!(state.set_finding.len(), 1, "the other archive is searched"); + assert_eq!( + state.gta6_finders.set_finding.len(), + 1, + "the other archive is searched" + ); finished(&mut state); assert!(found_set(&other, wanted[0]).is_some()); diff --git a/src/state/gta6/bodies/gta6_meta_save/mod.rs b/src/state/gta6/bodies/gta6_meta_save/mod.rs index 53e9701c6..c7d13a897 100644 --- a/src/state/gta6/bodies/gta6_meta_save/mod.rs +++ b/src/state/gta6/bodies/gta6_meta_save/mod.rs @@ -169,7 +169,7 @@ mod tests { fn finished(state: &mut AppState) { let deadline = Instant::now() + Duration::from_secs(30); - while state.extract_jobs.is_running() { + while state.bg.extract_jobs.is_running() { state.poll_extract_job(); assert!(Instant::now() < deadline, "the save never ended"); std::thread::sleep(Duration::from_millis(5)); @@ -181,7 +181,7 @@ mod tests { state.open_scanned_body(doc, row_at(&rows(state, doc), offset)); settle(state); let body = (state.active_document).filter(|&d| d != doc); - let body = body.unwrap_or_else(|| panic!("the body: {}", state.error_dialog_message)); + let body = body.unwrap_or_else(|| panic!("the body: {}", state.error_dialog.message)); let Some(DocPayload::Meta(meta)) = state.document_mut(body).map(|d| &mut d.payload) else { panic!("a metadata document"); }; diff --git a/src/state/gta6/bodies/gta6_other_bodies_save/cell.rs b/src/state/gta6/bodies/gta6_other_bodies_save/cell.rs index 47e83cada..6d7af6b8e 100644 --- a/src/state/gta6/bodies/gta6_other_bodies_save/cell.rs +++ b/src/state/gta6/bodies/gta6_other_bodies_save/cell.rs @@ -93,13 +93,13 @@ mod tests { settle(&mut state); let body = (state.active_document) .filter(|&d| d != scan) - .unwrap_or_else(|| panic!("the body: {}", state.error_dialog_message)); + .unwrap_or_else(|| panic!("the body: {}", state.error_dialog.message)); // Column 1 of row 0, which holds 50 over 5. state.set_height_map_cell(body, 1, 0, 51).expect("sets"); let saved = dir.path().join("saved.hmap"); assert!(state.save_active_document_as(saved.clone())); let deadline = Instant::now() + Duration::from_secs(30); - while state.extract_jobs.is_running() { + while state.bg.extract_jobs.is_running() { state.poll_extract_job(); assert!(Instant::now() < deadline, "the save never ended"); std::thread::sleep(Duration::from_millis(5)); diff --git a/src/state/gta6/bodies/gta6_other_bodies_save/mod.rs b/src/state/gta6/bodies/gta6_other_bodies_save/mod.rs index 5663395d7..a38d86402 100644 --- a/src/state/gta6/bodies/gta6_other_bodies_save/mod.rs +++ b/src/state/gta6/bodies/gta6_other_bodies_save/mod.rs @@ -73,7 +73,7 @@ mod tests { fn finished(state: &mut AppState) { let deadline = Instant::now() + Duration::from_secs(30); - while state.extract_jobs.is_running() { + while state.bg.extract_jobs.is_running() { state.poll_extract_job(); assert!(Instant::now() < deadline, "the save never ended"); std::thread::sleep(Duration::from_millis(5)); @@ -93,7 +93,7 @@ mod tests { settle(&mut state); let body = (state.active_document) .filter(|&d| d != scan) - .unwrap_or_else(|| panic!("the body: {}", state.error_dialog_message)); + .unwrap_or_else(|| panic!("the body: {}", state.error_dialog.message)); assert_eq!( state.document(body).map(|d| d.kind()), Some(DocumentKind::HeightMap) @@ -158,7 +158,7 @@ mod tests { settle(&mut state); let body = (state.active_document) .filter(|&d| d != scan) - .unwrap_or_else(|| panic!("the body: {}", state.error_dialog_message)); + .unwrap_or_else(|| panic!("the body: {}", state.error_dialog.message)); assert_eq!( state.document(body).map(|d| d.kind()), Some(DocumentKind::HeightMap) diff --git a/src/state/gta6/bodies/gta6_resource_save/awc_in_extent.rs b/src/state/gta6/bodies/gta6_resource_save/awc_in_extent.rs index d0b2e9550..ed3f80aa7 100644 --- a/src/state/gta6/bodies/gta6_resource_save/awc_in_extent.rs +++ b/src/state/gta6/bodies/gta6_resource_save/awc_in_extent.rs @@ -468,7 +468,9 @@ mod tests { let what = format!("entry {entry} of nested archive {number} of {file_name}"); state.open_rpf_entry(DOC, node); let deadline = wait(); - while state.load_receiver.is_some() || !state.pending_loads.is_empty() { + while state.io_queue.load_receiver.is_some() + || !state.io_queue.pending_loads.is_empty() + { state.poll_load_result(); assert!(Instant::now() < deadline, "the load never ended"); std::thread::sleep(Duration::from_millis(5)); diff --git a/src/state/gta6/bodies/gta6_resource_save/mod.rs b/src/state/gta6/bodies/gta6_resource_save/mod.rs index 9f52b8da0..39ec9fe66 100644 --- a/src/state/gta6/bodies/gta6_resource_save/mod.rs +++ b/src/state/gta6/bodies/gta6_resource_save/mod.rs @@ -213,7 +213,7 @@ impl AppState { match self.gate_permits(Some(&path)) { GateOutcome::Refused => Some(false), GateOutcome::Confirm(target_path) => { - self.pending_retail_edit = Some(PendingRetailEditPrompt { + self.prompts.retail_edit = Some(PendingRetailEditPrompt { action: PendingRetailEdit::SaveLooseFile { doc_id: doc }, target_path, verb: "save", @@ -257,7 +257,7 @@ impl AppState { }; let started = self.start_edited_save(edited, dest, name, path.clone(), Vec::new()); if started { - self.extract_jobs.saving(doc, at); + self.bg.extract_jobs.saving(doc, at); } started } @@ -301,7 +301,7 @@ pub(in crate::state) mod tests { fn finished(state: &mut AppState) { let deadline = Instant::now() + Duration::from_secs(30); - while state.extract_jobs.is_running() { + while state.bg.extract_jobs.is_running() { state.poll_extract_job(); assert!(Instant::now() < deadline, "the save never ended"); std::thread::sleep(Duration::from_millis(5)); @@ -334,7 +334,7 @@ pub(in crate::state) mod tests { settle(state); (state.active_document) .filter(|&d| d != not) - .unwrap_or_else(|| panic!("opened: {}", state.error_dialog_message)) + .unwrap_or_else(|| panic!("opened: {}", state.error_dialog.message)) } #[test] @@ -350,7 +350,7 @@ pub(in crate::state) mod tests { settle(&mut state); let body = (state.active_document) .filter(|&d| d != doc) - .unwrap_or_else(|| panic!("the body: {}", state.error_dialog_message)); + .unwrap_or_else(|| panic!("the body: {}", state.error_dialog.message)); assert_eq!( state.document(body).map(|d| d.kind()), Some(DocumentKind::Gta6Drawable) @@ -391,6 +391,7 @@ pub(in crate::state) mod tests { // Refused while a defragment holds the file, as every Save is. let before = std::fs::read(©).expect("the copy"); state + .bg .defrag .start(copy.clone(), "a defragment".into(), |_, cancel| { while !cancel.is_set() { @@ -401,9 +402,9 @@ pub(in crate::state) mod tests { state.toasts.clear(); assert!(!state.save_active_document()); assert!(said(&state, ToastType::Error, &["being defragmented"])); - state.defrag.cancel(); + state.bg.defrag.cancel(); let deadline = Instant::now() + Duration::from_secs(30); - while state.defrag.is_running() { + while state.bg.defrag.is_running() { state.poll_defrag(); assert!(Instant::now() < deadline, "the defragment never stopped"); std::thread::sleep(Duration::from_millis(5)); diff --git a/src/state/gta6/bodies/gta6_resource_save/saving_an_edited_gta_vi_text_body.rs b/src/state/gta6/bodies/gta6_resource_save/saving_an_edited_gta_vi_text_body.rs index 650c34571..e2e46e09f 100644 --- a/src/state/gta6/bodies/gta6_resource_save/saving_an_edited_gta_vi_text_body.rs +++ b/src/state/gta6/bodies/gta6_resource_save/saving_an_edited_gta_vi_text_body.rs @@ -12,7 +12,7 @@ const TEXT: &[u8] = b"first line\r\nsecond line\r\n"; fn finished(state: &mut AppState) { let deadline = Instant::now() + Duration::from_secs(30); - while state.extract_jobs.is_running() { + while state.bg.extract_jobs.is_running() { state.poll_extract_job(); assert!(Instant::now() < deadline, "the save never ended"); std::thread::sleep(Duration::from_millis(5)); @@ -25,7 +25,7 @@ fn opened(state: &mut AppState, doc: DocumentId, offset: u64) -> DocumentId { settle(state); (state.active_document) .filter(|&d| d != doc) - .unwrap_or_else(|| panic!("the body: {}", state.error_dialog_message)) + .unwrap_or_else(|| panic!("the body: {}", state.error_dialog.message)) } /// An archive of `bodies`, each deflated at the start of a 4 KiB page from 0x1000. diff --git a/src/state/gta6/drawable/gta6_edit/tests.rs b/src/state/gta6/drawable/gta6_edit/tests.rs index 25b6e6ef9..1776fd7f8 100644 --- a/src/state/gta6/drawable/gta6_edit/tests.rs +++ b/src/state/gta6/drawable/gta6_edit/tests.rs @@ -72,7 +72,7 @@ pub(in crate::state) fn drawable_body() -> Vec { fn finished(state: &mut AppState) { let deadline = Instant::now() + Duration::from_secs(30); - while state.extract_jobs.is_running() { + while state.bg.extract_jobs.is_running() { state.poll_extract_job(); assert!(Instant::now() < deadline, "the save never ended"); std::thread::sleep(Duration::from_millis(5)); @@ -92,7 +92,7 @@ fn opened(state: &mut AppState, path: PathBuf, not: DocumentId) -> DocumentId { settle(state); (state.active_document) .filter(|&d| d != not) - .unwrap_or_else(|| panic!("opened: {}", state.error_dialog_message)) + .unwrap_or_else(|| panic!("opened: {}", state.error_dialog.message)) } /// The texture key of `name`, which the app then knows by that name. @@ -125,7 +125,7 @@ fn a_material_edit_undoes_and_saves_as_a_loose_resource_that_reads_back_to_it() settle(&mut state); let doc = (state.active_document) .filter(|&d| d != archive) - .unwrap_or_else(|| panic!("the drawable: {}", state.error_dialog_message)); + .unwrap_or_else(|| panic!("the drawable: {}", state.error_dialog.message)); let opened_as = shader(&state, doc); assert_eq!(opened_as.texture_keys, [Some(KEY)]); @@ -134,7 +134,7 @@ fn a_material_edit_undoes_and_saves_as_a_loose_resource_that_reads_back_to_it() assert!(state.save_active_document_as(copy.clone())); finished(&mut state); let said: Vec<_> = state.toasts.iter().map(|t| t.message.clone()).collect(); - assert!(copy.exists(), "{said:?} {}", state.error_dialog_message); + assert!(copy.exists(), "{said:?} {}", state.error_dialog.message); assert_eq!(read_back(©).virtual_section, drawable_body()); let words = vec![2.5f32.to_bits(), (-4.0f32).to_bits()]; @@ -199,7 +199,7 @@ fn a_material_edit_undoes_and_saves_as_a_loose_resource_that_reads_back_to_it() assert!(state.save_active_document_as(saved.clone())); finished(&mut state); let said: Vec<_> = state.toasts.iter().map(|t| t.message.clone()).collect(); - assert!(saved.exists(), "{said:?} {}", state.error_dialog_message); + assert!(saved.exists(), "{said:?} {}", state.error_dialog.message); let mut expected = drawable_body(); put( &mut expected, diff --git a/src/state/gta6/drawable/gta6_gltf_import/tests.rs b/src/state/gta6/drawable/gta6_gltf_import/tests.rs index 0b497240d..1fd4ec7cd 100644 --- a/src/state/gta6/drawable/gta6_gltf_import/tests.rs +++ b/src/state/gta6/drawable/gta6_gltf_import/tests.rs @@ -157,7 +157,7 @@ fn worked_out(state: &mut AppState) { let deadline = Instant::now() + Duration::from_secs(30); loop { state.poll_gltf(); - if let Some(Asked::Import(asked)) = &state.gltf.asked { + if let Some(Asked::Import(asked)) = &state.bg.gltf.asked { if asked.made.is_some() { return; } @@ -169,7 +169,7 @@ fn worked_out(state: &mut AppState) { fn finished(state: &mut AppState) { let deadline = Instant::now() + Duration::from_secs(30); - while state.extract_jobs.is_running() { + while state.bg.extract_jobs.is_running() { state.poll_extract_job(); assert!(Instant::now() < deadline, "the save never ended"); std::thread::sleep(Duration::from_millis(5)); @@ -187,7 +187,7 @@ fn a_gltf_replaces_a_gta_vi_drawable_s_geometry_as_a_step_that_undoes_and_saves( state.load_file(path.clone()); settle(&mut state); let doc = - (state.active_document).unwrap_or_else(|| panic!("opened: {}", state.error_dialog_message)); + (state.active_document).unwrap_or_else(|| panic!("opened: {}", state.error_dialog.message)); assert_eq!(state.gltf_import_into(GltfModel::Document(doc)), Ok(doc)); // The drawable's own glTF, a fourth vertex and a second triangle added. @@ -209,7 +209,7 @@ fn a_gltf_replaces_a_gta_vi_drawable_s_geometry_as_a_step_that_undoes_and_saves( state.import_gltf(doc, mesh.clone()); worked_out(&mut state); - let Some(Asked::Import(asked)) = &state.gltf.asked else { + let Some(Asked::Import(asked)) = &state.bg.gltf.asked else { panic!("the import's question"); }; assert!(asked.is_gta_vi()); @@ -259,7 +259,7 @@ fn a_mesh_without_normals_at_another_count_is_refused_until_the_fill_is_ticked_a state.load_file(path.clone()); settle(&mut state); let doc = - (state.active_document).unwrap_or_else(|| panic!("opened: {}", state.error_dialog_message)); + (state.active_document).unwrap_or_else(|| panic!("opened: {}", state.error_dialog.message)); // A fourth vertex, and no normals at all. let drawable = read_drawable(§ions.virtual_section, Some(§ions.physical)) @@ -279,7 +279,7 @@ fn a_mesh_without_normals_at_another_count_is_refused_until_the_fill_is_ticked_a state.import_gltf(doc, mesh); worked_out(&mut state); - let Some(Asked::Import(asked)) = &mut state.gltf.asked else { + let Some(Asked::Import(asked)) = &mut state.bg.gltf.asked else { panic!("the import's question"); }; assert!( @@ -289,7 +289,7 @@ fn a_mesh_without_normals_at_another_count_is_refused_until_the_fill_is_ticked_a asked.choice.fill_missing = true; state.rerun_gltf(); worked_out(&mut state); - let Some(Asked::Import(asked)) = &state.gltf.asked else { + let Some(Asked::Import(asked)) = &state.bg.gltf.asked else { panic!("the import's question"); }; let Some(Ok((_, report))) = &asked.made else { diff --git a/src/state/gta6/drawable/gta6_material_layout/tests.rs b/src/state/gta6/drawable/gta6_material_layout/tests.rs index 25d588cf0..89e311ff8 100644 --- a/src/state/gta6/drawable/gta6_material_layout/tests.rs +++ b/src/state/gta6/drawable/gta6_material_layout/tests.rs @@ -28,7 +28,7 @@ fn shader(state: &AppState, doc: DocumentId) -> Shader { fn finished(state: &mut AppState) { let deadline = Instant::now() + Duration::from_secs(30); - while state.extract_jobs.is_running() { + while state.bg.extract_jobs.is_running() { state.poll_extract_job(); assert!(Instant::now() < deadline, "the save never ended"); std::thread::sleep(Duration::from_millis(5)); @@ -54,7 +54,7 @@ fn a_material_laid_out_anew_undoes_and_saves_as_a_loose_resource_that_reads_back settle(&mut state); let doc = (state.active_document) .filter(|&d| d != archive) - .unwrap_or_else(|| panic!("the drawable: {}", state.error_dialog_message)); + .unwrap_or_else(|| panic!("the drawable: {}", state.error_dialog.message)); let opened_as = shader(&state, doc); assert_eq!(opened_as.parameters.len(), 2); @@ -119,7 +119,7 @@ fn a_material_laid_out_anew_undoes_and_saves_as_a_loose_resource_that_reads_back assert!(state.save_active_document_as(saved.clone())); finished(&mut state); let said: Vec<_> = state.toasts.iter().map(|t| t.message.clone()).collect(); - assert!(saved.exists(), "{said:?} {}", state.error_dialog_message); + assert!(saved.exists(), "{said:?} {}", state.error_dialog.message); let sections = read_back(&saved); let body = drawable_body(); let v = §ions.virtual_section; diff --git a/src/state/gta6/install/gta6_first_entry.rs b/src/state/gta6/install/gta6_first_entry.rs index af9f91b09..c5f6e70bf 100644 --- a/src/state/gta6/install/gta6_first_entry.rs +++ b/src/state/gta6/install/gta6_first_entry.rs @@ -260,7 +260,7 @@ mod tests { settle(&mut state); let doc = state.active_document.expect("an open document"); let Some(DocPayload::Hex(hex)) = state.document(doc).map(|d| &d.payload) else { - panic!("its bytes: {}", state.error_dialog_message); + panic!("its bytes: {}", state.error_dialog.message); }; assert_eq!(hex.bytes, held); assert!( @@ -303,7 +303,7 @@ mod tests { let picked = [row_at(&listed, NESTED), row_at(&listed, 0)]; assert!(state.extract_scanned_bodies(doc, &picked, out.clone())); let deadline = Instant::now() + Duration::from_secs(30); - while state.extract_jobs.is_running() { + while state.bg.extract_jobs.is_running() { state.poll_extract_job(); assert!(Instant::now() < deadline, "the extraction never ended"); std::thread::sleep(Duration::from_millis(5)); diff --git a/src/state/gta6/install/gta6_install_harvest.rs b/src/state/gta6/install/gta6_install_harvest.rs index 3bf6db508..d1ff1e9e2 100644 --- a/src/state/gta6/install/gta6_install_harvest.rs +++ b/src/state/gta6/install/gta6_install_harvest.rs @@ -293,7 +293,7 @@ fn keep(file: &Path, kept: &HashMap) -> io::Result<()> { impl AppState { /// Serve the harvest kept in the configuration folder, read on a worker once a session. pub(in crate::state) fn read_kept_harvest(&mut self) { - let harvest = &mut self.texture_packs.dictionaries.harvest; + let harvest = &mut self.gta6_finders.texture_packs.dictionaries.harvest; if std::mem::replace(&mut harvest.read, true) { return; } @@ -327,7 +327,7 @@ impl AppState { return; }; let packs = crate::state::gta6_texture_index::pack_keys(root); - let built = Arc::clone(&self.texture_packs.dictionaries.harvest.built); + let built = Arc::clone(&self.gta6_finders.texture_packs.dictionaries.harvest.built); let doing = tr!( "Reading the drawables and texture dictionaries of every GTA VI archive under {folder}", folder = root.display() @@ -352,7 +352,7 @@ impl AppState { false => NamingEnded::Harvested(read, named), } }); - self.texture_naming.push(run); + self.gta6_finders.texture_naming.push(run); } } diff --git a/src/state/gta6/install/gta6_names.rs b/src/state/gta6/install/gta6_names.rs index 06d0a5fd1..635173505 100644 --- a/src/state/gta6/install/gta6_names.rs +++ b/src/state/gta6/install/gta6_names.rs @@ -363,7 +363,7 @@ impl AppState { _ => NamingEnded::Stopped, } }); - self.texture_naming.push(run); + self.gta6_finders.texture_naming.push(run); } /// Harvest the names of the GTA VI folder open in a tab, the tab in front first; a toast diff --git a/src/state/gta6/install/gta_vi.rs b/src/state/gta6/install/gta_vi.rs index 8751daa56..3da215568 100644 --- a/src/state/gta6/install/gta_vi.rs +++ b/src/state/gta6/install/gta_vi.rs @@ -432,7 +432,7 @@ mod tests { "the open install was closed for a switch that was refused" ); assert!( - state.pending_close.is_none(), + state.prompts.close.is_none(), "a refused switch asked about unsaved work" ); assert!(says( diff --git a/src/state/gta6/modding/batch_export.rs b/src/state/gta6/modding/batch_export.rs index c8d9fa8c4..5f384f7a8 100644 --- a/src/state/gta6/modding/batch_export.rs +++ b/src/state/gta6/modding/batch_export.rs @@ -197,7 +197,7 @@ impl AppState { if roots.is_empty() { return false; } - if let Some(what) = self.extract_jobs.running_noun() { + if let Some(what) = self.bg.extract_jobs.running_noun() { self.show_error_toast(tr!( "{what} is running; export once it is done", what = what @@ -231,7 +231,7 @@ impl AppState { dry_run: false, }; let label = tr!("{count} row(s) as files people open", count = rows.len()); - self.extract_jobs.start( + self.bg.extract_jobs.start( JobKind::Export, label, folder, diff --git a/src/state/gta6/modding/model_replace/tests.rs b/src/state/gta6/modding/model_replace/tests.rs index c739a9d39..f6f8952f7 100644 --- a/src/state/gta6/modding/model_replace/tests.rs +++ b/src/state/gta6/modding/model_replace/tests.rs @@ -182,7 +182,7 @@ fn a_geometry_replaced_in_the_app_is_a_step_that_undoes_and_a_save_makes_again() state.load_file(path.clone()); settle(&mut state); let doc = - (state.active_document).unwrap_or_else(|| panic!("opened: {}", state.error_dialog_message)); + (state.active_document).unwrap_or_else(|| panic!("opened: {}", state.error_dialog.message)); assert_eq!(shown(&state, doc), 3); let mut scene = exported(&body()); diff --git a/src/state/gta6/modding/references.rs b/src/state/gta6/modding/references.rs index 63e3bf009..919a71444 100644 --- a/src/state/gta6/modding/references.rs +++ b/src/state/gta6/modding/references.rs @@ -253,14 +253,14 @@ impl AppState { /// Drop the index of the GTA VI install, which the next list opened reads again. pub(crate) fn gta6_refs_read_again(&mut self) { - self.dependencies.gta6.forget(); + self.bg.dependencies.gta6.forget(); } fn gta6_answer(&mut self, doc: DocumentId, row: RpfNodeId, used_by: bool) -> Answer { let Some((root, path)) = self.gta6_place(doc, row) else { return Answer::Cannot(tr!("This file is in no GTA VI install folder").to_string()); }; - let refs = &mut self.dependencies.gta6; + let refs = &mut self.bg.dependencies.gta6; let index = match refs.index(&root) { Ok(index) => index, Err(answer) => return answer, @@ -295,7 +295,7 @@ impl AppState { }; let inner = rpf.session.path_of(row)?; let path = document.path.clone()?; - let roots = &mut self.dependencies.gta6.roots; + let roots = &mut self.bg.dependencies.gta6.roots; let root = roots .entry(path.clone()) .or_insert_with(|| install_of(&path)) @@ -311,7 +311,7 @@ impl AppState { /// Where a finished read of the GTA VI install lands. pub(in crate::state) fn poll_gta6_refs(&mut self) { - if let Some((outcome, said)) = self.dependencies.gta6.poll() { + if let Some((outcome, said)) = self.bg.dependencies.gta6.poll() { self.jobs.record(JobKind::Dependencies, outcome, said); } } diff --git a/src/state/gta6/modding/texture_replace.rs b/src/state/gta6/modding/texture_replace.rs index ca1f11a14..1e238105a 100644 --- a/src/state/gta6/modding/texture_replace.rs +++ b/src/state/gta6/modding/texture_replace.rs @@ -44,7 +44,7 @@ fn a_picture_replaces_a_bcpack_coded_texture_of_an_open_pack_and_saves_it_in_cod assert!( save_as(&mut state, doc, &saved), "{}", - state.error_dialog_message + state.error_dialog.message ); let reopened = or_io::gta6::TexturePack::open(&saved).expect("the saved pack opens"); let rows = reopened.rows_of(0).expect("its rows"); diff --git a/src/state/gta6/particles/gta6_particle_models.rs b/src/state/gta6/particles/gta6_particle_models.rs index 18c3002e5..42429ddd8 100644 --- a/src/state/gta6/particles/gta6_particle_models.rs +++ b/src/state/gta6/particles/gta6_particle_models.rs @@ -222,7 +222,7 @@ impl Drop for ModelFinding { impl AppState { /// The job list's row for the search, while it runs. pub(in crate::state) fn particle_model_finding_job(&self) -> Option { - let finding = self.particle_model_finding.as_ref()?; + let finding = self.gta6_finders.particle_model_finding.as_ref()?; if finding.ended().is_some() { return None; } @@ -237,7 +237,7 @@ impl AppState { /// Ask the search to stop; it says it stopped once its worker sees the stop. pub(in crate::state) fn stop_particle_model_finding(&self) { - if let Some(finding) = &self.particle_model_finding { + if let Some(finding) = &self.gta6_finders.particle_model_finding { finding.cancel.set(); } } @@ -260,18 +260,19 @@ impl AppState { tr!("Open the whole scan of an archive to look for the drawables in.").to_string(), ); } - self.particle_model_finding = Some(ModelFinding::start(bodies, wanted)); + self.gta6_finders.particle_model_finding = Some(ModelFinding::start(bodies, wanted)); Ok(()) } /// Say in the job list how the search ended, once it has, and drop it; a drawable found /// rebuilds the effect the preview plays, so its mesh domains take the model's surface. pub(in crate::state) fn poll_particle_model_finding(&mut self) { - let Some(ended) = (self.particle_model_finding.as_ref()).and_then(ModelFinding::ended) + let Some(ended) = + (self.gta6_finders.particle_model_finding.as_ref()).and_then(ModelFinding::ended) else { return; }; - self.particle_model_finding = None; + self.gta6_finders.particle_model_finding = None; let (outcome, said) = match ended { FindEnded::Found(found, of) => { self.sim.pending_rebuild |= found > 0; diff --git a/src/state/gta6/physics/gta6_navmesh.rs b/src/state/gta6/physics/gta6_navmesh.rs index 5e22542df..3f95d1fdd 100644 --- a/src/state/gta6/physics/gta6_navmesh.rs +++ b/src/state/gta6/physics/gta6_navmesh.rs @@ -463,14 +463,15 @@ impl AppState { }); *ended.lock().unwrap_or_else(|p| p.into_inner()) = Some(outcome); }); - self.neighbour_search = Some(found); + self.gta6_finders.neighbour_search = Some(found); } /// Open the cells the search found and say how it ended, once. pub(in crate::state) fn poll_neighbour_search(&mut self) { - let ended = (self.neighbour_search.as_ref()).and_then(|s| s.ended.lock().ok()?.take()); + let ended = + (self.gta6_finders.neighbour_search.as_ref()).and_then(|s| s.ended.lock().ok()?.take()); if ended.is_some() { - self.neighbour_search = None; + self.gta6_finders.neighbour_search = None; } let (outcome, said) = match ended { None => return, @@ -495,7 +496,7 @@ impl AppState { /// The search while it runs, as the job list draws it. pub(in crate::state) fn neighbour_search_job(&self) -> Option { - let s = self.neighbour_search.as_ref()?; + let s = self.gta6_finders.neighbour_search.as_ref()?; if s.ended.lock().ok()?.is_some() { return None; } @@ -509,7 +510,7 @@ impl AppState { } pub(in crate::state) fn stop_neighbour_search(&self) { - if let Some(s) = &self.neighbour_search { + if let Some(s) = &self.gta6_finders.neighbour_search { s.cancel.set(); } } diff --git a/src/state/gta6/physics/gta6_navmesh_delete/mod.rs b/src/state/gta6/physics/gta6_navmesh_delete/mod.rs index b595920e1..bd8b60ddd 100644 --- a/src/state/gta6/physics/gta6_navmesh_delete/mod.rs +++ b/src/state/gta6/physics/gta6_navmesh_delete/mod.rs @@ -403,7 +403,7 @@ mod tests { settle(&mut state); let doc = (state.active_document) .filter(|&d| d != archive) - .unwrap_or_else(|| panic!("the cell: {}", state.error_dialog_message)); + .unwrap_or_else(|| panic!("the cell: {}", state.error_dialog.message)); (state, doc) } @@ -490,7 +490,7 @@ mod tests { fn finished(state: &mut AppState) { let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30); - while state.extract_jobs.is_running() { + while state.bg.extract_jobs.is_running() { state.poll_extract_job(); assert!(std::time::Instant::now() < deadline, "the save never ended"); std::thread::sleep(std::time::Duration::from_millis(5)); diff --git a/src/state/gta6/physics/gta6_navmesh_edit.rs b/src/state/gta6/physics/gta6_navmesh_edit.rs index e8fd6429e..0792f7904 100644 --- a/src/state/gta6/physics/gta6_navmesh_edit.rs +++ b/src/state/gta6/physics/gta6_navmesh_edit.rs @@ -242,7 +242,7 @@ mod tests { settle(&mut state); let doc = (state.active_document) .filter(|&d| d != archive) - .unwrap_or_else(|| panic!("the cell: {}", state.error_dialog_message)); + .unwrap_or_else(|| panic!("the cell: {}", state.error_dialog.message)); (state, doc) } diff --git a/src/state/gta6/physics/gta6_physics_edit/tests.rs b/src/state/gta6/physics/gta6_physics_edit/tests.rs index 1f6c15bd2..1be4ed782 100644 --- a/src/state/gta6/physics/gta6_physics_edit/tests.rs +++ b/src/state/gta6/physics/gta6_physics_edit/tests.rs @@ -53,13 +53,13 @@ fn opened_body(dir: &Path, body: &[u8]) -> (AppState, DocumentId) { settle(&mut state); let doc = (state.active_document) .filter(|&d| d != archive) - .unwrap_or_else(|| panic!("the body: {}", state.error_dialog_message)); + .unwrap_or_else(|| panic!("the body: {}", state.error_dialog.message)); (state, doc) } fn finished(state: &mut AppState) { let deadline = Instant::now() + Duration::from_secs(30); - while state.extract_jobs.is_running() { + while state.bg.extract_jobs.is_running() { state.poll_extract_job(); assert!(Instant::now() < deadline, "the save never ended"); std::thread::sleep(Duration::from_millis(5)); @@ -81,7 +81,7 @@ fn saved(state: &mut AppState, dir: &Path, name: &str) -> PathBuf { assert!(state.save_active_document_as(path.clone())); finished(state); let said: Vec<_> = state.toasts.iter().map(|t| t.message.clone()).collect(); - assert!(path.exists(), "{said:?} {}", state.error_dialog_message); + assert!(path.exists(), "{said:?} {}", state.error_dialog.message); path } diff --git a/src/state/gta6/textures/gta6_dictionary_index.rs b/src/state/gta6/textures/gta6_dictionary_index.rs index ea37ed17a..ac4472fb6 100644 --- a/src/state/gta6/textures/gta6_dictionary_index.rs +++ b/src/state/gta6/textures/gta6_dictionary_index.rs @@ -179,36 +179,46 @@ impl AppState { return false; }; let doc_id = doc.id; - let misses = self.texture_report.document == Some(doc_id) - && !self.texture_report.missing().is_empty(); + let misses = self.textures.report.document == Some(doc_id) + && !self.textures.report.missing().is_empty(); if !misses || !matches!(doc.payload, DocPayload::Gta6Drawable(_)) { return false; } - if self.texture_packs.dictionaries.opening.is_some() { + if self + .gta6_finders + .texture_packs + .dictionaries + .opening + .is_some() + { return false; } let (archives, _) = whole_scans(&self.documents, false); - if archives != self.texture_packs.dictionaries.archives { + if archives != self.gta6_finders.texture_packs.dictionaries.archives { self.index_texture_dictionaries(archives); return false; } let wanted: Vec = { - let held = &self.texture_packs.dictionaries; + let held = &self.gta6_finders.texture_packs.dictionaries; let open = held.built.lock().unwrap_or_else(|p| p.into_inner()); let harvest = held.harvest.built.lock(); let harvest = harvest.unwrap_or_else(|p| p.into_inner()); let indexes = [open.as_ref(), harvest.as_ref()]; - (self.texture_report.missing().into_iter()) + (self.textures.report.missing().into_iter()) .filter_map(crate::state::gta6_texture_index::key_of) .filter_map(|key| indexes.into_iter().flatten().find_map(|i| i.body_of(key))) .cloned() .collect() }; - let tried = &self.texture_packs.dictionaries.tried; + let tried = &self.gta6_finders.texture_packs.dictionaries.tried; let open = |path: &Path| (self.documents.iter()).any(|d| d.path.as_deref() == Some(path)); let next = (wanted.into_iter()).find(|path| !open(path) && !tried.contains(path)); if let Some(path) = next { - self.texture_packs.dictionaries.tried.insert(path.clone()); + self.gta6_finders + .texture_packs + .dictionaries + .tried + .insert(path.clone()); self.read_texture_dictionary(path); } false @@ -217,7 +227,7 @@ impl AppState { /// Index the dictionaries of the whole scans of `archives` on a worker, in place of any index before it. fn index_texture_dictionaries(&mut self, archives: Vec) { let (_, bodies) = whole_scans(&self.documents, true); - let held = &mut self.texture_packs.dictionaries; + let held = &mut self.gta6_finders.texture_packs.dictionaries; *held = DictionaryIndex { archives, harvest: std::mem::take(&mut held.harvest), @@ -236,13 +246,13 @@ impl AppState { *built.lock().unwrap_or_else(|p| p.into_inner()) = Some(found); NamingEnded::Dictionaries(read) }); - self.texture_naming.push(run); + self.gta6_finders.texture_naming.push(run); } /// Read the dictionary at `path`, a scan row's body, on a worker. fn read_texture_dictionary(&mut self, path: PathBuf) { let opening: Opening = Arc::default(); - self.texture_packs.dictionaries.opening = Some(Arc::clone(&opening)); + self.gta6_finders.texture_packs.dictionaries.opening = Some(Arc::clone(&opening)); std::thread::spawn(move || { let read = match scanned_body(&path) { Some((archive, offset)) => { @@ -256,14 +266,20 @@ impl AppState { /// Open the dictionary its worker read beside the drawable that asked for it, once read; whether one opened. fn take_opened_dictionary(&mut self) -> bool { - let Some(opening) = self.texture_packs.dictionaries.opening.as_ref() else { + let Some(opening) = self + .gta6_finders + .texture_packs + .dictionaries + .opening + .as_ref() + else { return false; }; let taken = opening.lock().unwrap_or_else(|p| p.into_inner()).take(); let Some((path, read)) = taken else { return false; }; - self.texture_packs.dictionaries.opening = None; + self.gta6_finders.texture_packs.dictionaries.opening = None; let payload = match read { Ok(payload) => payload, Err(error) => { diff --git a/src/state/gta6/textures/gta6_dictionary_write/tests.rs b/src/state/gta6/textures/gta6_dictionary_write/tests.rs index e9f6a5580..dd5d99485 100644 --- a/src/state/gta6/textures/gta6_dictionary_write/tests.rs +++ b/src/state/gta6/textures/gta6_dictionary_write/tests.rs @@ -16,7 +16,7 @@ use crate::state::{AppState, DocumentId}; fn finished(state: &mut AppState) { let deadline = Instant::now() + Duration::from_secs(30); - while state.extract_jobs.is_running() { + while state.bg.extract_jobs.is_running() { state.poll_extract_job(); assert!(Instant::now() < deadline, "the save never ended"); std::thread::sleep(Duration::from_millis(5)); @@ -76,7 +76,7 @@ fn a_scanned_dictionary_texture_resized_re_encoded_and_added_saves_planned_anew_ let mut state = AppState::new(); state.load_file(path); settle(&mut state); - let doc = (state.active_document).unwrap_or_else(|| panic!("{}", state.error_dialog_message)); + let doc = (state.active_document).unwrap_or_else(|| panic!("{}", state.error_dialog.message)); let opened = textures(&state, doc); let start = state.document(doc).expect("open").history.at(); let (at, options) = (TextureSource::Document, TextureBuildOptions::default()); @@ -127,7 +127,7 @@ fn a_scanned_dictionary_texture_resized_re_encoded_and_added_saves_planned_anew_ assert!(state.save_active_document_as(saved.clone())); finished(&mut state); let said: Vec<_> = state.toasts.iter().map(|t| t.message.clone()).collect(); - assert!(saved.exists(), "{said:?} {}", state.error_dialog_message); + assert!(saved.exists(), "{said:?} {}", state.error_dialog.message); let sections = read_back(&saved); let read = read_dictionary(§ions.virtual_section, Some(§ions.physical)).expect("it reads"); diff --git a/src/state/gta6/textures/gta6_embedded_edit/mod.rs b/src/state/gta6/textures/gta6_embedded_edit/mod.rs index 382e66d3b..ff95c836d 100644 --- a/src/state/gta6/textures/gta6_embedded_edit/mod.rs +++ b/src/state/gta6/textures/gta6_embedded_edit/mod.rs @@ -379,7 +379,7 @@ impl AppState { if let Some(document) = self.document_mut(doc) { document.history.seal(); } - self.texture_cache.forget_document(doc); + self.textures.cache.forget_document(doc); } } diff --git a/src/state/gta6/textures/gta6_embedded_edit/tests.rs b/src/state/gta6/textures/gta6_embedded_edit/tests.rs index 9cab34f84..cdf1ea068 100644 --- a/src/state/gta6/textures/gta6_embedded_edit/tests.rs +++ b/src/state/gta6/textures/gta6_embedded_edit/tests.rs @@ -68,7 +68,7 @@ fn embedding_body() -> (Vec, u64) { fn finished(state: &mut AppState) { let deadline = Instant::now() + Duration::from_secs(30); - while state.extract_jobs.is_running() { + while state.bg.extract_jobs.is_running() { state.poll_extract_job(); assert!(Instant::now() < deadline, "the save never ended"); std::thread::sleep(Duration::from_millis(5)); @@ -109,7 +109,7 @@ fn an_embedded_texture_is_replaced_drawn_undone_and_saved_into_its_own_tiles() { state.load_file(path.clone()); settle(&mut state); let doc = - (state.active_document).unwrap_or_else(|| panic!("opened: {}", state.error_dialog_message)); + (state.active_document).unwrap_or_else(|| panic!("opened: {}", state.error_dialog.message)); let name = texture_name(key); assert!(embeds(&state, doc, &name)); assert!(!embeds(&state, doc, "hash_0000000000000001")); diff --git a/src/state/gta6/textures/gta6_texture_index.rs b/src/state/gta6/textures/gta6_texture_index.rs index 8ab7eca86..9abc476bc 100644 --- a/src/state/gta6/textures/gta6_texture_index.rs +++ b/src/state/gta6/textures/gta6_texture_index.rs @@ -471,8 +471,8 @@ impl AppState { /// Have `doc`'s textures come from the packs under `root`, whatever folder its file is in, and /// keep the index of those packs when a document is let go. pub(crate) fn serve_textures_from(&mut self, doc: DocumentId, root: &Path) { - (self.texture_packs.asked).insert(doc, Some(root.to_path_buf())); - self.texture_packs.kept_across_documents = true; + (self.gta6_finders.texture_packs.asked).insert(doc, Some(root.to_path_buf())); + self.gta6_finders.texture_packs.kept_across_documents = true; } /// Whether the active GTA VI drawable binds a key nothing open holds. @@ -482,13 +482,13 @@ impl AppState { /// Whether a worker still opens a pack [`Self::try_open_texture_pack`] asked for. pub(crate) fn texture_packs_opening(&self) -> bool { - !self.texture_packs.opening.asked.is_empty() + !self.gta6_finders.texture_packs.opening.asked.is_empty() } /// Add as documents, once every one asked for is in and in the order asked, the packs workers /// have opened; whether one was. fn take_opened_texture_packs(&mut self) -> bool { - let opening = &mut self.texture_packs.opening; + let opening = &mut self.gta6_finders.texture_packs.opening; let mut opened = { let mut opened = opening.opened.lock().unwrap_or_else(|p| p.into_inner()); if opened.len() < opening.asked.len() { @@ -513,7 +513,7 @@ impl AppState { let id = self.alloc_doc_id(); let payload = DocPayload::Ttpf(Arc::new(ttpf)); (self.documents).push(Document::new(id, Some(path.clone()), payload)); - self.auto_opened_texture_docs.insert(id); + self.textures.auto_opened_docs.insert(id); tracing::info!(path = %path.display(), "opened the texture pack that holds a drawable's key"); any = true; } @@ -523,18 +523,21 @@ impl AppState { /// Have workers open the packs the active drawable's missing maps are in, each once. fn ask_for_texture_packs(&mut self) { // A drawable that asked and closed reopens under another id, so its folder is walked again. - let (documents, asked) = (&self.documents, self.texture_packs.asked.len()); - (self.texture_packs.asked).retain(|id, _| documents.iter().any(|d| d.id == *id)); - if self.texture_packs.asked.len() < asked && !self.texture_packs.kept_across_documents { - self.texture_packs.forget(); + let (documents, asked) = (&self.documents, self.gta6_finders.texture_packs.asked.len()); + (self.gta6_finders.texture_packs.asked) + .retain(|id, _| documents.iter().any(|d| d.id == *id)); + if self.gta6_finders.texture_packs.asked.len() < asked + && !self.gta6_finders.texture_packs.kept_across_documents + { + self.gta6_finders.texture_packs.forget(); } let Some(doc) = self.active_document() else { return; }; let doc_id = doc.id; // The maps the drawable names and nothing open holds, then the tiles of its material. - let mut missing: Vec = match self.texture_report.document == Some(doc_id) { - true => (self.texture_report.missing().into_iter()) + let mut missing: Vec = match self.textures.report.document == Some(doc_id) { + true => (self.textures.report.missing().into_iter()) .filter_map(key_of) .collect(), false => Vec::new(), @@ -545,18 +548,21 @@ impl AppState { if missing.is_empty() || !matches!(doc.payload, DocPayload::Gta6Drawable(_)) { return; } - let root = match self.texture_packs.asked.get(&doc_id) { + let root = match self.gta6_finders.texture_packs.asked.get(&doc_id) { Some(root) => root.clone(), None => root_of(self, doc), }; - self.texture_packs.asked.insert(doc_id, root.clone()); + self.gta6_finders + .texture_packs + .asked + .insert(doc_id, root.clone()); // ponytail: one index at a time, walked again when a drawable under another folder asks. - if root.is_some() && root != self.texture_packs.root { + if root.is_some() && root != self.gta6_finders.texture_packs.root { self.index_texture_packs(root); return; } let wanted: Vec = { - let built = self.texture_packs.built.lock(); + let built = self.gta6_finders.texture_packs.built.lock(); let built = built.unwrap_or_else(|p| p.into_inner()); let Some(index) = built.as_ref() else { return; @@ -568,15 +574,15 @@ impl AppState { }; // Every pack wanted is asked for at once, so that their headers are read side by side. for path in wanted { let open = (self.documents.iter()).any(|d| d.path.as_deref() == Some(path.as_path())); - if self.texture_packs.tried.insert(path.clone()) && !open { - open_on_a_worker(&mut self.texture_packs.opening, path); + if self.gta6_finders.texture_packs.tried.insert(path.clone()) && !open { + open_on_a_worker(&mut self.gta6_finders.texture_packs.opening, path); } } } /// The format code the directory of the indexed pack that holds `key` states, open or not. pub(crate) fn indexed_texture_format(&self, key: u64) -> Option { - let built = self.texture_packs.built.lock(); + let built = self.gta6_finders.texture_packs.built.lock(); (built .unwrap_or_else(|p| p.into_inner()) .as_ref()? @@ -588,7 +594,7 @@ impl AppState { /// The folder that serves `doc`, once every pack under it is indexed whole and none holds /// texture `name`, which no open document resolves either: there is no texture to load for it. pub(crate) fn held_by_no_pack(&self, doc: DocumentId, name: &str) -> Option { - let packs = &self.texture_packs; + let packs = &self.gta6_finders.texture_packs; // ⚠ Another drawable's folder may be the one indexed now: its packs say nothing of this one's keys. let root = (packs.asked.get(&doc)?.as_ref()).filter(|r| packs.root.as_ref() == Some(r))?; let key = key_of(name)?; @@ -608,7 +614,7 @@ impl AppState { /// 0 until the packs are indexed, then a count that moves with each index: what was built from [`Self::held_by_no_pack`] is built again when it moves. pub(crate) fn texture_packs_indexed(&self) -> u64 { - let built = self.texture_packs.built.lock(); + let built = self.gta6_finders.texture_packs.built.lock(); let built = built.unwrap_or_else(|p| p.into_inner()); built .as_ref() @@ -617,8 +623,10 @@ impl AppState { /// Forget the index once `path`, which the app wrote, moved or removed, is under its folder. pub(in crate::state) fn texture_packs_changed(&mut self, path: &Path) { - if (self.texture_packs.root.as_deref()).is_some_and(|root| path.starts_with(root)) { - self.texture_packs.forget(); + if (self.gta6_finders.texture_packs.root.as_deref()) + .is_some_and(|root| path.starts_with(root)) + { + self.gta6_finders.texture_packs.forget(); } } @@ -628,14 +636,14 @@ impl AppState { return; }; let built = Arc::new(Mutex::new(None)); - self.texture_packs = PackIndex { + self.gta6_finders.texture_packs = PackIndex { root, built: Arc::clone(&built), - asked: std::mem::take(&mut self.texture_packs.asked), + asked: std::mem::take(&mut self.gta6_finders.texture_packs.asked), tried: HashSet::new(), - opening: std::mem::take(&mut self.texture_packs.opening), - dictionaries: std::mem::take(&mut self.texture_packs.dictionaries), - kept_across_documents: self.texture_packs.kept_across_documents, + opening: std::mem::take(&mut self.gta6_finders.texture_packs.opening), + dictionaries: std::mem::take(&mut self.gta6_finders.texture_packs.dictionaries), + kept_across_documents: self.gta6_finders.texture_packs.kept_across_documents, }; let doing = tr!( "Indexing the GTA VI texture packs under {folder}", @@ -651,7 +659,7 @@ impl AppState { *built.lock().unwrap_or_else(|p| p.into_inner()) = Some(index); NamingEnded::Indexed(packs, opened) }); - self.texture_naming.push(run); + self.gta6_finders.texture_naming.push(run); } } @@ -752,7 +760,7 @@ mod tests { formats: HashMap::from([(normal, 71 << 3), (colour, 72 << 3)]), whole: true, }; - state.texture_packs.built = Arc::new(Mutex::new(Some(index))); + state.gta6_finders.texture_packs.built = Arc::new(Mutex::new(Some(index))); assert_eq!(state.indexed_texture_format(colour), Some(72 << 3)); assert_eq!(state.indexed_texture_format(colour ^ 1), None); assert_eq!(base(&state), Some(texture_name(colour))); diff --git a/src/state/gta6/textures/gta6_texture_names_file.rs b/src/state/gta6/textures/gta6_texture_names_file.rs index 2f9a576ae..0c322a6b9 100644 --- a/src/state/gta6/textures/gta6_texture_names_file.rs +++ b/src/state/gta6/textures/gta6_texture_names_file.rs @@ -68,6 +68,6 @@ impl AppState { } NamingEnded::Loaded(named) }); - self.texture_naming.push(run); + self.gta6_finders.texture_naming.push(run); } } diff --git a/src/state/gta6/textures/gta6_texture_naming.rs b/src/state/gta6/textures/gta6_texture_naming.rs index 4f409b36d..86034737f 100644 --- a/src/state/gta6/textures/gta6_texture_naming.rs +++ b/src/state/gta6/textures/gta6_texture_naming.rs @@ -113,24 +113,32 @@ impl Drop for TextureNaming { impl AppState { /// The naming runs still running, as the job list draws them. pub(in crate::state) fn texture_naming_jobs(&self) -> impl Iterator + '_ { - self.texture_naming.iter().filter_map(TextureNaming::job) + self.gta6_finders + .texture_naming + .iter() + .filter_map(TextureNaming::job) } /// Ask every naming run to stop; each says it stopped once its worker sees the stop. pub(in crate::state) fn stop_texture_naming(&self) { - self.texture_naming.iter().for_each(|n| n.cancel.set()); + self.gta6_finders + .texture_naming + .iter() + .for_each(|n| n.cancel.set()); } /// Say in the job list how each naming run that ended went, and drop it. pub(in crate::state) fn poll_texture_naming(&mut self) { let mut ended = Vec::new(); - self.texture_naming.retain(|n| match n.ended() { - Some(e) => { - ended.push(e); - false - } - None => true, - }); + self.gta6_finders + .texture_naming + .retain(|n| match n.ended() { + Some(e) => { + ended.push(e); + false + } + None => true, + }); for e in ended { let (outcome, said) = match e { NamingEnded::Named(count) => ( diff --git a/src/state/gta6/world/gta6_map/mod.rs b/src/state/gta6/world/gta6_map/mod.rs index 680988207..2f31624d5 100644 --- a/src/state/gta6/world/gta6_map/mod.rs +++ b/src/state/gta6/world/gta6_map/mod.rs @@ -437,7 +437,7 @@ impl AppState { dictionaries, }; let offsets = [types, bodies, dictionary_bodies]; - (self.map_search).push(ArchetypeSearch::start(archive, offsets, looked_for)); + (self.gta6_finders.map_search).push(ArchetypeSearch::start(archive, offsets, looked_for)); Ok(()) } @@ -457,17 +457,24 @@ impl AppState { /// The searches still running, as the job list draws them. pub(in crate::state) fn map_search_jobs(&self) -> impl Iterator + '_ { - (self.map_search.iter().filter_map(ArchetypeSearch::job)) - .chain(self.models_in_place_job()) - .chain(crate::state::gta6_world::fill::job()) - .chain(entity::job()) - .chain((self.workbench.maps.gta6.world_removal.as_ref()).and_then(WorldRemoval::job)) - .chain(crate::state::gta6_world::worldview::viewer().job()) + (self + .gta6_finders + .map_search + .iter() + .filter_map(ArchetypeSearch::job)) + .chain(self.models_in_place_job()) + .chain(crate::state::gta6_world::fill::job()) + .chain(entity::job()) + .chain((self.workbench.maps.gta6.world_removal.as_ref()).and_then(WorldRemoval::job)) + .chain(crate::state::gta6_world::worldview::viewer().job()) } /// Ask every search to stop; each says it stopped once its worker sees the stop. pub(in crate::state) fn stop_map_search(&self) { - self.map_search.iter().for_each(|s| s.cancel.set()); + self.gta6_finders + .map_search + .iter() + .for_each(|s| s.cancel.set()); self.stop_models_in_place(); crate::state::gta6_world::fill::stop(); entity::stop(); @@ -479,7 +486,7 @@ impl AppState { /// Say in the job list how each search that ended went, and drop it. pub(in crate::state) fn poll_map_search(&mut self) { let mut ended = Vec::new(); - self.map_search.retain(|s| match s.ended() { + self.gta6_finders.map_search.retain(|s| match s.ended() { Some(e) => { ended.push(e); false @@ -548,8 +555,12 @@ impl AppState { fn select_what_was_wanted_on_the_map(&mut self) { // ⚠ A body that did not open is let go: it would select itself the day a person opens that map. if let Some((path, _)) = &self.workbench.maps.gta6.wanted { - let loading = self.load_receiver.as_ref().map(|(loading, _)| loading); - if !self.pending_loads.contains(path) + let loading = self + .io_queue + .load_receiver + .as_ref() + .map(|(loading, _)| loading); + if !self.io_queue.pending_loads.contains(path) && loading != Some(path) && self.document_holding(path, None).is_none() { diff --git a/src/state/gta6/world/gta6_map/tests.rs b/src/state/gta6/world/gta6_map/tests.rs index 1da7e2597..919add4a6 100644 --- a/src/state/gta6/world/gta6_map/tests.rs +++ b/src/state/gta6/world/gta6_map/tests.rs @@ -131,7 +131,7 @@ fn map_types_body(word: u64, name: u32) -> Vec { fn finished(state: &mut AppState) { let deadline = Instant::now() + Duration::from_secs(30); - while !state.map_search.is_empty() { + while !state.gta6_finders.map_search.is_empty() { state.poll_map_search(); assert!(Instant::now() < deadline, "the search never ended"); std::thread::sleep(Duration::from_millis(5)); @@ -157,7 +157,11 @@ fn an_archetype_a_map_names_is_found_among_the_bodies_of_its_scan_as_a_job() { assert_eq!(state.scanned_map().map(ScannedMap::markers), Some(2)); state.find_gta6_archetypes().expect("a scan to look in"); - assert_eq!(state.map_search.len(), 1, "the search is a job"); + assert_eq!( + state.gta6_finders.map_search.len(), + 1, + "the search is a job" + ); assert!(state .running_jobs() .iter() @@ -232,7 +236,7 @@ fn what_another_screen_asked_for_is_selected_once_its_map_is_shown_and_let_go_wh // A body still on its way is waited for, and nothing is selected meanwhile. state.workbench.maps.gta6.wanted = Some((map_path.clone(), 1)); - state.pending_loads.push_back(map_path.clone()); + state.io_queue.pending_loads.push_back(map_path.clone()); state.select_what_was_wanted_on_the_map(); assert_eq!( state.workbench.maps.gta6.wanted, @@ -243,7 +247,7 @@ fn what_another_screen_asked_for_is_selected_once_its_map_is_shown_and_let_go_wh assert_eq!(state.active_workspace, before); // Once the Map screen shows it, the entity asked for is selected there and that screen is shown. - state.pending_loads.clear(); + state.io_queue.pending_loads.clear(); let doc = open(&mut state, map_path.clone()); state.active_document = Some(doc); state.refresh_scanned_map(); diff --git a/src/state/install_lifecycle.rs b/src/state/install_lifecycle.rs index 4cd3a56aa..015b8f9ae 100644 --- a/src/state/install_lifecycle.rs +++ b/src/state/install_lifecycle.rs @@ -24,7 +24,8 @@ impl AppState { self.set_active_document(install); if self.keys.has_keys() { if let Some(install) = gta_install_root_from_prefs(&self.prefs) { - self.materials_palette + self.install + .materials_palette .start_load(install.clone(), self.keys.provider()); self.start_shader_definitions_load(install); } @@ -108,13 +109,15 @@ impl AppState { /// its shader container and names parameters as Enhanced materials bind /// them, including in a Gen8 file it ships. pub fn start_shader_definitions_load(&mut self, install_root: PathBuf) { - if or_io::gta5::shaders::shader_defs::is_installed() || self.shader_defs.is_loading() { + if or_io::gta5::shaders::shader_defs::is_installed() + || self.install.shader_defs.is_loading() + { return; } let Some(game) = self.prefs.active_game else { return; }; - self.shader_defs.start_from_install( + self.install.shader_defs.start_from_install( install_root, self.keys.provider(), game.asset_slug(), @@ -123,7 +126,7 @@ impl AppState { } pub fn poll_shader_definitions(&mut self) { - let Some(status) = self.shader_defs.poll() else { + let Some(status) = self.install.shader_defs.poll() else { return; }; match status { @@ -236,10 +239,11 @@ impl AppState { return; }; if let Some(game) = self.prefs.active_game { - self.name_index.retarget(game.asset_slug()); + self.install.name_index.retarget(game.asset_slug()); } let mount = self.prefs.mount_options(); - self.name_index + self.install + .name_index .start_scan(install_root, self.keys.provider(), mount); } @@ -256,14 +260,18 @@ impl AppState { save_prefs(&self.prefs); let mount = self.prefs.mount_options(); - self.name_index.stop_bg_scan(); + self.install.name_index.stop_bg_scan(); self.maybe_start_name_scan(); self.check_overlay_staleness(); if self.keys.has_keys() { if let Some(install_root) = gta_install_root_from_prefs(&self.prefs) { let shadow = self.project_shadow_root(); - self.clip_regions - .start_load(install_root, self.keys.provider(), mount, shadow); + self.install.clip_regions.start_load( + install_root, + self.keys.provider(), + mount, + shadow, + ); } } self.show_toast(if read_overlay_first { @@ -310,9 +318,9 @@ impl AppState { pub fn forget_gta_keys(&mut self) { self.keys.forget(&mut self.prefs); - self.materials_palette.reset(); - self.clip_regions.reset(); - self.shader_defs.reset(); + self.install.materials_palette.reset(); + self.install.clip_regions.reset(); + self.install.shader_defs.reset(); save_prefs(&self.prefs); self.show_toast(tr!("GTA V keys forgotten")); } @@ -332,10 +340,11 @@ impl AppState { ); if let Some(install_root) = gta_install_root_from_prefs(&self.prefs) { let mount = self.prefs.mount_options(); - self.materials_palette + self.install + .materials_palette .start_load(install_root.clone(), self.keys.provider()); let shadow = self.project_shadow_root(); - self.clip_regions.start_load( + self.install.clip_regions.start_load( install_root.clone(), self.keys.provider(), mount, @@ -345,7 +354,7 @@ impl AppState { self.open_game_root(install_root); } // New keys can open archives the last scan could not. - self.name_index.stop_bg_scan(); + self.install.name_index.stop_bg_scan(); self.maybe_start_name_scan(); self.check_overlay_staleness(); self.refresh_game_root_crypto(); @@ -381,7 +390,7 @@ impl AppState { } pub fn poll_material_palette_load(&mut self) { - let Some(result) = self.materials_palette.poll() else { + let Some(result) = self.install.materials_palette.poll() else { return; }; match result { @@ -398,7 +407,7 @@ impl AppState { } pub fn poll_clip_regions_load(&mut self) { - let Some(result) = self.clip_regions.poll() else { + let Some(result) = self.install.clip_regions.poll() else { return; }; match result { @@ -435,13 +444,13 @@ impl AppState { /// Bake the pack of the game's shaders for the viewport once an install is set and none is current. pub fn maybe_auto_bake_game_pack(&mut self) -> Option { let root = gta_install_root_from_prefs(&self.prefs)?; - let event = self.game_pack.maybe_auto_bake(&root)?; + let event = self.install.game_pack.maybe_auto_bake(&root)?; self.note_game_pack(event) } /// The pack's root when a bake of it just finished, for the viewport to read. pub fn poll_game_pack(&mut self) -> Option { - let event = self.game_pack.poll()?; + let event = self.install.game_pack.poll()?; self.note_game_pack(event) } @@ -450,7 +459,7 @@ impl AppState { match event { GamePackEvent::Ready { root, baked } => { if baked { - let said = self.game_pack.status().short_label(); + let said = self.install.game_pack.status().short_label(); self.show_toast(said.clone()); self.jobs .record(JobKind::GamePackBake, Outcome::Done(Then::Nothing), said); @@ -485,13 +494,13 @@ impl AppState { return; }; // The helper finds the keys it needs itself - if let Some(event) = self.game_pack.rebake(&install_root) { + if let Some(event) = self.install.game_pack.rebake(&install_root) { self.note_game_pack(event); } } pub fn poll_game_discovery(&mut self) { - let Some(report) = self.discovery.poll() else { + let Some(report) = self.bg.discovery.poll() else { return; }; let mut wrote_prefs = false; @@ -527,7 +536,8 @@ impl AppState { )); return; } - self.materials_palette + self.install + .materials_palette .start_load(install_root, self.keys.provider()); } diff --git a/src/state/jobs.rs b/src/state/jobs.rs index b7ecb100a..c69427941 100644 --- a/src/state/jobs.rs +++ b/src/state/jobs.rs @@ -213,21 +213,21 @@ impl AppState { /// Every job running now, in the order the list draws them. pub fn running_jobs(&self) -> Vec { [ - self.extract_jobs.job(), - self.defrag.job(), - self.overlay_copy.job(), - self.search.job(), - self.file_index.job(), + self.bg.extract_jobs.job(), + self.bg.defrag.job(), + self.bg.overlay_copy.job(), + self.find.session.job(), + self.find.file_index.job(), self.keys.job(), - self.game_pack.job(), - self.name_index.job(), + self.install.game_pack.job(), + self.install.name_index.job(), self.load_job(), self.save_job(), - self.convert.job(), - self.dlc_pack.job(), - self.gltf.job(), - self.dependencies.job(), - self.compare.job(), + self.bg.convert.job(), + self.bg.dlc_pack.job(), + self.bg.gltf.job(), + self.bg.dependencies.job(), + self.bg.compare.job(), self.project_build_job(), self.project_read_job(), self.project_import_job(), @@ -257,33 +257,33 @@ impl AppState { /// Stop the running job of `kind`: at once where it can drop its work, else once it has finished what it cannot. pub fn cancel_job(&mut self, kind: JobKind) { let dropped = match kind { - JobKind::Extraction | JobKind::Export => self.extract_jobs.request_cancel(kind), + JobKind::Extraction | JobKind::Export => self.bg.extract_jobs.request_cancel(kind), JobKind::Defragment => { - self.defrag.cancel(); + self.bg.defrag.cancel(); false } JobKind::OverlayCopy => { - self.overlay_copy.cancel(); + self.bg.overlay_copy.cancel(); false } JobKind::Search => { - let running = self.search.is_running(); - self.search.stop(); + let running = self.find.session.is_running(); + self.find.session.stop(); running } - JobKind::FileIndex => self.file_index.stop(), + JobKind::FileIndex => self.find.file_index.stop(), JobKind::Keys => { self.keys.cancel(); false } JobKind::GamePackBake => { - self.game_pack.cancel(); + self.install.game_pack.cancel(); false } JobKind::NameScan => { - let running = self.name_index.is_scanning(); + let running = self.install.name_index.is_scanning(); if running { - self.name_index.stop_bg_scan(); + self.install.name_index.stop_bg_scan(); } running } @@ -295,17 +295,17 @@ impl AppState { false } JobKind::Conversion => { - self.convert.cancel(); - self.extract_jobs.request_cancel(kind); + self.bg.convert.cancel(); + self.bg.extract_jobs.request_cancel(kind); false } JobKind::DlcPack => { - self.dlc_pack.cancel(); + self.bg.dlc_pack.cancel(); false } - JobKind::Gltf => self.gltf.cancel(), - JobKind::Dependencies => self.dependencies.cancel(), - JobKind::Compare => self.compare.cancel(), + JobKind::Gltf => self.bg.gltf.cancel(), + JobKind::Dependencies => self.bg.dependencies.cancel(), + JobKind::Compare => self.bg.compare.cancel(), JobKind::ProjectBuild => { self.workbench.stop_building(); self.show_info_toast(tr!( @@ -420,7 +420,7 @@ impl AppState { paths: impl IntoIterator, then: &str, ) -> Result<(), String> { - self.no_job_touches(self.extract_jobs.reads(), paths, then) + self.no_job_touches(self.bg.extract_jobs.reads(), paths, then) } /// As [`no_job_reads`](Self::no_job_reads), for what removes or relocates `path`: an extraction still opening its rows also holds every file under the rows it names. @@ -429,7 +429,7 @@ impl AppState { /// archives an opening extraction has asked for, and a save of any other /// file under the install goes ahead. pub(super) fn no_job_holds(&self, path: &Path, then: &str) -> Result<(), String> { - self.no_job_touches(self.extract_jobs.holds(), [path], then) + self.no_job_touches(self.bg.extract_jobs.holds(), [path], then) } fn no_job_touches<'a>( @@ -440,9 +440,9 @@ impl AppState { ) -> Result<(), String> { let reads = [ extraction, - self.convert.reads(), - self.dlc_pack.reads(), - self.compare.reads(), + self.bg.convert.reads(), + self.bg.dlc_pack.reads(), + self.bg.compare.reads(), ]; let reading: Vec<(String, Vec)> = (reads.into_iter().flatten()) .map(|(job, files)| { @@ -550,22 +550,22 @@ impl AppState { } fn poll_search(&mut self) { - if !self.search.poll() { + if !self.find.session.poll() { return; } - let progress = &self.search.progress; + let progress = &self.find.session.progress; let said = tr!( "{hits} hit(s) in {files_seen} file(s) for {asked}", hits = progress.hits, files_seen = progress.files_seen, - asked = self.search.asked() + asked = self.find.session.asked() ); let then = Then::Panel(crate::state::panel_ids::SEARCH); self.jobs.record(JobKind::Search, Outcome::Done(then), said); } fn poll_name_scan(&mut self) { - if let Some(names) = self.name_index.drain_bg() { + if let Some(names) = self.install.name_index.drain_bg() { let said = tr!( "{files} ready for the pickers", files = crate::state::front_door::counted(names, "game name") diff --git a/src/state/media_playback.rs b/src/state/media_playback.rs new file mode 100644 index 000000000..28c3d1172 --- /dev/null +++ b/src/state/media_playback.rs @@ -0,0 +1,417 @@ +//! Audio (`.awc`) and video (`.bik`/`.bk2`) playback, export and replacement operations on [`AppState`]. + +use std::path::{Path, PathBuf}; +use std::sync::MutexGuard; + +use or_io::awc::wav; +#[cfg(test)] +use or_io::awc::wav::read_wav; +use or_io::awc::{ogg, AwcFile, AwcKey}; +use or_media::replace::XmaMarkers; +#[cfg(test)] +use or_media::Codec; + +use crate::audio::opus_job::{Made, OpusJob, Work, RATE}; +use crate::audio::{ + refused_streams, stream_pcm, stream_replaced_change, stream_rows, AwcStreamRow, +}; +use crate::video::{Preview, SoundCue}; + +use super::jobs::{JobKind, Outcome, RunningJob, Then}; +use super::{AppState, DocPayload, DocumentId, DocumentKind, GateOutcome}; + +impl AppState { + // ── AWC audio containers ────────────────────────────────────────────────── + + fn awc_key(&self) -> AwcKey { + self.keys + .keys() + .map_or_else(AwcKey::default, |keys| AwcKey(keys.awc_key)) + } + + fn awc_file_mut(&mut self, doc: DocumentId) -> Result<&mut AwcFile, String> { + let key = self.awc_key(); + match self.document_mut(doc).map(|d| &mut d.payload) { + Some(DocPayload::Awc(awc)) => awc.file(key), + _ => Err("not an .awc document".to_string()), + } + } + + /// The container of `doc` as it was opened, before any edit. + fn awc_as_opened(&self, doc: DocumentId) -> Option { + match self.document(doc).map(|d| &d.payload) { + Some(DocPayload::Awc(awc)) => awc.as_opened(), + _ => None, + } + } + + /// The parsed container, once the AWC key, if it needs one, has unscrambled it. + pub fn awc_file(&mut self, doc: DocumentId) -> Result<&AwcFile, String> { + self.awc_file_mut(doc).map(|file| &*file) + } + + pub fn awc_streams(&mut self, doc: DocumentId) -> Result, String> { + self.awc_file(doc).map(stream_rows) + } + + /// Opens the GTA VI animation resource stream `stream` stores beside its audio, read on the loader. + pub fn awc_open_animation(&mut self, doc: DocumentId, stream: usize) -> Result<(), String> { + let path = self + .document(doc) + .and_then(|d| d.path.clone()) + .unwrap_or_default(); + let file = self.awc_file(doc)?; + let chunk = (file.streams.get(stream)) + .and_then(|s| Some((s.id, s.chunk(or_io::awc::AwcChunkKind::Animation)?))) + .ok_or_else(|| tr!("This stream stores no animation.").to_string())?; + let (id, chunk) = chunk; + let path = path.join(format!("0x{id:08X}.anim")); + let bytes = chunk.payload.clone(); + self.open_bytes(path, DocumentKind::Gta6Anim, bytes); + Ok(()) + } + + /// Writes the edited animation opened from stream `stream` back as its chunk, a step of undo. + pub fn awc_put_animation(&mut self, doc: DocumentId, stream: usize) -> Result<(), String> { + if let Some(why) = self.document(doc).and_then(|d| d.read_only) { + return Err(crate::i18n::tr(why).to_string()); + } + let path = self + .document(doc) + .and_then(|d| d.path.clone()) + .unwrap_or_default(); + let id = (self.awc_file(doc)?.streams.get(stream)) + .filter(|s| s.chunk(or_io::awc::AwcChunkKind::Animation).is_some()) + .map(|s| s.id) + .ok_or_else(|| tr!("This stream stores no animation.").to_string())?; + let opened = path.join(format!("0x{id:08X}.anim")); + let (animation, sections) = (self.documents.iter()) + .find(|d| d.path.as_deref() == Some(opened.as_path())) + .and_then(|d| match &d.payload { + DocPayload::Gta6Anim(r) if r.edited => Some((d.id, r.sections.clone()?)), + _ => None, + }) + .ok_or_else(|| { + tr!("Open this stream's animation and edit it first: no edited animation of it is open.") + .to_string() + })?; + let bytes = + or_io::container::rpf::write_rpf9_resource(§ions).map_err(|e| e.to_string())?; + let file = self.awc_file_mut(doc)?; + let mut edited = file.clone(); + (edited.set_chunk_payload(stream, or_io::awc::AwcChunkKind::Animation, bytes)) + .map_err(|e| e.to_string())?; + let before = std::mem::replace(file, edited); + let change = stream_replaced_change(stream, before); + self.record(doc, tr!("Write the edited animation back"), change); + self.say_the_animation_hashes_are_kept(animation); + Ok(()) + } + + /// [`refused_streams`] of `doc`, whose streams listed are `rows`. + pub fn awc_refused( + &mut self, + doc: DocumentId, + rows: &[AwcStreamRow], + ) -> Option<(usize, String)> { + refused_streams(self.awc_file(doc).ok()?, rows) + } + + /// A stream as a `.wav` file's bytes. + pub fn awc_wav(&mut self, doc: DocumentId, stream: usize) -> Result, String> { + let key = self.awc_key(); + let (samples, rate, channels) = stream_pcm(self.awc_file(doc)?, stream, key)?; + let pcm: Vec = samples.iter().flat_map(|s| s.to_le_bytes()).collect(); + Ok(wav::wav_from_pcm16(&pcm, rate, channels)) + } + + /// A GTA VI stream's Opus packets as `awc export` writes them: Ogg Opus files named for each stream's or channel's id. + pub fn awc_ogg_opus( + &mut self, + doc: DocumentId, + stream: usize, + ) -> Result)>, String> { + let groups = (self.awc_file(doc)?.opus_streams(stream)).map_err(|e| e.to_string())?; + groups + .iter() + .map(|g| { + // A stream that speaks a dialogue line found carries the line as comments. + let comments = super::gta6_dialogue::comments(g.id); + Ok(( + format!("{:08X}.opus", g.id), + ogg::ogg_opus_tagged(g, &comments).map_err(|e| e.to_string())?, + )) + }) + .collect() + } + + pub fn awc_play(&mut self, doc: DocumentId, stream: usize) -> Result<(), String> { + let key = self.awc_key(); + let (samples, rate, channels) = stream_pcm(self.awc_file(doc)?, stream, key)?; + self.audio.play_stream(doc, stream, rate, channels, samples) + } + + /// Replace a stream's samples from a `.wav` file's bytes, re-encoded to the stream's codec. + #[cfg(test)] + pub fn awc_replace( + &mut self, + doc: DocumentId, + stream: usize, + wav: &[u8], + ) -> Result<(), String> { + self.awc_writable(doc)?; + let (pcm, rate, channels) = read_wav(wav).map_err(|e| e.to_string())?; + let key = self.awc_key(); + let file = self.awc_file_mut(doc)?; + let rows = or_media::awc::streams(file); + let opus = rows + .iter() + .any(|r| r.stream == stream && r.info.codec == Codec::Opus); + let spectra = (rows.iter()).any(|r| r.stream == stream && r.info.codec == Codec::Spectra); + let edited = if opus { + let edited = or_media::opus::replaced(file, stream, &pcm, rate, channels); + edited.map_err(|e| e.to_string()) + } else if spectra { + let edited = or_media::spectra::replaced(file, stream, &pcm, rate, channels); + edited.map_err(|e| e.to_string()) + } else { + let edited = file.with_stream_replaced(stream, &pcm, rate, channels, key); + edited.map_err(|e| e.to_string()) + }?; + self.awc_replaced(doc, stream, edited) + } + + /// `Err` saying why `doc` takes no replace: read-only for any reason but being a body a scan + /// found, whose Save As writes the replaced container. + fn awc_writable(&self, doc: DocumentId) -> Result<(), String> { + match self.document(doc).and_then(|d| d.read_only) { + Some(why) if why != super::rpf9_scan::READ_ONLY_BODY => { + Err(crate::i18n::tr(why).to_string()) + } + _ => Ok(()), + } + } + + /// `edited`, stream `stream` of `doc` replaced in it, made the document's container as an edit. + fn awc_replaced( + &mut self, + doc: DocumentId, + stream: usize, + edited: AwcFile, + ) -> Result<(), String> { + let file = self.awc_file_mut(doc)?; + let before = std::mem::replace(file, edited); + self.audio.stop_stream(doc, stream); + let change = stream_replaced_change(stream, before); + self.record(doc, format!("Replace stream {stream}"), change); + Ok(()) + } + + // ── Opus background decode / encode ─────────────────────────────────────── + + /// Plays Opus stream `stream` of `doc`, or writes it as a WAV at `wav`, decoded on a worker. + pub fn awc_opus_decode( + &mut self, + doc: DocumentId, + stream: usize, + wav: Option, + ) -> Result<(), String> { + if let Some(ref path) = wav { + match self.gate_permits(Some(path)) { + GateOutcome::Proceed => {} + GateOutcome::Refused => return Ok(()), + GateOutcome::Confirm(_) => { + return Err(super::gta6_modding::mod_package::in_game_folder(path)); + } + } + } + let groups = or_media::awc::opus_groups(self.awc_file(doc)?, stream); + let groups = groups.map_err(|e| e.to_string())?; + let doing = if wav.is_some() { + tr!("Decoding an Opus stream to WAV") + } else { + tr!("Decoding an Opus stream to play it") + }; + self.start_opus(doc, stream, doing, Work::Decode { groups, wav }); + Ok(()) + } + + /// Replaces Opus stream `stream` of `doc` from the WAV at `from`, encoded on a worker. + #[cfg(test)] + pub fn awc_opus_replace( + &mut self, + doc: DocumentId, + stream: usize, + from: PathBuf, + ) -> Result<(), String> { + self.awc_writable(doc)?; + let file = self.awc_file(doc)?.clone(); + let doing = tr!("Encoding an Opus stream from a WAV"); + self.start_opus(doc, stream, doing, Work::Encode { file, stream, from }); + Ok(()) + } + + /// Replaces stream `stream` of `doc`, of any codec OpenRage encodes, from the WAV at `from`, + /// fitted to the stream and encoded on a worker. + pub fn awc_replace_from( + &mut self, + doc: DocumentId, + stream: usize, + from: PathBuf, + ) -> Result<(), String> { + self.awc_replace_with(doc, stream, from, XmaMarkers::Keep) + } + + /// [`Self::awc_replace_from`], an XMA stream's granular and marker chunks as `markers` says. + pub fn awc_replace_with( + &mut self, + doc: DocumentId, + stream: usize, + from: PathBuf, + markers: XmaMarkers, + ) -> Result<(), String> { + self.awc_writable(doc)?; + let key = self.awc_key(); + let file = self.awc_file(doc)?.clone(); + let target = or_media::replace::target(&file, stream).map_err(|e| e.to_string())?; + let length = super::gta6_modding::audio_replace::length_for(&target); + let as_read = self.awc_as_opened(doc); + let doing = tr!("Encoding an audio stream from a WAV"); + let work = Work::Fit { + file, + stream, + from, + key, + length, + markers, + as_read, + }; + self.start_opus(doc, stream, doing, work); + Ok(()) + } + + fn start_opus(&mut self, doc: DocumentId, stream: usize, doing: &'static str, work: Work) { + let at = self.document(doc).map_or(0, |d| d.history.at()); + self.audio + .set_opus(OpusJob::start(doc, stream, at, doing, work)); + } + + /// The Opus job, while it runs, as the job list draws it. + pub(crate) fn awc_opus_job(&self) -> Option { + let job = self.audio.opus()?; + if job.ended().is_some() { + return None; + } + Some(RunningJob { + kind: JobKind::OpusAudio, + doing: job.doing.to_string(), + fraction: Some(job.progress.snapshot().fraction()), + detail: String::new(), + stopping: job.cancel.is_set(), + }) + } + + /// Asks the Opus job to stop; [`Self::poll_awc_opus`] says how it ended. + pub(crate) fn stop_awc_opus(&self) { + if let Some(job) = self.audio.opus() { + job.cancel.set(); + } + } + + /// Plays, reports or applies what the Opus job made, once it has ended. + pub(crate) fn poll_awc_opus(&mut self) { + let Some(made) = (self.audio.opus()).and_then(|job| job.ended().take()) else { + return; + }; + let Some(job) = self.audio.take_opus() else { + return; + }; + let kind = JobKind::OpusAudio; + if job.cancel.is_set() { + let said = tr!("Stopped before it finished"); + self.jobs + .record(kind, Outcome::Stopped(Then::Nothing), said); + return; + } + let at = self.document(job.doc).map(|d| d.history.at()); + let ended = match made { + Err(why) => Err(why), + // A stream of a document closed since is not played. + Ok(Made::Samples(..)) if at.is_none() => Ok(None), + Ok(Made::Samples(pcm, channels)) => self + .audio + .play_stream(job.doc, job.stream, RATE, channels, pcm) + .map(|()| None), + Ok(Made::Written(path)) => { + let folder = path.parent().map(Path::to_path_buf).unwrap_or_default(); + let said = tr!("Wrote {path}", path = path.display()); + Ok(Some((Then::OpenFolder(folder), said))) + } + // An edit made or undone while the worker ran is not dropped by the replace. + #[cfg(test)] + Ok(Made::Replaced(..)) if at != Some(job.at) => { + let why = tr!( + "The container changed while its stream was encoded, so the replace is dropped: replace it again" + ); + Err(why.to_string()) + } + Ok(Made::Fitted(..)) if at != Some(job.at) => { + let why = tr!( + "The container changed while its stream was encoded, so the replace is dropped: replace it again" + ); + Err(why.to_string()) + } + #[cfg(test)] + Ok(Made::Replaced(edited, from)) => { + let said = tr!("Replaced the stream from {path}", path = from.display()); + let replaced = self.awc_replaced(job.doc, job.stream, edited); + replaced.map(|()| Some((Then::Show(job.doc), said))) + } + Ok(Made::Fitted(replaced, from)) => { + let said = super::gta6_modding::audio_replace::said(&replaced, &from); + let edited = self.awc_replaced(job.doc, job.stream, replaced.file); + edited.map(|()| Some((Then::Show(job.doc), said))) + } + }; + match ended { + Ok(None) => {} + Ok(Some((then, said))) => { + self.show_toast(said.clone()); + self.jobs.record(kind, Outcome::Done(then), said); + } + Err(why) => { + self.show_error_toast(why.clone()); + self.jobs.record(kind, Outcome::Failed, why); + } + } + } + + // ── Bink video preview ──────────────────────────────────────────────────── + + /// The document's preview, started on first use. + pub fn video_preview(&self, doc: DocumentId) -> Option> { + let DocPayload::Bik(bik) = &self.document(doc)?.payload else { + return None; + }; + Some(bik.lock_prepared()) + } + + /// Gives the speaker what `doc`'s preview owes it: the movie's sound started where the picture + /// stands, or stopped. + pub fn sound_the_movie(&mut self, doc: DocumentId) { + let owed = self + .video_preview(doc) + .map(|mut preview| (preview.take_cue(), preview.position)); + match owed { + Some((Some(SoundCue::Play(sound)), position)) => { + if let Err(why) = self.audio.play_movie(doc, &sound, position) { + if let Some(mut preview) = self.video_preview(doc) { + preview.set_sound_problem(why); + } + } + } + Some((Some(SoundCue::Stop), _)) => self.audio.stop_movie(doc), + _ => {} + } + } +} diff --git a/src/state/memory.rs b/src/state/memory.rs index 8f5ac95d4..ccc0d5e28 100644 --- a/src/state/memory.rs +++ b/src/state/memory.rs @@ -65,14 +65,14 @@ impl AppState { } } CpuState { - name_index: self.name_index.held_bytes(), - file_index: self.file_index.held_bytes(), - search_results: self.search.held_bytes() + self.deep_find.held_bytes(), + name_index: self.install.name_index.held_bytes(), + file_index: self.find.file_index.held_bytes(), + search_results: self.find.session.held_bytes() + self.find.deep.held_bytes(), archive_tree: tree, archive_tables: tables, undo_history: history, simulation: self.sim.held_bytes(), - dependency_index: self.dependencies.held_bytes(), + dependency_index: self.bg.dependencies.held_bytes(), } } } diff --git a/src/state/mod.rs b/src/state/mod.rs index 4cbc2ad52..a65402e40 100644 --- a/src/state/mod.rs +++ b/src/state/mod.rs @@ -1,4 +1,5 @@ mod animation_session; +mod app_clusters; pub mod batch; pub mod bone_numbers; pub mod capabilities; @@ -73,6 +74,7 @@ mod keys; pub mod kinds; mod load_error; mod materials_palette; +mod media_playback; pub mod memory; pub(crate) mod meta_edit; pub mod mod_manager; @@ -134,40 +136,65 @@ pub mod workbench; pub mod workspace; pub mod world_session; -pub use clip_regions::*; -pub use closing::{AfterClose, CloseAnswer, PendingClose}; +pub use app_clusters::{ + AnimationState, BackgroundControllers, ErrorDialog, FrameTelemetry, InstallReferenceData, + PendingPrompts, SearchState, TextureResolutionState, +}; +use app_clusters::{DocumentIoQueue, Gta6Finders}; + +pub use clip_regions::ClipRegionsLoadResult; +pub use closing::{AfterClose, CloseAnswer}; pub use clothing::{Clothing, ClothingVariant}; -pub use document::*; +pub use document::{ + drawable_mut, enhanced_drawable_mut, enhanced_drawables_of, gta6_script, hash_name_or_text, + hash_text_name, meta_names_from_the_text, meta_schema, meta_text_name, name_table_text, + natives_dir, ArchiveId, BaselineValue, DatTable, DocPayload, Document, DocumentId, + DocumentKind, DocumentStrings, FxcDocument, Gta6ScriptDocument, HexDocument, LoadingState, + MaterialAddress, MaterialBaseline, MetaDocument, RelDocument, ResourceImage, RpfNodeId, + ScriptDocument, Slot, TextDocument, STRING_NAMES_NEED_KEYS, +}; pub use document_io::{described_root, never_written}; +use document_io::{empty_file_bytes_for_kind, empty_payload_for_kind, unique_child_name}; pub use edit_history::{Change, ClipFieldSnapshot, EditDirection, EditHistory, Swap}; -pub use expander::*; -pub use extract_job::{ExtractJobs, PendingExportFixes, TypeFilter}; -pub use frame_stats::FrameStats; -pub use game_pack::{GamePackController, GamePackStatus}; -pub use keys::*; -pub use materials_palette::*; +pub use expander::{ + DiskScanItem, ExpansionRequest, ExpansionResult, ResolvedArchive, WorkerArchiveSource, +}; +pub use extract_job::{PendingExportFixes, TypeFilter}; +pub use game_pack::GamePackStatus; +pub use keys::{ + apply_successful_extraction, gta_install_root_from_prefs, rpf_needs_keys, ExtractionResult, + KeysController, +}; +pub use materials_palette::{MaterialPaletteLoadResult, MaterialPaletteStatus}; pub use meta_edit::MetaEdit; pub use models::{DocumentModel, ModelListing}; -pub use or_title::{format_recovery_hint, KnownArchiveNames}; -pub use pending_prompts::*; -pub use prefs::*; -pub use preview_scene::{AnimSession, MeshSource, PreviewScene, SkeletonSource}; -pub use project::*; -pub use rpf::rpf_node::*; -pub use rpf::rpf_session::*; -pub use selection::*; -pub use shader_defs::*; -pub use texture_cache::*; -pub use texture_resolution::{AttachedDictionary, TextureResolutionReport}; +pub use or_title::format_recovery_hint; +pub(crate) use pending_prompts::retail_pending_message; +pub(in crate::state) use pending_prompts::RetailGuard; +pub use pending_prompts::{ + EnhancedOpenDecision, GateOutcome, PendingEnhancedOpen, PendingRetailEdit, + PendingRetailEditPrompt, RetailEditDecision, +}; +#[cfg(test)] +pub use prefs::{config_root, load_prefs_from, real_config_root, save_prefs_to}; +pub use prefs::{ + load_prefs, save_prefs, AppearancePrefs, EditMode, ExportFixes, FontChoice, Game, + PersistedBinding, Prefs, RecentFile, RpfOutputMode, ThemeChoice, ViewportPrefs, + DEFAULT_GPU_TEXTURE_MIB, +}; +pub use preview_scene::{MeshSource, PreviewScene, SkeletonSource}; +pub use project::{ProjectDocument, PROJECT_EXTENSION}; +pub use rpf::rpf_node::{ArchiveSource, RpfNodeBacking, RpfSessionNode, RpfSessionNodeKind}; +pub use rpf::rpf_session::{RpfDocument, RpfEditSession, RpfEntryBinding}; +pub use selection::{DictPart, Selection, SelectionKey, YptDomainKind}; +pub use shader_defs::ShaderDefsStatus; +pub use texture_cache::{CachedTexture, DEFAULT_BUDGET_MIB}; +pub use texture_resolution::TextureResolutionReport; pub use texture_tiles::Tile; pub use textures::{DocumentTexture, TextureListing, TextureResolution, TextureSource}; pub use toasts::{ToastType, Toasts}; pub use workspace::Workspace; -pub use search_session::SearchQuery; - -use document_io::*; - use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::mpsc::{channel, Receiver, Sender}; @@ -212,16 +239,8 @@ pub struct AppState { pub selection: Selection, pub records_selected: presets::RecordSelection, pub presets: presets::PresetLibrary, - pub texture_cache: TextureCache, - pub pinned_texture_docs: std::collections::HashMap>, - pub auto_opened_texture_docs: std::collections::HashSet, - pub attached_texture_docs: Vec, + pub textures: TextureResolutionState, pub clothing: Clothing, - pub attempted_texture_siblings: std::collections::HashSet, - pub attempted_shared_dictionaries: std::collections::HashSet<(DocumentId, &'static str)>, - pub attempted_texture_search_paths: std::collections::HashSet, - pub attempted_texture_project: std::collections::HashSet, - pub texture_report: TextureResolutionReport, pub closed_documents: Vec, pub prefs: Prefs, pub project_path: Option, @@ -231,95 +250,32 @@ pub struct AppState { pub world: world_session::Held, pub front_door: front_door::FrontDoor, pub loading: LoadingState, - /// The file being opened, and where its result arrives. - load_receiver: Option<(PathBuf, Receiver)>, - pending_loads: std::collections::VecDeque, - batch_loading: bool, - save_receiver: Option, - pub show_error_dialog: bool, - /// The operation that failed, as the error window's title names it, and the file when it was an open. - pub error_dialog_title: String, - /// What the reader said, which the window keeps for its details. - pub error_dialog_message: String, - /// One plain sentence in place of `error_dialog_message`, for an open that failed. - pub error_dialog_plain: Option, + io_queue: DocumentIoQueue, + pub error_dialog: ErrorDialog, pub toasts: Toasts, pub keys: KeysController, - pub materials_palette: MaterialsPaletteController, - pub clip_regions: ClipRegionsController, - pub name_index: name_index::NameIndex, - pub interiors: reference_names::InstallInteriors, - pub game_tables: reference_names::InstallTables, - pub search: search_session::SearchSession, - pub search_query: SearchQuery, - pub deep_find: vfs_session::VfsSession, - pub file_index: file_index::FileIndex, + pub install: InstallReferenceData, + pub find: SearchState, pub navigation: navigation::Navigation, pub tabs: tabs::Tabs, - /// The game's shaders as a SPIR-V pack, which a helper program bakes. - pub game_pack: GamePackController, - pub shader_defs: ShaderDefsController, - pub expander: ExpansionWorker, pub panels: panel_state::PanelStore, pub plugins: plugins::PluginSession, pub preview_scene: PreviewScene, pub cameras: viewport_camera::DocumentCameras, - pub anim: AnimSession, - pub anim_edits: or_anim::PoseEdits, - pub anim_transport: or_transport::Transport, + pub animation: AnimationState, pub last_window_title: String, - pub frame_stats: FrameStats, - /// What the viewport holds on the GPU, as the render bridge last published it. - pub gpu_usage: crate::render::gpu_budget::GpuUsage, - /// The stages of the last viewport frame the device timed, each with its milliseconds; none where it cannot time them. - pub gpu_stages: Vec<(&'static str, f32)>, + pub perf: FrameTelemetry, next_doc_id: AtomicU64, - pub known_archive_names: KnownArchiveNames, - pub discovery: game_discovery::DiscoveryWorker, - pub extract_jobs: ExtractJobs, - pub defrag: defrag_job::DefragJobs, - pub convert: convert::Conversions, - pub dlc_pack: dlc_pack::DlcPacks, - pub mod_manager: mod_manager::ModManager, - pub gltf: gltf::Interchange, - pub dependencies: dependencies::Dependencies, - pub compare: compare::Comparisons, - texture_naming: Vec, - texture_packs: gta6_texture_index::PackIndex, - set_finding: Vec, - clip_finding: Option, - particle_model_finding: Option, - map_search: Vec, - neighbour_search: Option, + pub bg: BackgroundControllers, + gta6_finders: Gta6Finders, pub jobs: jobs::JobLog, - /// A delete in the archive tree waiting on its answer. - pub pending_delete: Option, - pub collision_bvh: Option>, - pub retail_edit_session_allow: bool, - pub pending_retail_edit: Option, - /// A write the edit mode refused, offering to change the mode until answered. - pub refused_write: Option, - /// An export waiting on whether to apply OpenRage's export fixes. - pub pending_export_fixes: Option, - /// The answer a drag out asked for, held for the next drag out. - pub drag_out_fixes: Option, - pub pending_enhanced_open: Option, - pub overlay_copy: overlay_copy::OverlayCopy, - pub overlay_loader: overlay_loader::OverlayLoaderChecks, - /// A save of an archive entry waiting on where it goes. - pub save_destination: Option, - /// A close waiting on whether to save what it would drop. - pub pending_close: Option, + pub prompts: PendingPrompts, /// Set once an exit's close has gone ahead; the editor loop exits on it. pub should_exit: bool, - /// Files that changed on disk while they hold unsaved edits, waiting on whether to reload. - pub reload_conflicts: Vec, /// Counts the recooks that read an open tab again; what is drawn from another tab's file, as a model is from its dictionary, is built again when it moves. pub recooked: u64, pub sim: sim::SimSession, - pub file_watcher: file_watcher::FileWatcher, pub drivers: drivers::Drivers, - pub ptfx_sinks: sinks::EditorSinks, pub audio: crate::audio::AudioOut, } @@ -343,22 +299,8 @@ impl AppState { crate::i18n::apply(prefs.language.as_deref()); let mut keys = KeysController::default(); keys.try_load_cached(&prefs); - let mut materials_palette = MaterialsPaletteController::default(); - let mut clip_regions = ClipRegionsController::default(); - let game_pack = GamePackController::aimed(gta_install_root_from_prefs(&prefs).as_deref()); - let mut shader_defs = ShaderDefsController::default(); - shader_defs.start_staged(); - if let Some(install_root) = gta_install_root_from_prefs(&prefs) { - if keys.has_keys() { - materials_palette.start_load(install_root.clone(), keys.provider()); - clip_regions.start_load( - install_root.clone(), - keys.provider(), - prefs.mount_options(), - None, - ); - } - } + let install_root = gta_install_root_from_prefs(&prefs); + let install = InstallReferenceData::from_install(install_root.as_deref(), &keys, &prefs); let known_game_paths: Vec<(Game, PathBuf)> = Game::all() .filter_map(|g| prefs.game_paths.get(g).cloned().map(|p| (g, p))) .collect(); @@ -374,6 +316,7 @@ impl AppState { if let Some(game) = prefs.active_game { crate::diagnostics::crash::note_edition(game.generation().edition_label()); } + let textures = TextureResolutionState::new(prefs.texture_cache_budget()); let mut state = Self { documents: Vec::new(), active_document: None, @@ -382,16 +325,8 @@ impl AppState { selection: Selection::default(), records_selected: Default::default(), presets: Default::default(), - texture_cache: TextureCache::new(prefs.texture_cache_budget()), - pinned_texture_docs: Default::default(), - auto_opened_texture_docs: Default::default(), - attached_texture_docs: Vec::new(), + textures, clothing: Clothing::default(), - attempted_texture_siblings: Default::default(), - attempted_shared_dictionaries: Default::default(), - attempted_texture_search_paths: Default::default(), - attempted_texture_project: Default::default(), - texture_report: TextureResolutionReport::default(), closed_documents: Vec::new(), prefs, project_path: None, @@ -400,79 +335,30 @@ impl AppState { world: Default::default(), front_door: Default::default(), loading: LoadingState::Idle, - load_receiver: None, - pending_loads: std::collections::VecDeque::new(), - batch_loading: false, - save_receiver: None, - show_error_dialog: false, - error_dialog_title: String::new(), - error_dialog_message: String::new(), - error_dialog_plain: None, + io_queue: DocumentIoQueue::default(), + error_dialog: ErrorDialog::default(), toasts: Toasts::default(), keys, - materials_palette, - clip_regions, - name_index: name_index::NameIndex::new(), - interiors: reference_names::InstallInteriors::default(), - game_tables: reference_names::InstallTables::default(), - search: search_session::SearchSession::default(), - search_query: SearchQuery::default(), - deep_find: vfs_session::VfsSession::default(), - file_index: Default::default(), + install, + find: SearchState::default(), navigation: navigation::Navigation::default(), tabs: tabs::Tabs::default(), - game_pack, - shader_defs, - expander: ExpansionWorker::default(), panels: Default::default(), plugins: Default::default(), preview_scene, cameras: Default::default(), - anim: AnimSession::default(), - anim_edits: or_anim::PoseEdits::new(), - anim_transport: or_transport::Transport::default(), + animation: AnimationState::default(), last_window_title: String::new(), - frame_stats: FrameStats::default(), - gpu_usage: Default::default(), - gpu_stages: Vec::new(), + perf: FrameTelemetry::default(), next_doc_id: AtomicU64::new(1), - known_archive_names: KnownArchiveNames::with_stock(), - discovery: game_discovery::DiscoveryWorker::spawn(known_game_paths), - extract_jobs: ExtractJobs::default(), - defrag: defrag_job::DefragJobs::default(), - convert: Default::default(), - dlc_pack: Default::default(), - mod_manager: Default::default(), - gltf: Default::default(), - dependencies: Default::default(), - compare: Default::default(), - texture_naming: Vec::new(), - texture_packs: Default::default(), - set_finding: Vec::new(), - clip_finding: None, - particle_model_finding: None, - map_search: Vec::new(), - neighbour_search: None, + bg: BackgroundControllers::spawn(known_game_paths), + gta6_finders: Gta6Finders::default(), jobs: jobs::JobLog::default(), - pending_delete: None, - retail_edit_session_allow: false, - pending_retail_edit: None, - refused_write: None, - pending_export_fixes: None, - drag_out_fixes: None, - pending_enhanced_open: None, - overlay_copy: overlay_copy::OverlayCopy::default(), - overlay_loader: overlay_loader::OverlayLoaderChecks::default(), - save_destination: None, - pending_close: None, + prompts: PendingPrompts::default(), should_exit: false, - reload_conflicts: Vec::new(), recooked: 0, sim: sim::SimSession::default(), - file_watcher: file_watcher::FileWatcher::new(), drivers, - collision_bvh: None, - ptfx_sinks: sinks::EditorSinks::new(), audio: crate::audio::AudioOut::default(), }; if let Some(root) = state @@ -566,13 +452,14 @@ impl AppState { } pub fn tick_frame_stats(&mut self) { - self.frame_stats.tick(); + self.perf.frame_stats.tick(); } /// Store the texture cache budget, save it, and evict down to it at once. pub fn set_texture_cache_budget_mib(&mut self, mib: u32) { self.prefs.texture_cache_mib = mib; - self.texture_cache + self.textures + .cache .set_budget(self.prefs.texture_cache_budget()); save_prefs(&self.prefs); } @@ -627,7 +514,7 @@ impl AppState { } pub fn tick_previews(&mut self) { - let changed = self.file_watcher.poll(); + let changed = self.io_queue.file_watcher.poll(); for path in changed { self.reload_ypt_from_disk(&path, false); } @@ -681,8 +568,8 @@ impl AppState { self.sim.manager.wall_time_seconds += dt; self.sim .manager - .set_collision_bvh(self.collision_bvh.clone()); - self.ptfx_sinks.install(&mut self.sim.manager); + .set_collision_bvh(self.sim.collision_bvh.clone()); + self.sim.sinks.install(&mut self.sim.manager); self.sim.manager.tick(dt); self.sim.last_sim_ms = start.elapsed().as_secs_f32() * 1000.0; } @@ -750,8 +637,7 @@ impl AppState { self.documents.remove(pos); self.selection.forget(id); self.navigation.forget(id); - self.texture_cache.forget_document(id); - self.forget_texture_resolution(id); + self.textures.clear_for_document(id); self.closed_documents.push(id); self.sim.forget_doc(id); @@ -793,14 +679,15 @@ impl AppState { doc.read_only = Some(rpf9_scan::READ_ONLY_BODY); } let kind = doc.kind(); - self.name_index.absorb(&doc.payload); + self.install.name_index.absorb(&doc.payload); if let Some((names, keys)) = ttpf_document::texture_naming_work(&self.documents, &doc.payload) { - (self.texture_naming).push(gta6_texture_naming::TextureNaming::start(names, keys)); + (self.gta6_finders.texture_naming) + .push(gta6_texture_naming::TextureNaming::start(names, keys)); } if matches!(kind, DocumentKind::Ypt) { - self.file_watcher.watch(path.clone()); + self.io_queue.file_watcher.watch(path.clone()); } // A dictionary opens on its first entry: the viewport draws an entry only while it is selected. let first_entry = selection_lookup::ydd_first_entry_hash(&doc.payload); diff --git a/src/state/mod_manager.rs b/src/state/mod_manager.rs index cbadcd9f0..ae63e2f09 100644 --- a/src/state/mod_manager.rs +++ b/src/state/mod_manager.rs @@ -64,7 +64,7 @@ impl AppState { /// when a mods folder of many packs stalls a frame. pub fn refresh_mods(&mut self) { let Some(root) = self.prefs.active_game_root().cloned() else { - self.mod_manager = ModManager::default(); + self.bg.mod_manager = ModManager::default(); return; }; let crypto = self.keys.provider(); @@ -72,21 +72,21 @@ impl AppState { let mut found = mods::scan_install(&root, &crypto, list.as_ref()); let saved = (self.prefs.mod_orders.get(&mods::install_key(&root))).map_or(&[][..], |o| o); mods::arrange(&mut found, saved); - self.mod_manager.resolution = mods::resolve(&found); - self.mod_manager.mods = found; - self.mod_manager.root = Some(root); + self.bg.mod_manager.resolution = mods::resolve(&found); + self.bg.mod_manager.mods = found; + self.bg.mod_manager.root = Some(root); } /// Move `name` one place up or down the load order, save the order for this install and resolve again. pub fn move_mod(&mut self, name: &str, up: bool) { - if !mods::nudge(&mut self.mod_manager.mods, name, up) { + if !mods::nudge(&mut self.bg.mod_manager.mods, name, up) { return; } - self.mod_manager.resolution = mods::resolve(&self.mod_manager.mods); - let Some(root) = &self.mod_manager.root else { + self.bg.mod_manager.resolution = mods::resolve(&self.bg.mod_manager.mods); + let Some(root) = &self.bg.mod_manager.root else { return; }; - let order = mods::order_of(&self.mod_manager.mods); + let order = mods::order_of(&self.bg.mod_manager.mods); self.prefs.mod_orders.insert(mods::install_key(root), order); save_prefs(&self.prefs); } @@ -96,11 +96,11 @@ impl AppState { /// ⚠ Asks the edit gate about the overlay side of the move, `mods/`, in both /// directions: the parked folder is the user's own and holds nothing the game reads. pub fn ask_toggle_mod(&mut self, name: &str) { - let Some(root) = self.mod_manager.root.clone() else { + let Some(root) = self.bg.mod_manager.root.clone() else { return; }; let Some(found) = - (self.mod_manager.mods.iter()).find(|m| m.name == name && m.place.is_ordered()) + (self.bg.mod_manager.mods.iter()).find(|m| m.name == name && m.place.is_ordered()) else { return; }; @@ -121,7 +121,7 @@ impl AppState { // ⚠ Only a shipped file asks, and `mods` holds none. GateOutcome::Refused | GateOutcome::Confirm(_) => return, } - self.mod_manager.pending_move = Some(PendingModMove { + self.bg.mod_manager.pending_move = Some(PendingModMove { name: name.to_string(), enable, from, @@ -132,10 +132,10 @@ impl AppState { /// The move the user was shown, done or dropped. pub fn answer_mod_move(&mut self, accept: bool) { - let Some(pending) = self.mod_manager.pending_move.take().filter(|_| accept) else { + let Some(pending) = self.bg.mod_manager.pending_move.take().filter(|_| accept) else { return; }; - let Some(root) = self.mod_manager.root.clone() else { + let Some(root) = self.bg.mod_manager.root.clone() else { return; }; match self.gate_permits(Some(&root.join(OVERLAY_DIR).join(&pending.name))) { diff --git a/src/state/move_network.rs b/src/state/move_network.rs index 0c70286b3..f24104679 100644 --- a/src/state/move_network.rs +++ b/src/state/move_network.rs @@ -32,14 +32,14 @@ mod tests { fn open(state: &mut AppState, path: PathBuf) -> DocumentId { state.load_file(path); let deadline = Instant::now() + Duration::from_secs(30); - while state.load_receiver.is_some() && Instant::now() < deadline { + while state.io_queue.load_receiver.is_some() && Instant::now() < deadline { state.poll_load_result(); std::thread::sleep(Duration::from_millis(5)); } assert!( matches!(state.loading, LoadingState::Idle), "the load did not finish: {}", - state.error_dialog_message + state.error_dialog.message ); state.active_document.expect("the .mrf opened") } diff --git a/src/state/navigation.rs b/src/state/navigation.rs index b16686ca9..05cdf2405 100644 --- a/src/state/navigation.rs +++ b/src/state/navigation.rs @@ -437,10 +437,10 @@ impl AppState { true } Resolved::Unloaded(node) => { - if !self.expander.is_in_flight(doc_id, node) { + if !self.bg.expander.is_in_flight(doc_id, node) { self.request_expand(doc_id, node); } - let expanding = self.expander.is_in_flight(doc_id, node); + let expanding = self.bg.expander.is_in_flight(doc_id, node); if !expanding { self.show_warning_toast(format!("{} could not be opened", place.label())); } diff --git a/src/state/os_drop.rs b/src/state/os_drop.rs index d2c0268ad..8acc6e6da 100644 --- a/src/state/os_drop.rs +++ b/src/state/os_drop.rs @@ -436,7 +436,7 @@ impl AppState { } GateOutcome::Refused => {} GateOutcome::Confirm(path) => { - self.pending_retail_edit = Some(PendingRetailEditPrompt { + self.prompts.retail_edit = Some(PendingRetailEditPrompt { action: PendingRetailEdit::ImportPaths { doc_id: doc, folder_id: folder, @@ -612,11 +612,12 @@ impl AppState { } let form = or_io::container::rpf::BodyForm::Decoded; let Some(fixes) = self + .prompts .drag_out_fixes .take() .or_else(|| self.export_fixes_for(&items, form)) else { - self.pending_export_fixes = Some(PendingExportFixes::DragOut); + self.prompts.export_fixes = Some(PendingExportFixes::DragOut); return Ok(Vec::new()); }; let mut tops: Vec = Vec::new(); diff --git a/src/state/overlay_copy.rs b/src/state/overlay_copy.rs index 9f199e2de..555244644 100644 --- a/src/state/overlay_copy.rs +++ b/src/state/overlay_copy.rs @@ -133,7 +133,7 @@ impl AppState { let Ok(meta) = std::fs::metadata(source) else { return false; }; - self.overlay_copy.offer = Some(OverlayCopyOffer { + self.bg.overlay_copy.offer = Some(OverlayCopyOffer { source: source.to_path_buf(), dest, bytes: meta.len(), @@ -144,13 +144,13 @@ impl AppState { /// Start the offered copy on a worker, or drop the offer. pub fn answer_overlay_copy(&mut self, accept: bool) { - let Some(offer) = self.overlay_copy.offer.take() else { + let Some(offer) = self.bg.overlay_copy.offer.take() else { return; }; if !accept { return; } - if let Some(running) = self.overlay_copy.running() { + if let Some(running) = self.bg.overlay_copy.running() { let busy = tr!( "Not copied: the overlay copy of `{source}` is still running", source = running.source.display() @@ -172,7 +172,7 @@ impl AppState { let (source, dest) = (offer.source.clone(), offer.dest.clone()); let replace = offer.replaces.is_some(); let tracking = self.base_tracking(); - self.overlay_copy.start(offer, move |cancel, progress| { + self.bg.overlay_copy.start(offer, move |cancel, progress| { // ⚠ Taken before the copy reads the original, so the record is of what the copy holds. let record = tracking.as_ref().map(|(records, crypto)| { (BaseRecord::of(&source, crypto), record_file(records, &dest)) @@ -185,7 +185,7 @@ impl AppState { /// Where a finished copy lands, each frame. pub fn poll_overlay_copy(&mut self) { - let Some(job) = &self.overlay_copy.running else { + let Some(job) = &self.bg.overlay_copy.running else { return; }; let result = match job.receiver.try_recv() { @@ -197,7 +197,7 @@ impl AppState { }; let (dest, cancelled) = (job.offer.dest.clone(), job.cancel.is_set()); let refreshed = job.offer.replaces.is_some(); - self.overlay_copy.running = None; + self.bg.overlay_copy.running = None; match result { Ok(()) if refreshed => self.refreshed_overlay_copy(&dest), Ok(()) => { @@ -325,12 +325,12 @@ mod tests { std::fs::write(&shipped, &bytes).expect("archive"); let mut state = AppState::new(); - state.retail_edit_session_allow = false; + state.prompts.retail_edit_session_allow = false; state.prefs.edit_mode = EditMode::Overlay; assert!(state.offer_overlay_copy(&shipped)); let dest = install.join("mods").join("update").join("update.rpf"); assert_eq!( - state.overlay_copy.offer, + state.bg.overlay_copy.offer, Some(OverlayCopyOffer { source: shipped.clone(), dest: dest.clone(), @@ -343,7 +343,7 @@ mod tests { state.answer_overlay_copy(true); let deadline = Instant::now() + Duration::from_secs(30); - while state.overlay_copy.running().is_some() { + while state.bg.overlay_copy.running().is_some() { state.poll_overlay_copy(); assert!(Instant::now() < deadline, "the copy never reported"); std::thread::sleep(Duration::from_millis(2)); diff --git a/src/state/overlay_loader.rs b/src/state/overlay_loader.rs index 47a2dbed4..366c1ee71 100644 --- a/src/state/overlay_loader.rs +++ b/src/state/overlay_loader.rs @@ -54,7 +54,7 @@ pub fn why_unread(profile: &dyn GameProfile, report: &OverlayLoaderReport) -> Op impl AppState { /// What the install at `root` needs for the game to read its overlay, read on first ask. pub fn overlay_loader(&mut self, root: &Path) -> Option<&Reading> { - (self.overlay_loader.readings) + (self.bg.overlay_loader.readings) .entry(root.to_path_buf()) .or_insert_with(|| read(root)) .as_ref() @@ -62,7 +62,7 @@ impl AppState { /// Look in `root`'s folder again, after the user has added or removed a file there. pub fn recheck_overlay_loader(&mut self, root: &Path) { - self.overlay_loader.readings.remove(root); + self.bg.overlay_loader.readings.remove(root); } /// Warn once per install that a write into its overlay will not be read by the game. @@ -74,6 +74,7 @@ impl AppState { return; }; let Some(reading) = self + .bg .overlay_loader .readings .entry(root) diff --git a/src/state/overlay_refresh.rs b/src/state/overlay_refresh.rs index 408b085c3..a5642093c 100644 --- a/src/state/overlay_refresh.rs +++ b/src/state/overlay_refresh.rs @@ -63,7 +63,7 @@ impl AppState { pub fn check_overlay_staleness(&mut self) { if !self.prefs.read_overlay_first { // Copies nothing reads hide nothing. - self.overlay_copy.stale.clear(); + self.bg.overlay_copy.stale.clear(); return; } let Some(root) = self.overlay_install_root() else { @@ -78,7 +78,7 @@ impl AppState { let _ = tx.send((root, found)); }); // A check still running is dropped: it holds the keys from before this one. - self.overlay_copy.checking = Some(rx); + self.bg.overlay_copy.checking = Some(rx); } /// Where a finished staleness check or weighing lands, each frame. @@ -88,26 +88,26 @@ impl AppState { } fn poll_overlay_staleness(&mut self) { - let Some(check) = &self.overlay_copy.checking else { + let Some(check) = &self.bg.overlay_copy.checking else { return; }; let (root, found) = match check.try_recv() { Ok(answer) => answer, Err(TryRecvError::Empty) => return, Err(TryRecvError::Disconnected) => { - self.overlay_copy.checking = None; + self.bg.overlay_copy.checking = None; return; } }; - self.overlay_copy.checking = None; + self.bg.overlay_copy.checking = None; if self.overlay_install_root().as_ref() != Some(&root) { return; } let news: Vec = (found.iter()) - .filter(|stale| self.overlay_copy.stale_copy(&stale.copy).is_none()) + .filter(|stale| self.bg.overlay_copy.stale_copy(&stale.copy).is_none()) .map(|stale| self.overlay_name(&stale.copy)) .collect(); - self.overlay_copy.stale = found; + self.bg.overlay_copy.stale = found; if news.is_empty() { return; } @@ -126,12 +126,12 @@ impl AppState { /// Work out what refreshing the overlay copy at `copy` from the patched archive would discard, then offer it. pub fn refresh_overlay_copy(&mut self, copy: &Path) { - let Some(stale) = self.overlay_copy.stale_copy(copy).cloned() else { + let Some(stale) = self.bg.overlay_copy.stale_copy(copy).cloned() else { return; }; - let busy = self.overlay_copy.running().is_some() - || self.overlay_copy.weighing.is_some() - || self.overlay_copy.offer.is_some(); + let busy = self.bg.overlay_copy.running().is_some() + || self.bg.overlay_copy.weighing.is_some() + || self.bg.overlay_copy.offer.is_some(); if busy { self.show_error_toast(tr!("An overlay copy is already under way")); return; @@ -174,7 +174,7 @@ impl AppState { .map_err(|e| e.to_string()); let _ = tx.send(plan); }); - self.overlay_copy.weighing = Some(Weighing { + self.bg.overlay_copy.weighing = Some(Weighing { stale, cancel, receiver: rx, @@ -182,7 +182,7 @@ impl AppState { } fn poll_overlay_weighing(&mut self) { - let Some(job) = &self.overlay_copy.weighing else { + let Some(job) = &self.bg.overlay_copy.weighing else { return; }; let result = match job.receiver.try_recv() { @@ -193,12 +193,12 @@ impl AppState { } }; let (stale, cancelled) = (job.stale.clone(), job.cancel.is_set()); - self.overlay_copy.weighing = None; + self.bg.overlay_copy.weighing = None; // A weighing asked to stop offers nothing, even where the worker finished first. match result { Ok(plan) if !cancelled => { let bytes = std::fs::metadata(&stale.base).map_or(0, |meta| meta.len()); - self.overlay_copy.offer = Some(OverlayCopyOffer { + self.bg.overlay_copy.offer = Some(OverlayCopyOffer { source: stale.base, dest: stale.copy, bytes, @@ -256,9 +256,12 @@ impl AppState { /// The copy at `copy` was replaced: forget what the session read from it, and what was indexed of the old one. pub(super) fn refreshed_overlay_copy(&mut self, copy: &Path) { - self.overlay_copy.stale.retain(|stale| stale.copy != copy); + self.bg + .overlay_copy + .stale + .retain(|stale| stale.copy != copy); // ⚠ Every offset the session read from this file is stale now. - self.expander.files_replaced(); + self.bg.expander.files_replaced(); let mut reopen = Vec::new(); for doc in self.documents.iter_mut() { let DocPayload::Rpf(rpf) = &mut doc.payload else { @@ -276,7 +279,7 @@ impl AppState { for (doc_id, root) in reopen { self.request_expand(doc_id, root); } - self.name_index.stop_bg_scan(); + self.install.name_index.stop_bg_scan(); self.maybe_start_name_scan(); let said = tr!( "Refreshed {copy} from the patched archive", @@ -339,7 +342,7 @@ mod tests { let base = root.join("update").join("update.rpf"); std::fs::write(&base, archive(SHIPPED)).expect("the shipped archive"); let mut state = AppState::new(); - state.retail_edit_session_allow = false; + state.prompts.retail_edit_session_allow = false; state.prefs.edit_mode = EditMode::Overlay; state .prefs @@ -359,9 +362,9 @@ mod tests { /// Poll until nothing the overlay is doing is still running. fn settle(state: &mut AppState) { let deadline = Instant::now() + Duration::from_secs(60); - while state.overlay_copy.running().is_some() - || state.overlay_copy.weighing.is_some() - || state.overlay_copy.checking.is_some() + while state.bg.overlay_copy.running().is_some() + || state.bg.overlay_copy.weighing.is_some() + || state.bg.overlay_copy.checking.is_some() { state.poll_overlay_copy(); state.poll_overlay_refresh(); @@ -440,7 +443,7 @@ mod tests { scene.check(); scene.refresh(); - let offer = scene.state.overlay_copy.offer.clone().expect("an offer"); + let offer = scene.state.bg.overlay_copy.offer.clone().expect("an offer"); let plan = offer.replaces.expect("a refresh says what it replaces"); assert_eq!( plan.yours, @@ -460,10 +463,10 @@ mod tests { std::fs::read(&scene.base).expect("the patched archive"), "the refresh is the patched archive" ); - assert!(scene.state.overlay_copy.stale.is_empty()); + assert!(scene.state.bg.overlay_copy.stale.is_empty()); scene.check(); assert!( - scene.state.overlay_copy.stale.is_empty(), + scene.state.bg.overlay_copy.stale.is_empty(), "the refreshed copy is of the patched archive, so it is fresh" ); } @@ -482,7 +485,11 @@ mod tests { settle(&mut scene.state); assert_eq!(std::fs::read(&scene.copy).expect("the copy"), edited); - assert_eq!(scene.state.overlay_copy.stale.len(), 1, "still out of date"); + assert_eq!( + scene.state.bg.overlay_copy.stale.len(), + 1, + "still out of date" + ); } #[test] @@ -511,7 +518,7 @@ mod tests { ); settle(&mut scene.state); - assert!(scene.state.overlay_copy.offer.is_none()); + assert!(scene.state.bg.overlay_copy.offer.is_none()); assert!(listed(&scene.state).is_none()); assert_eq!(std::fs::read(&scene.copy).expect("the copy"), edited); let ended = (scene.state.jobs.ended().iter()) @@ -519,7 +526,11 @@ mod tests { .expect("the stop is recorded"); assert_eq!(ended.outcome, Outcome::Stopped(Then::Nothing)); assert_eq!(ended.said, "Nothing was refreshed"); - assert_eq!(scene.state.overlay_copy.stale.len(), 1, "still out of date"); + assert_eq!( + scene.state.bg.overlay_copy.stale.len(), + 1, + "still out of date" + ); } #[test] @@ -536,7 +547,7 @@ mod tests { rpf.session.mark_archive_dirty(node); scene.refresh(); - assert!(scene.state.overlay_copy.offer.is_none()); + assert!(scene.state.bg.overlay_copy.offer.is_none()); assert!( (scene.state.toasts.iter()).any(|t| t.message.contains("Save or discard")), "the refusal says what to do first" diff --git a/src/state/plugins/the_cloth_painter_installs_as_a_plugin.rs b/src/state/plugins/the_cloth_painter_installs_as_a_plugin.rs index e3ab996b0..65dceb192 100644 --- a/src/state/plugins/the_cloth_painter_installs_as_a_plugin.rs +++ b/src/state/plugins/the_cloth_painter_installs_as_a_plugin.rs @@ -123,7 +123,7 @@ fn the_painter_is_refused_its_write_while_the_editor_is_read_only() { .prefs .game_paths .set(or_title::Game::GtaVLegacy, Some(dir.path().to_path_buf())); - state.retail_edit_session_allow = false; + state.prompts.retail_edit_session_allow = false; state.prefs.edit_mode = EditMode::ReadOnly; state.load_plugin_surfaces(); diff --git a/src/state/project_io.rs b/src/state/project_io.rs index 0832c9efa..b6f32cc80 100644 --- a/src/state/project_io.rs +++ b/src/state/project_io.rs @@ -118,7 +118,7 @@ impl AppState { for id in self.every_document_but_the_install() { self.drop_document(id); } - self.texture_cache.clear(); + self.textures.cache.clear(); } /// Leave the project and show the start page, with the install still mounted; a project with a change nothing wrote down asks first. diff --git a/src/state/project_shadow.rs b/src/state/project_shadow.rs index 23ad92058..cba4a8f68 100644 --- a/src/state/project_shadow.rs +++ b/src/state/project_shadow.rs @@ -27,7 +27,7 @@ impl AppState { /// built once from the install, so a project whose copy is only consulted /// on the next launch is one a user concludes does nothing. pub(super) fn reread_through_project(&mut self) { - self.attempted_texture_project.clear(); + self.textures.attempted_project.clear(); if !self.keys.has_keys() { return; } @@ -35,7 +35,7 @@ impl AppState { return; }; let shadow = self.project_shadow_root(); - self.clip_regions.start_load( + self.install.clip_regions.start_load( install_root, self.keys.provider(), self.prefs.mount_options(), @@ -73,7 +73,7 @@ impl AppState { let Some((doc_id, stem)) = stem_missing_textures(self) else { return false; }; - if !self.attempted_texture_project.insert(doc_id) { + if !self.textures.attempted_project.insert(doc_id) { return false; } for path in self.project_texture_candidates(&stem) { diff --git a/src/state/reload_open_file.rs b/src/state/reload_open_file.rs index d1b7351bb..080445d2b 100644 --- a/src/state/reload_open_file.rs +++ b/src/state/reload_open_file.rs @@ -39,8 +39,8 @@ impl AppState { let mut reloaded = 0; for (id, kind, dirty) in open { if dirty && !over_edits(id) { - if !self.reload_conflicts.iter().any(|p| p == path) { - self.reload_conflicts.push(path.to_path_buf()); + if !self.prompts.reload_conflicts.iter().any(|p| p == path) { + self.prompts.reload_conflicts.push(path.to_path_buf()); } continue; } @@ -48,7 +48,7 @@ impl AppState { if let Some(doc) = self.document_mut(id) { doc.reloaded(payload, resource); } - self.texture_cache.forget_document(id); + self.textures.cache.forget_document(id); reloaded += 1; } if reloaded > 0 { @@ -68,8 +68,8 @@ impl AppState { return; }; if dirty && !over_edits { - if !self.reload_conflicts.iter().any(|p| p == path) { - self.reload_conflicts.push(path.to_path_buf()); + if !self.prompts.reload_conflicts.iter().any(|p| p == path) { + self.prompts.reload_conflicts.push(path.to_path_buf()); } return; } diff --git a/src/state/rpf/rpf9_scan/extracting_a_gta_vi_body.rs b/src/state/rpf/rpf9_scan/extracting_a_gta_vi_body.rs index 8b7464ce8..63ad8e61e 100644 --- a/src/state/rpf/rpf9_scan/extracting_a_gta_vi_body.rs +++ b/src/state/rpf/rpf9_scan/extracting_a_gta_vi_body.rs @@ -21,7 +21,7 @@ fn archive() -> Vec { /// Wait for the extraction in flight to end. fn finished(state: &mut AppState) { let deadline = Instant::now() + Duration::from_secs(30); - while state.extract_jobs.is_running() { + while state.bg.extract_jobs.is_running() { state.poll_extract_job(); assert!(Instant::now() < deadline, "the extraction never ended"); std::thread::sleep(Duration::from_millis(5)); @@ -37,7 +37,7 @@ fn save_as_refuses_a_scanned_body_whose_edits_no_writer_takes_rather_than_drop_t settle(&mut state); let body = (state.active_document) .filter(|&d| d != doc) - .unwrap_or_else(|| panic!("the body: {}", state.error_dialog_message)); + .unwrap_or_else(|| panic!("the body: {}", state.error_dialog.message)); // An edit of a view whose body has no writer marks the document and leaves its bytes. state.document_mut(body).expect("open").mark_edited(); state.toasts.clear(); diff --git a/src/state/rpf/rpf9_scan/mod.rs b/src/state/rpf/rpf9_scan/mod.rs index 180d1fddc..4a294431a 100644 --- a/src/state/rpf/rpf9_scan/mod.rs +++ b/src/state/rpf/rpf9_scan/mod.rs @@ -814,7 +814,7 @@ impl crate::state::AppState { items: Vec, on_clash: OnClash, ) -> bool { - if let Some(what) = self.extract_jobs.running_noun() { + if let Some(what) = self.bg.extract_jobs.running_noun() { self.show_error_toast(tr!("{what} is already running", what = what)); return false; } @@ -825,7 +825,7 @@ impl crate::state::AppState { return false; } let worker_dest = dest.clone(); - self.extract_jobs.start( + self.bg.extract_jobs.start( JobKind::Extraction, label, dest, diff --git a/src/state/rpf/rpf_archive_open/tree_open/bind/tests.rs b/src/state/rpf/rpf_archive_open/tree_open/bind/tests.rs index 31a91466f..b41796c33 100644 --- a/src/state/rpf/rpf_archive_open/tree_open/bind/tests.rs +++ b/src/state/rpf/rpf_archive_open/tree_open/bind/tests.rs @@ -102,7 +102,7 @@ fn row(state: &AppState, inner: &str) -> RpfNodeId { fn settle(state: &mut AppState) { let deadline = Instant::now() + Duration::from_secs(30); - while state.load_receiver.is_some() || !state.pending_loads.is_empty() { + while state.io_queue.load_receiver.is_some() || !state.io_queue.pending_loads.is_empty() { state.poll_load_result(); assert!(Instant::now() < deadline, "the load never ended"); std::thread::sleep(Duration::from_millis(5)); @@ -138,7 +138,7 @@ fn opened(state: &mut AppState, node: RpfNodeId) -> DocumentId { (state.documents.iter()) .find(|d| d.path.as_deref() == Some(path.as_path())) .map(|d| d.id) - .unwrap_or_else(|| panic!("row {node} opened: {}", state.error_dialog_message)) + .unwrap_or_else(|| panic!("row {node} opened: {}", state.error_dialog.message)) } /// Poll until a save says how it ended. diff --git a/src/state/rpf/rpf_archive_open/tree_open/names_tests.rs b/src/state/rpf/rpf_archive_open/tree_open/names_tests.rs index 5ae38c1d6..d4478c1f5 100644 --- a/src/state/rpf/rpf_archive_open/tree_open/names_tests.rs +++ b/src/state/rpf/rpf_archive_open/tree_open/names_tests.rs @@ -38,7 +38,7 @@ fn resource(name: &str) -> (String, Rpf9NewBody) { fn settle(state: &mut AppState) { let deadline = Instant::now() + Duration::from_secs(30); - while state.load_receiver.is_some() || !state.pending_loads.is_empty() { + while state.io_queue.load_receiver.is_some() || !state.io_queue.pending_loads.is_empty() { state.poll_load_result(); assert!(Instant::now() < deadline, "the load never ended"); std::thread::sleep(Duration::from_millis(5)); diff --git a/src/state/rpf/rpf_archive_open/tree_verbs/adopt/tests.rs b/src/state/rpf/rpf_archive_open/tree_verbs/adopt/tests.rs index 9bedcc87c..44b21857a 100644 --- a/src/state/rpf/rpf_archive_open/tree_verbs/adopt/tests.rs +++ b/src/state/rpf/rpf_archive_open/tree_verbs/adopt/tests.rs @@ -110,7 +110,7 @@ fn opened(state: &mut AppState, node: RpfNodeId) -> DocumentId { name(state, &path, DOC, node); state.load_file(path.clone()); let deadline = Instant::now() + Duration::from_secs(30); - while state.load_receiver.is_some() || !state.pending_loads.is_empty() { + while state.io_queue.load_receiver.is_some() || !state.io_queue.pending_loads.is_empty() { state.poll_load_result(); assert!(Instant::now() < deadline, "the load never ended"); std::thread::sleep(Duration::from_millis(5)); @@ -118,7 +118,7 @@ fn opened(state: &mut AppState, node: RpfNodeId) -> DocumentId { (state.documents.iter()) .find(|d| d.path.as_deref() == Some(path.as_path())) .map(|d| d.id) - .unwrap_or_else(|| panic!("row {node} opened: {}", state.error_dialog_message)) + .unwrap_or_else(|| panic!("row {node} opened: {}", state.error_dialog.message)) } /// Whether a save has said how it ended. diff --git a/src/state/rpf/rpf_archive_open/tree_verbs/headerless_tests/saves_per_kind/mod.rs b/src/state/rpf/rpf_archive_open/tree_verbs/headerless_tests/saves_per_kind/mod.rs index f82387871..d7b022eb8 100644 --- a/src/state/rpf/rpf_archive_open/tree_verbs/headerless_tests/saves_per_kind/mod.rs +++ b/src/state/rpf/rpf_archive_open/tree_verbs/headerless_tests/saves_per_kind/mod.rs @@ -396,7 +396,7 @@ fn waited(state: &mut AppState, poll: fn(&mut AppState), ended: fn(&AppState) -> } fn loaded(state: &AppState) -> bool { - state.load_receiver.is_none() && state.pending_loads.is_empty() + state.io_queue.load_receiver.is_none() && state.io_queue.pending_loads.is_empty() } fn said_how_it_ended(state: &AppState) -> bool { diff --git a/src/state/rpf/rpf_expansion.rs b/src/state/rpf/rpf_expansion.rs index a269a4d78..34cf52de6 100644 --- a/src/state/rpf/rpf_expansion.rs +++ b/src/state/rpf/rpf_expansion.rs @@ -2,14 +2,14 @@ use crate::state::*; impl AppState { pub fn request_expand(&mut self, doc_id: DocumentId, node_id: RpfNodeId) { - if self.expander.is_in_flight(doc_id, node_id) { + if self.bg.expander.is_in_flight(doc_id, node_id) { return; } let request = match self.build_expansion_request(doc_id, node_id) { Some(r) => r, None => return, }; - self.expander.submit(request); + self.bg.expander.submit(request); } /// Open an archive row the tree has not expanded, as expanding it does, so what is added to it reaches it. @@ -84,11 +84,11 @@ impl AppState { } pub fn poll_expansions(&mut self) { - let (results, stale) = self.expander.drain(); + let (results, stale) = self.bg.expander.drain(); // ⚠ Listed from a file a save or a defragment has since replaced, a // row would read the new file at the old offsets. for (doc_id, node_id) in stale { - self.expander.finish(doc_id, node_id); + self.bg.expander.finish(doc_id, node_id); self.request_expand(doc_id, node_id); } for result in results { @@ -99,7 +99,7 @@ impl AppState { items, } => { self.apply_disk_scan(doc_id, node_id, items); - self.expander.finish(doc_id, node_id); + self.bg.expander.finish(doc_id, node_id); } ExpansionResult::Archive { doc_id, @@ -121,7 +121,7 @@ impl AppState { self.mark_archive_open_failed(doc_id, node_id, error); } } - self.expander.finish(doc_id, node_id); + self.bg.expander.finish(doc_id, node_id); } ExpansionResult::Failure { doc_id, @@ -130,7 +130,7 @@ impl AppState { } => { tracing::warn!(%doc_id, %node_id, error = %error, "Expansion failed"); self.show_error_toast(tr!("Tree scan failed: {error}", error = error)); - self.expander.finish(doc_id, node_id); + self.bg.expander.finish(doc_id, node_id); } } } @@ -199,7 +199,7 @@ impl AppState { or_io::container::TocDecryptOutcome::Nominal => None, or_io::container::TocDecryptOutcome::RecoveredNg { ng_key_index } => { Some(format_recovery_hint( - &self.known_archive_names, + &self.install.known_archive_names, self.keys.keys().as_ref(), ng_key_index, archive_size_for_hint, @@ -207,7 +207,7 @@ impl AppState { } }; if let Some(name) = &archive_filename { - self.known_archive_names.insert(name.clone()); + self.install.known_archive_names.insert(name.clone()); } if let Some(hint) = &recovery_hint { tracing::info!( @@ -293,7 +293,7 @@ impl AppState { ) -> Result<(), String> { if let Some(path) = self .affected_disk_path(parent_doc_id, entry_id) - .filter(|p| self.defrag.holds(p)) + .filter(|p| self.bg.defrag.holds(p)) { return Err(tr!( "`{path}` is being defragmented; save once that is done", diff --git a/src/state/rpf/rpf_moves.rs b/src/state/rpf/rpf_moves.rs index ff07ea7e8..9c0cffe2e 100644 --- a/src/state/rpf/rpf_moves.rs +++ b/src/state/rpf/rpf_moves.rs @@ -35,7 +35,7 @@ impl AppState { } } if let Some(target_path) = ask { - self.pending_retail_edit = Some(PendingRetailEditPrompt { + self.prompts.retail_edit = Some(PendingRetailEditPrompt { action: PendingRetailEdit::MoveNode { doc_id: doc, node_ids: rows, diff --git a/src/state/rpf/rpf_tree.rs b/src/state/rpf/rpf_tree.rs index 392cc01a6..d22090558 100644 --- a/src/state/rpf/rpf_tree.rs +++ b/src/state/rpf/rpf_tree.rs @@ -448,9 +448,9 @@ impl AppState { return; } self.prefs.edit_mode = mode; - self.retail_edit_session_allow = false; - self.pending_retail_edit = None; - self.refused_write = None; + self.prompts.retail_edit_session_allow = false; + self.prompts.retail_edit = None; + self.prompts.refused_write = None; save_prefs(&self.prefs); } @@ -489,7 +489,7 @@ impl AppState { path = path.display(), semantics = mode.semantics() )) - } else if self.retail_edit_session_allow { + } else if self.prompts.retail_edit_session_allow { RetailGuard::Allowed } else { RetailGuard::NeedsConfirmation(path.to_path_buf()) @@ -518,7 +518,7 @@ impl AppState { /// Write paths call this rather than matching on [`RetailGuard`] themselves, /// so every refusal is toasted one way and offers to change the mode. pub(crate) fn gate_permits(&mut self, target: Option<&Path>) -> GateOutcome { - if let Some(path) = target.filter(|p| self.defrag.holds(p)) { + if let Some(path) = target.filter(|p| self.bg.defrag.holds(p)) { self.show_error_toast(tr!( "`{path}` is being defragmented; try again once that is done", path = path.display() @@ -541,7 +541,7 @@ impl AppState { .filter(|_| self.prefs.edit_mode.permits_overlay()) .is_some_and(|path| self.offer_overlay_copy(path)); if !offered { - self.refused_write = target.map(Path::to_path_buf); + self.prompts.refused_write = target.map(Path::to_path_buf); } GateOutcome::Refused } @@ -560,7 +560,7 @@ impl AppState { GateOutcome::Proceed => Ok(()), GateOutcome::Refused => Err(retail_pending_message()), GateOutcome::Confirm(target_path) => { - self.pending_retail_edit = Some(PendingRetailEditPrompt { + self.prompts.retail_edit = Some(PendingRetailEditPrompt { action, target_path, verb, @@ -590,7 +590,7 @@ impl AppState { } pub fn apply_pending_retail_edit(&mut self, decision: RetailEditDecision) { - let prompt = match self.pending_retail_edit.take() { + let prompt = match self.prompts.retail_edit.take() { Some(p) => p, None => return, }; @@ -600,7 +600,7 @@ impl AppState { return; } RetailEditDecision::YesSession => { - self.retail_edit_session_allow = true; + self.prompts.retail_edit_session_allow = true; } } match prompt.action { diff --git a/src/state/save_destination.rs b/src/state/save_destination.rs index b718927df..01aa7ba11 100644 --- a/src/state/save_destination.rs +++ b/src/state/save_destination.rs @@ -83,7 +83,7 @@ impl AppState { .unwrap_or_default(); let archive = self.holder_of(binding).map(|h| h.path().to_path_buf()); let overlay = archive.as_deref().and_then(|p| self.overlay_for(p)); - self.save_destination = Some(SaveDestinationChoice { + self.prompts.save_destination = Some(SaveDestinationChoice { doc_id, name, archive, @@ -93,12 +93,12 @@ impl AppState { } pub fn cancel_save_destination(&mut self) { - self.save_destination = None; + self.prompts.save_destination = None; } /// Answer the open choice with `dest`. pub fn choose_save_destination(&mut self, dest: SaveDestination) { - if let Some(choice) = self.save_destination.take() { + if let Some(choice) = self.prompts.save_destination.take() { self.save_entry_to(choice.doc_id, dest); } } @@ -125,7 +125,7 @@ impl AppState { match self.gate_permits(target.as_deref()) { GateOutcome::Refused => return, GateOutcome::Confirm(target_path) => { - self.pending_retail_edit = Some(PendingRetailEditPrompt { + self.prompts.retail_edit = Some(PendingRetailEditPrompt { action: PendingRetailEdit::SaveEntry { doc_id, dest }, target_path, verb: tr!("save to"), @@ -222,7 +222,7 @@ impl AppState { Some(true) => None, Some(false) => Some(original), None => { - self.pending_export_fixes = + self.prompts.export_fixes = Some(PendingExportFixes::SaveEntry { doc_id, path }); return Ok(None); } @@ -304,7 +304,7 @@ impl AppState { let (bytes, _) = self.archive_bytes(parent, archive_id, Some(&dest))?; write_into_place(&dest, &bytes)?; self.note_overlay_base(&base, &dest); - self.expander.files_replaced(); + self.bg.expander.files_replaced(); self.file_replaced(&dest); if let Some(doc) = self.document_mut(parent) { if let DocPayload::Rpf(rpf) = &mut doc.payload { diff --git a/src/state/search_session.rs b/src/state/search_session.rs index 58aebb16f..4c6d63167 100644 --- a/src/state/search_session.rs +++ b/src/state/search_session.rs @@ -281,12 +281,12 @@ pub fn hit_path(hit: &ContentHit) -> String { impl super::AppState { /// Go to the hits at `rows` in the install they were found in, then do what `then` says. pub fn go_to_search_hits(&mut self, rows: &[usize], then: Arrival) { - let Some(root) = self.search.root.clone() else { + let Some(root) = self.find.session.root.clone() else { return; }; let inners = rows .iter() - .filter_map(|&row| self.search.hits.get(row)) + .filter_map(|&row| self.find.session.hits.get(row)) .map(hit_path) .collect(); self.walk_to(&root, inners, then); @@ -344,8 +344,11 @@ impl super::AppState { return; } } - match std::fs::write(path, self.search.export()) { - Ok(()) => self.show_toast(tr!("Wrote {count} results", count = self.search.hits.len())), + match std::fs::write(path, self.find.session.export()) { + Ok(()) => self.show_toast(tr!( + "Wrote {count} results", + count = self.find.session.hits.len() + )), Err(e) => self.show_error_toast(tr!("Export failed: {e}", e = e)), } } diff --git a/src/state/sim.rs b/src/state/sim.rs index 6610fda6a..676d8c507 100644 --- a/src/state/sim.rs +++ b/src/state/sim.rs @@ -70,6 +70,8 @@ pub struct SimSession { pub last_sim_ms: f32, pub pinned_effects: Vec, pub pin_offsets: HashMap, + pub collision_bvh: Option>, + pub sinks: super::sinks::EditorSinks, } impl Default for SimSession { @@ -83,6 +85,8 @@ impl Default for SimSession { last_sim_ms: 0.0, pinned_effects: Vec::new(), pin_offsets: HashMap::new(), + collision_bvh: None, + sinks: super::sinks::EditorSinks::new(), } } } diff --git a/src/state/tabs.rs b/src/state/tabs.rs index ff5fb14dc..f2fc5c562 100644 --- a/src/state/tabs.rs +++ b/src/state/tabs.rs @@ -81,7 +81,7 @@ pub(super) fn entry_display_path(parent_path: Option, child_path: &str) impl AppState { /// Whether `doc` has a tab: every document but a dictionary the app opened from an archive for itself. pub fn has_tab(&self, doc: &Document) -> bool { - doc.rpf_entry_binding.is_none() || !self.auto_opened_texture_docs.contains(&doc.id) + doc.rpf_entry_binding.is_none() || !self.textures.auto_opened_docs.contains(&doc.id) } /// The documents with a tab, in the strip's order. @@ -167,9 +167,14 @@ impl AppState { Some(Some(id)) if self.is_preview(id) => self.close_document(id), // ⚠ Still on its way, it has no document to close: one waiting never starts, and the one loading is dropped when it arrives. Some(None) => { - self.pending_loads + self.io_queue + .pending_loads .retain(|waiting| Some(waiting) != old.as_ref()); - let loading = self.load_receiver.as_ref().map(|(loading, _)| loading); + let loading = self + .io_queue + .load_receiver + .as_ref() + .map(|(loading, _)| loading); if loading == old.as_ref() { self.tabs.scan_abandoned = old; } diff --git a/src/state/tests/a_bones_numbers_can_be_edited.rs b/src/state/tests/a_bones_numbers_can_be_edited.rs index 1465a68d4..1a95ed6ff 100644 --- a/src/state/tests/a_bones_numbers_can_be_edited.rs +++ b/src/state/tests/a_bones_numbers_can_be_edited.rs @@ -652,10 +652,13 @@ fn a_rotation_edited_in_a_bone_poses_the_previews_skeleton_again() { state.tick_animation(); let epoch = state.skeleton_epoch(); assert!( - !state.anim.needs_rebuild(&state.preview_scene, epoch), + !state + .animation + .session + .needs_rebuild(&state.preview_scene, epoch), "{target}: the session is built again with nothing changed" ); - let child = state.anim.world_matrices[1].w_axis; + let child = state.animation.session.world_matrices[1].w_axis; assert_eq!( (child.x, child.y), (0.0, 2.0), @@ -670,11 +673,18 @@ fn a_rotation_edited_in_a_bone_poses_the_previews_skeleton_again() { .expect("a rotation is edited"); let epoch = state.skeleton_epoch(); assert!( - state.anim.needs_rebuild(&state.preview_scene, epoch), + state + .animation + .session + .needs_rebuild(&state.preview_scene, epoch), "{target}: the edit asks for a new session" ); state.tick_animation(); - let skeleton = state.anim.skeleton().expect("a skeleton is bound"); + let skeleton = state + .animation + .session + .skeleton() + .expect("a skeleton is bound"); let turned = skeleton.bones[0].bind_rotation; let quarter = std::f32::consts::FRAC_1_SQRT_2; assert!( @@ -685,7 +695,7 @@ fn a_rotation_edited_in_a_bone_poses_the_previews_skeleton_again() { (turned.z - quarter).abs() < 1e-5 && (turned.w - quarter).abs() < 1e-5, "{target}: the preview poses the rotation as {turned:?}" ); - let child = state.anim.world_matrices[1].w_axis; + let child = state.animation.session.world_matrices[1].w_axis; assert!( (child.x + 1.0).abs() < 1e-5 && (child.y - 1.0).abs() < 1e-5, "{target}: the child is posed at ({}, {})", diff --git a/src/state/tests/a_drag_copies_and_a_change_of_nothing_does_nothing.rs b/src/state/tests/a_drag_copies_and_a_change_of_nothing_does_nothing.rs index 850b22a29..196a36176 100644 --- a/src/state/tests/a_drag_copies_and_a_change_of_nothing_does_nothing.rs +++ b/src/state/tests/a_drag_copies_and_a_change_of_nothing_does_nothing.rs @@ -236,7 +236,7 @@ fn a_move_or_a_rename_that_changes_nothing_asks_the_edit_gate_nothing_and_writes steps(&state, tree), std::fs::read(dir.path().join("a.rpf")).expect("the archive"), ); - state.retail_edit_session_allow = false; + state.prompts.retail_edit_session_allow = false; for mode in [EditMode::ReadOnly, EditMode::Everything] { state.prefs.edit_mode = mode; @@ -256,11 +256,11 @@ fn a_move_or_a_rename_that_changes_nothing_asks_the_edit_gate_nothing_and_writes "a rename of an archive on disk to its own name, in {mode:?}" ); assert!( - state.pending_retail_edit.is_none(), + state.prompts.retail_edit.is_none(), "the gate was asked in {mode:?}" ); assert!( - state.refused_write.is_none(), + state.prompts.refused_write.is_none(), "a write was refused in {mode:?}" ); } @@ -415,9 +415,9 @@ fn a_copys_staged_files_are_gone_once_its_gate_question_is_answered() { state.prefs.edit_mode = EditMode::Everything; for decision in [RetailEditDecision::No, RetailEditDecision::YesSession] { - state.retail_edit_session_allow = false; + state.prompts.retail_edit_session_allow = false; assert_eq!(state.rpf_copy_nodes(tree, &rows, b_row), Ok(())); - let staged = match state.pending_retail_edit.as_ref().map(|p| &p.action) { + let staged = match state.prompts.retail_edit.as_ref().map(|p| &p.action) { Some(crate::state::PendingRetailEdit::ImportPaths { staged: Some(staged), .. @@ -470,7 +470,7 @@ fn a_copy_the_gate_refuses_leaves_no_staged_file() { assert_eq!(state.rpf_copy_nodes(tree, &rows, b_row), Ok(())); assert!( - state.pending_retail_edit.is_none(), + state.prompts.retail_edit.is_none(), "a refusal asks nothing" ); assert_eq!( @@ -499,7 +499,7 @@ fn a_copy_that_asks_while_another_question_waits_takes_the_staged_files_of_the_o let two = node_at(&mut state, tree, "a.rpf/asked_two.txt"); let b_row = node_at(&mut state, tree, "b.rpf"); state.prefs.edit_mode = EditMode::Everything; - state.retail_edit_session_allow = false; + state.prompts.retail_edit_session_allow = false; let staged = || { ( staged_copies("asked_one.txt"), @@ -509,7 +509,7 @@ fn a_copy_that_asks_while_another_question_waits_takes_the_staged_files_of_the_o let before = staged(); assert_eq!(state.rpf_copy_nodes(tree, &[one], b_row), Ok(())); - assert!(state.pending_retail_edit.is_some(), "the gate did not ask"); + assert!(state.prompts.retail_edit.is_some(), "the gate did not ask"); assert_eq!( staged(), (before.0 + 1, before.1), diff --git a/src/state/tests/a_model_is_drawn_with_its_own_textures.rs b/src/state/tests/a_model_is_drawn_with_its_own_textures.rs index 2eb1cbdf8..c948bf07d 100644 --- a/src/state/tests/a_model_is_drawn_with_its_own_textures.rs +++ b/src/state/tests/a_model_is_drawn_with_its_own_textures.rs @@ -106,7 +106,7 @@ fn a_vehicle_opens_the_dictionaries_every_vehicle_shares_only_while_a_name_is_st .map(|n| (None, (*n).to_string())) .collect::>() }; - f.state.texture_report = report(&f.state, None, wanted(&["generic", "worn"]), 1); + f.state.textures.report = report(&f.state, None, wanted(&["generic", "worn"]), 1); assert_eq!(f.drawn_with("generic"), None); assert!( @@ -120,13 +120,13 @@ fn a_vehicle_opens_the_dictionaries_every_vehicle_shares_only_while_a_name_is_st assert_eq!(f.dictionaries(), 2); // `worn` is still missing, so the next one is asked for, once - f.state.texture_report = report(&f.state, None, wanted(&["worn"]), 2); + f.state.textures.report = report(&f.state, None, wanted(&["worn"]), 2); assert!( f.state.try_auto_open_shared_dictionary(), "vehshare_worn.ytd opens" ); assert!(f.drawn_with("worn").is_some()); - f.state.texture_report = report(&f.state, None, wanted(&["nothing"]), 3); + f.state.textures.report = report(&f.state, None, wanted(&["nothing"]), 3); assert!( !f.state.try_auto_open_shared_dictionary(), "no one is asked twice, and the rest are not in the folder" diff --git a/src/state/tests/a_plugin_asks_before_it_runs.rs b/src/state/tests/a_plugin_asks_before_it_runs.rs index 64069d831..db7a12139 100644 --- a/src/state/tests/a_plugin_asks_before_it_runs.rs +++ b/src/state/tests/a_plugin_asks_before_it_runs.rs @@ -273,7 +273,7 @@ fn a_plugin_replacing_a_file_is_refused_in_read_only_mode_and_accepted_in_overla .game_paths .set(or_title::Game::GtaVLegacy, Some(root.path().to_path_buf())); state.prefs.edit_mode = EditMode::ReadOnly; - state.retail_edit_session_allow = false; + state.prompts.retail_edit_session_allow = false; state.request_plugin_run("bytes-gated"); state.answer_plugin_consent(true); diff --git a/src/state/tests/a_recook_reloads_what_is_open.rs b/src/state/tests/a_recook_reloads_what_is_open.rs index b4f94cff6..bbdc32b8c 100644 --- a/src/state/tests/a_recook_reloads_what_is_open.rs +++ b/src/state/tests/a_recook_reloads_what_is_open.rs @@ -115,9 +115,9 @@ fn a_tab_with_unsaved_edits_waits_for_an_answer_and_is_then_read_again() { c.save_an_image(200); until(&mut c.state, "the question", |s| { - !s.reload_conflicts.is_empty() + !s.prompts.reload_conflicts.is_empty() }); - assert_eq!(c.state.reload_conflicts, [c.output.clone()]); + assert_eq!(c.state.prompts.reload_conflicts, [c.output.clone()]); assert_eq!( c.tab().payload_epoch(), epoch, diff --git a/src/state/tests/a_save_names_its_destination.rs b/src/state/tests/a_save_names_its_destination.rs index f5764929e..27d4a5f17 100644 --- a/src/state/tests/a_save_names_its_destination.rs +++ b/src/state/tests/a_save_names_its_destination.rs @@ -30,7 +30,7 @@ fn mounted(root: &Path, install: bool, mode: EditMode, name: &str, shipped: &[u8 let archive_path = root.join("update").join("update.rpf"); let mut state = AppState::new(); - state.retail_edit_session_allow = false; + state.prompts.retail_edit_session_allow = false; state.prefs.edit_mode = mode; state.prefs.export_fixes = ExportFixes::Ask; let bytes = crate::state::document_io::serialize_archive_records( @@ -117,12 +117,13 @@ fn save(f: &mut Fixture, dest: SaveDestination) { assert!(f.state.save_active_document()); let choice = f .state + .prompts .save_destination .clone() .expect("saving an archive entry asks where it goes"); assert_eq!(choice.doc_id, f.entry_doc); f.state.choose_save_destination(dest); - assert!(f.state.save_destination.is_none()); + assert!(f.state.prompts.save_destination.is_none()); } #[test] @@ -176,13 +177,13 @@ fn every_destination_is_behind_the_gate() { "{dest:?} wrote into the install in ReadOnly" ); assert!(f.state.document(f.entry_doc).expect("the entry").dirty); - f.state.overlay_copy.offer = None; + f.state.bg.overlay_copy.offer = None; } // `Everything` asks first, and the answer is what writes. f.state.prefs.edit_mode = EditMode::Everything; save(&mut f, SaveDestination::Archive); - assert!(f.state.pending_retail_edit.is_some(), "the gate asks first"); + assert!(f.state.prompts.retail_edit.is_some(), "the gate asks first"); assert_eq!(std::fs::read(&f.archive).expect("archive"), before); f.state .apply_pending_retail_edit(crate::state::RetailEditDecision::YesSession); diff --git a/src/state/tests/a_self_check_keeps_to_itself.rs b/src/state/tests/a_self_check_keeps_to_itself.rs index 97e356a21..ab67755aa 100644 --- a/src/state/tests/a_self_check_keeps_to_itself.rs +++ b/src/state/tests/a_self_check_keeps_to_itself.rs @@ -100,7 +100,7 @@ fn a_self_checks_rebake_starts_nothing_and_writes_nothing() { let owners = owners_pack_manifest(); let mut state = a_self_check(); // ⚠ Asked before the rebake: until the bake has a stand-in, a rebake writes where the pack is. - let pack = state.game_pack.root().to_path_buf(); + let pack = state.install.game_pack.root().to_path_buf(); assert!( pack.starts_with(&own), "the game's shader pack is at {}, outside the run's own configuration {}", @@ -112,7 +112,7 @@ fn a_self_checks_rebake_starts_nothing_and_writes_nothing() { keys_for(&mut state, install.path()); let lines = crate::platform::tests::said(|| click(&mut state, Action::BakeShaders, None)); - assert!(!state.game_pack.is_baking(), "a bake started"); + assert!(!state.install.game_pack.is_baking(), "a bake started"); assert!(!pack.exists(), "a pack was baked into {}", pack.display()); assert_eq!( owners_pack_manifest(), @@ -280,7 +280,7 @@ fn a_self_checks_first_launch_bake_asks_the_stand_in_once() { asks, 1, "the bake's stand-in was asked {asks} times: {lines:?}" ); - assert!(!state.game_pack.is_baking(), "a bake started"); + assert!(!state.install.game_pack.is_baking(), "a bake started"); assert_eq!( owners_pack_manifest(), owners, diff --git a/src/state/tests/a_skeleton_is_seen_without_an_animation.rs b/src/state/tests/a_skeleton_is_seen_without_an_animation.rs index ed6d95a20..7bd3670f2 100644 --- a/src/state/tests/a_skeleton_is_seen_without_an_animation.rs +++ b/src/state/tests/a_skeleton_is_seen_without_an_animation.rs @@ -385,7 +385,7 @@ fn a_skeleton_chosen() { let mut p = previewing_the_rig::(holder, false); assert!(p.state.preview_scene.clip.is_none()); assert!( - p.state.anim.skeleton().is_none(), + p.state.animation.session.skeleton().is_none(), "no clip binds a skeleton" ); @@ -432,7 +432,8 @@ fn a_clip_that_does_not_bind() { p.state.preview_scene.set_clip(p.clips, CLIP); p.state.tick_animation(); assert!( - p.state.anim.player.is_none() && p.state.anim.world_matrices.is_empty(), + p.state.animation.session.player.is_none() + && p.state.animation.session.world_matrices.is_empty(), "{:?}: the clip over other bones poses the skeleton", p.holder ); diff --git a/src/state/tests/an_error_names_what_failed.rs b/src/state/tests/an_error_names_what_failed.rs index d9f395ea7..bb4c30d1e 100644 --- a/src/state/tests/an_error_names_what_failed.rs +++ b/src/state/tests/an_error_names_what_failed.rs @@ -33,7 +33,7 @@ fn a_failed_save_is_titled_as_a_save_and_a_failed_open_as_an_open() { let mut state = AppState::default(); let (tx, receiver) = std::sync::mpsc::channel(); - state.save_receiver = Some(crate::state::file_io::SaveJob { + state.io_queue.save_receiver = Some(crate::state::file_io::SaveJob { path: "vehicle.ydr".into(), cancel: or_job::Cancel::new(), receiver, @@ -55,7 +55,7 @@ fn a_failed_save_is_titled_as_a_save_and_a_failed_open_as_an_open() { state.clear_error(); let (tx, rx) = std::sync::mpsc::channel(); - state.load_receiver = Some(("vehicle.ydr".into(), rx)); + state.io_queue.load_receiver = Some(("vehicle.ydr".into(), rx)); tx.send(LoadResult::Error { path: "vehicle.ydr".into(), message: "not a drawable".into(), diff --git a/src/state/tests/an_export_asks_before_it_alters_the_bytes.rs b/src/state/tests/an_export_asks_before_it_alters_the_bytes.rs index c8168375b..60d9c6458 100644 --- a/src/state/tests/an_export_asks_before_it_alters_the_bytes.rs +++ b/src/state/tests/an_export_asks_before_it_alters_the_bytes.rs @@ -63,7 +63,7 @@ fn state_holding(files: &[(&str, Vec)]) -> (AppState, DocumentId, RpfNodeId) fn run_to_completion(state: &mut AppState) { let deadline = Instant::now() + Duration::from_secs(30); - while state.extract_jobs.is_running() { + while state.bg.extract_jobs.is_running() { state.poll_extract_job(); assert!(Instant::now() < deadline, "the extraction never reported"); std::thread::sleep(Duration::from_millis(2)); @@ -87,7 +87,7 @@ fn declining_the_fixes_writes_the_original_bytes() { let dest = tmp.path().join("out"); export(&mut state, doc, root, &dest); state.apply_export_fixes(false, false); - assert!(state.pending_export_fixes.is_none()); + assert!(state.prompts.export_fixes.is_none()); run_to_completion(&mut state); assert_eq!( std::fs::read(dest.join("b.gxt2")).expect("b.gxt2"), diff --git a/src/state/tests/an_extraction_holds_back_only_the_files_it_reads.rs b/src/state/tests/an_extraction_holds_back_only_the_files_it_reads.rs index bdda20502..ea063b01a 100644 --- a/src/state/tests/an_extraction_holds_back_only_the_files_it_reads.rs +++ b/src/state/tests/an_extraction_holds_back_only_the_files_it_reads.rs @@ -111,9 +111,10 @@ fn a_mod_does_not_move_under_an_extraction_still_opening_its_rows() { state.prefs.edit_mode = EditMode::Overlay; state.refresh_mods(); assert!( - state.mod_manager.mods.iter().any(|m| m.name == "sub"), + state.bg.mod_manager.mods.iter().any(|m| m.name == "sub"), "`sub` is not listed as a mod: {:?}", state + .bg .mod_manager .mods .iter() @@ -128,7 +129,7 @@ fn a_mod_does_not_move_under_an_extraction_still_opening_its_rows() { assert_eq!(started, ExtractStart::Planning); state.ask_toggle_mod("sub"); assert_eq!( - state.mod_manager.pending_move, None, + state.bg.mod_manager.pending_move, None, "the move was offered under the extraction" ); assert!( @@ -142,7 +143,7 @@ fn a_mod_does_not_move_under_an_extraction_still_opening_its_rows() { run_to_completion(&mut state); state.ask_toggle_mod("sub"); assert!( - state.mod_manager.pending_move.is_some(), + state.bg.mod_manager.pending_move.is_some(), "the move is refused for good: {:?}", errors(&state) ); @@ -240,7 +241,7 @@ fn a_count_goes_on_while_the_submenu_that_started_it_is_closed() { state.count_types_under(doc, row); // The menu is closed: only the frame's own tick runs, as no `census_of` is asked let until = Instant::now() + Duration::from_secs(30); - while state.extract_jobs.census.is_some() { + while state.bg.extract_jobs.census.is_some() { assert!(Instant::now() < until, "the count never went on"); state.poll_extract_job(); std::thread::sleep(Duration::from_millis(2)); diff --git a/src/state/tests/an_undo_finishes_or_says_why.rs b/src/state/tests/an_undo_finishes_or_says_why.rs index cb41551b0..92d7d9f6e 100644 --- a/src/state/tests/an_undo_finishes_or_says_why.rs +++ b/src/state/tests/an_undo_finishes_or_says_why.rs @@ -198,7 +198,10 @@ fn undoing_a_cut_asks_the_edit_gate_before_it_writes_the_file_back() { std::fs::write(game.join("gta5.exe"), b"an install marker").expect("marker"); std::fs::write(game.join("readme.txt"), SHIPPED).expect("a shipped file"); let (mut state, tree) = install(&game, &[("x.rpf", archive(&[("kept.txt", b"kept")]))]); - (state.prefs.edit_mode, state.retail_edit_session_allow) = (EditMode::Everything, true); + ( + state.prefs.edit_mode, + state.prompts.retail_edit_session_allow, + ) = (EditMode::Everything, true); let readme = node_at(&mut state, tree, "readme.txt"); let x_row = node_at(&mut state, tree, "x.rpf"); state.set_active_document(tree); @@ -224,10 +227,10 @@ fn undoing_a_cut_asks_the_edit_gate_before_it_writes_the_file_back() { // A mode that permits the write, with the session not yet allowed it: the gate would ask, so the undo asks state.prefs.edit_mode = EditMode::Everything; - state.retail_edit_session_allow = false; + state.prompts.retail_edit_session_allow = false; state.toasts.clear(); assert_eq!(state.undo(), None, "the undo went ahead unasked"); - let asked = state.pending_retail_edit.as_ref().expect("the undo asked"); + let asked = state.prompts.retail_edit.as_ref().expect("the undo asked"); assert_eq!(asked.target_path, game.join("readme.txt")); assert_eq!(asked.verb, "undo"); assert!( diff --git a/src/state/tests/building_a_dlc_pack_from_the_app.rs b/src/state/tests/building_a_dlc_pack_from_the_app.rs index 1ac9ac8c9..0a9813354 100644 --- a/src/state/tests/building_a_dlc_pack_from_the_app.rs +++ b/src/state/tests/building_a_dlc_pack_from_the_app.rs @@ -231,7 +231,7 @@ fn a_pack_is_never_built_into_a_game_install() { let mut state = AppState::from_prefs(Prefs::default()); (state.prefs.game_paths).set(Game::GtaVLegacy, Some(install.clone())); state.ask_dlc_pack(source); - if let Some(asked) = state.dlc_pack.asked.as_mut() { + if let Some(asked) = state.bg.dlc_pack.asked.as_mut() { asked.spec.name = "mypack".into(); asked.recheck(); } @@ -242,11 +242,11 @@ fn a_pack_is_never_built_into_a_game_install() { (EditMode::Everything, dlcpacks(&install)), ] { state.prefs.edit_mode = mode; - state.retail_edit_session_allow = true; + state.prompts.retail_edit_session_allow = true; state.create_dlc_pack(dest.clone()); built_by_the_job(&mut state); assert!( - state.dlc_pack.asked.is_some(), + state.bg.dlc_pack.asked.is_some(), "{mode:?}: a refused build keeps its question, to choose another folder" ); assert!( @@ -301,6 +301,7 @@ fn a_folder_opened_with_open_folder_packs_from_its_own_row() { ); assert_eq!( state + .bg .dlc_pack .asked .as_ref() @@ -359,6 +360,7 @@ fn the_palette_packs_the_folder_opened_when_no_row_is_selected() { assert_eq!( state + .bg .dlc_pack .asked .as_ref() diff --git a/src/state/tests/comparing_every_resource_and_archive.rs b/src/state/tests/comparing_every_resource_and_archive.rs index ede85b2e2..2c0f3a2f7 100644 --- a/src/state/tests/comparing_every_resource_and_archive.rs +++ b/src/state/tests/comparing_every_resource_and_archive.rs @@ -570,7 +570,7 @@ fn a_comparison_waits_for_a_defragment_of_an_archive_it_reads() { state.defragment_archive(folder, a); settle(&mut state); - assert!(state.defrag.holds(&held), "the size preview is on offer"); + assert!(state.bg.defrag.holds(&held), "the size preview is on offer"); run(&mut state, Action::SelectForCompare, folder, b); state.toasts.clear(); @@ -676,6 +676,7 @@ fn a_cancel_from_the_job_list_tells_the_comparison_running_to_stop() { let mut state = state(); let (told, heard) = std::sync::mpsc::channel(); state + .bg .compare .start("a.rpf ↔ b.rpf".into(), Vec::new(), move |stop| { let until = Instant::now() + Duration::from_secs(30); diff --git a/src/state/tests/converting_from_the_app.rs b/src/state/tests/converting_from_the_app.rs index 70f808ff6..8f165688c 100644 --- a/src/state/tests/converting_from_the_app.rs +++ b/src/state/tests/converting_from_the_app.rs @@ -83,7 +83,7 @@ pub(in crate::state) fn clis_entry(input: &Path, out: &Path, defs: &Path) -> Val pub(in crate::state) fn browsing(input: &Path, remap: &ParamRemap) -> (AppState, egui::Context) { let mut state = AppState::from_prefs(Prefs::default()); state.prefs.explorer = Default::default(); - state.shader_defs.remap = Arc::new(remap.clone()); + state.install.shader_defs.remap = Arc::new(remap.clone()); state.open_folder(input.to_path_buf()); let doc = state.active_document.expect("the folder opens"); let ctx = accessible(); @@ -108,12 +108,12 @@ pub(in crate::state) fn convert_from_the_menu( let menu = frame(ctx, state, Vec::new()); click(ctx, state, find(&menu, egui::Rect::EVERYTHING, item)); let until = Instant::now() + DEADLINE; - while state.convert.done.is_none() && Instant::now() < until { + while state.bg.convert.done.is_none() && Instant::now() < until { state.poll_jobs(); std::thread::sleep(Duration::from_millis(5)); } assert!( - state.convert.done.is_some(), + state.bg.convert.done.is_some(), "{name}: the conversion never asked" ); } @@ -268,7 +268,7 @@ pub(in crate::state) fn buttons(ctx: &egui::Context, state: &mut AppState) -> Ve pub(in crate::state) fn written_by_the_job(state: &mut AppState) { let until = Instant::now() + DEADLINE; - while state.extract_jobs.is_running() && Instant::now() < until { + while state.bg.extract_jobs.is_running() && Instant::now() < until { state.poll_extract_job(); std::thread::sleep(Duration::from_millis(5)); } @@ -349,7 +349,7 @@ fn a_drawable_converts_from_its_menu_and_its_report_equals_the_clis() { state.write_conversion(dest.clone(), None); written_by_the_job(&mut state); assert!( - state.convert.done.is_none(), + state.bg.convert.done.is_none(), "{name}: the question is answered" ); let written = std::fs::read(&dest).unwrap_or_else(|e| panic!("{name}: {e}")); diff --git a/src/state/tests/converting_in_a_modders_words.rs b/src/state/tests/converting_in_a_modders_words.rs index 74a746f03..a30e33c46 100644 --- a/src/state/tests/converting_in_a_modders_words.rs +++ b/src/state/tests/converting_in_a_modders_words.rs @@ -209,7 +209,7 @@ fn a_folder_that_holds_one_of_the_names(what: &str) -> Option { ); convert_from_the_menu(&ctx, &mut state, &names[0], "Convert to Enhanced…"); assert_eq!( - state.convert.done.as_ref().map(|done| done.files.len()), + state.bg.convert.done.as_ref().map(|done| done.files.len()), Some(2), "the menu converts the selection" ); @@ -311,7 +311,7 @@ fn replace_writes_over_the_file_already_there_and_skip_leaves_it_as_it_is() { "{choice} still writes the file nothing was holding" ); assert!( - state.convert.clash.is_none() && state.convert.done.is_none(), + state.bg.convert.clash.is_none() && state.bg.convert.done.is_none(), "{choice} answers the question" ); } @@ -320,7 +320,7 @@ fn replace_writes_over_the_file_already_there_and_skip_leaves_it_as_it_is() { fn cancelling_a_conversions_write_stops_it_and_never_stops_an_extraction() { let scratch = tempfile::tempdir().expect("a scratch folder"); let mut state = AppState::from_prefs(Prefs::default()); - state.extract_jobs.start( + state.bg.extract_jobs.start( JobKind::Conversion, "3 files".into(), scratch.path().to_path_buf(), @@ -388,7 +388,7 @@ fn press(ctx: &egui::Context, state: &mut AppState, at: egui::Pos2, which: egui: fn opened(state: &mut AppState) -> DocumentId { let until = Instant::now() + DEADLINE; - while state.load_receiver.is_some() && Instant::now() < until { + while state.io_queue.load_receiver.is_some() && Instant::now() < until { state.poll_load_result(); std::thread::sleep(Duration::from_millis(5)); } @@ -429,7 +429,7 @@ fn a_document_converts_from_its_tab_as_it_stands_its_unsaved_edits_included() { let on_disk = std::fs::read(&model).expect("staged"); let mut state = AppState::from_prefs(Prefs::default()); state.prefs.explorer = Default::default(); - state.shader_defs.remap = Arc::new(remap); + state.install.shader_defs.remap = Arc::new(remap); state.load_file(model.clone()); let doc = opened(&mut state); edit_the_first_distance(&mut state, doc, DISTANCE); @@ -451,12 +451,12 @@ fn a_document_converts_from_its_tab_as_it_stands_its_unsaved_edits_included() { let item = find(&menu, egui::Rect::EVERYTHING, "Convert to Enhanced…"); press(&ctx, &mut state, item, egui::PointerButton::Primary); let until = Instant::now() + DEADLINE; - while state.convert.done.is_none() && Instant::now() < until { + while state.bg.convert.done.is_none() && Instant::now() < until { state.poll_jobs(); std::thread::sleep(Duration::from_millis(5)); } assert!( - state.convert.done.is_some(), + state.bg.convert.done.is_some(), "the tab's conversion never asked" ); diff --git a/src/state/tests/converting_is_listed_and_asked_inside_its_panel.rs b/src/state/tests/converting_is_listed_and_asked_inside_its_panel.rs index a512cae30..740a4fcec 100644 --- a/src/state/tests/converting_is_listed_and_asked_inside_its_panel.rs +++ b/src/state/tests/converting_is_listed_and_asked_inside_its_panel.rs @@ -81,7 +81,7 @@ fn is_listed_as_an_export_and_cancelled(state: &mut AppState, doing: &str) { fn a_gltf_exports_write_is_listed_as_an_export_and_cancel_export_reaches_it() { let scratch = tempfile::tempdir().expect("a scratch folder"); let mut state = AppState::from_prefs(Prefs::default()); - state.gltf.asked = Some(exported(Scene::default())); + state.bg.gltf.asked = Some(exported(Scene::default())); state.write_gltf(scratch.path().join("prop.glb")); is_listed_as_an_export_and_cancelled(&mut state, "Exporting prop.glb"); } @@ -106,7 +106,7 @@ fn an_export_as_write_is_listed_as_an_export_and_cancel_export_reaches_it() { fn cancelling_an_exports_write_stops_it_and_never_stops_an_extraction() { let scratch = tempfile::tempdir().expect("a scratch folder"); let mut state = AppState::from_prefs(Prefs::default()); - state.extract_jobs.start( + state.bg.extract_jobs.start( JobKind::Export, "prop.glb".into(), scratch.path().to_path_buf(), @@ -174,11 +174,16 @@ fn holding_paint() -> AppState { /// The names the conversion under way converted, once it asks, and whether it was of the open document. fn asked_about(state: &mut AppState) -> (Vec, bool) { let until = Instant::now() + DEADLINE; - while state.convert.done.is_none() && Instant::now() < until { + while state.bg.convert.done.is_none() && Instant::now() < until { state.poll_jobs(); std::thread::sleep(Duration::from_millis(5)); } - let done = state.convert.done.as_ref().expect("the conversion asked"); + let done = state + .bg + .convert + .done + .as_ref() + .expect("the conversion asked"); ( done.files.iter().map(|file| file.name.clone()).collect(), done.of_document, @@ -210,7 +215,7 @@ fn the_palette_and_its_key_convert_the_open_document_with_no_row_selected() { "the palette converts something else than the open document as it stands" ); - state.convert.done = None; + state.bg.convert.done = None; commands::run_action(&mut state, &ctx, Action::Convert); assert_eq!( asked_about(&mut state), diff --git a/src/state/tests/copy_cut_and_paste/files.rs b/src/state/tests/copy_cut_and_paste/files.rs index 0250bce21..b87d6df45 100644 --- a/src/state/tests/copy_cut_and_paste/files.rs +++ b/src/state/tests/copy_cut_and_paste/files.rs @@ -182,19 +182,20 @@ fn a_paste_asks_the_edit_gate_and_refuses_a_name_already_taken() { assert!(state.paste_rows(tree, c_row).is_err(), "Read only refuses"); assert!(!names_under(&state, tree, c_row).contains(&"copied.txt".to_string())); assert!( - state.pending_retail_edit.is_none(), + state.prompts.retail_edit.is_none(), "a refusal asks nothing" ); state.prefs.edit_mode = EditMode::Everything; - state.retail_edit_session_allow = false; + state.prompts.retail_edit_session_allow = false; assert!( state.paste_rows(tree, c_row).is_err(), "the gate asks first" ); assert!(!names_under(&state, tree, c_row).contains(&"copied.txt".to_string())); let asked = state - .pending_retail_edit + .prompts + .retail_edit .as_ref() .map(|p| (p.target_path.clone(), p.verb)); assert_eq!(asked, Some((dir.path().join("c.rpf"), "paste into"))); diff --git a/src/state/tests/defragmenting_an_archive.rs b/src/state/tests/defragmenting_an_archive.rs index be8485d48..aa0f7f316 100644 --- a/src/state/tests/defragmenting_an_archive.rs +++ b/src/state/tests/defragmenting_an_archive.rs @@ -81,7 +81,7 @@ fn with_archive(state: &mut AppState, path: &Path) -> (DocumentId, RpfNodeId) { pub(in crate::state) fn settle(state: &mut AppState) { let deadline = Instant::now() + Duration::from_secs(60); - while state.defrag.is_running() { + while state.bg.defrag.is_running() { state.poll_defrag(); assert!(Instant::now() < deadline, "the defragment never reported"); std::thread::sleep(Duration::from_millis(2)); @@ -101,7 +101,7 @@ fn defragmenting_shrinks_the_archive_and_keeps_every_entry() { state.defragment_archive(doc_id, node); settle(&mut state); - let offer = state.defrag.offer.as_ref().expect("a size preview"); + let offer = state.bg.defrag.offer.as_ref().expect("a size preview"); assert_eq!(offer.before, original.len() as u64); assert!( offer.after < offer.before, @@ -152,35 +152,38 @@ fn defragmenting_asks_the_gate() { std::fs::write(&shipped, &original).expect("archive"); let mut state = AppState::new(); - state.retail_edit_session_allow = false; + state.prompts.retail_edit_session_allow = false; state.prefs.edit_mode = EditMode::ReadOnly; state.open_game_root(install.clone()); let (doc_id, node) = with_archive(&mut state, &shipped); state.defragment_archive(doc_id, node); assert!( - !state.defrag.is_running() && state.defrag.offer.is_none(), + !state.bg.defrag.is_running() && state.bg.defrag.offer.is_none(), "`ReadOnly` starts nothing" ); state.prefs.edit_mode = EditMode::Everything; state.defragment_archive(doc_id, node); - assert!(!state.defrag.is_running(), "a shipped archive asks first"); + assert!( + !state.bg.defrag.is_running(), + "a shipped archive asks first" + ); assert!(matches!( - state.pending_retail_edit.as_ref().map(|p| &p.action), + state.prompts.retail_edit.as_ref().map(|p| &p.action), Some(PendingRetailEdit::Defragment { .. }) )); state.apply_pending_retail_edit(RetailEditDecision::YesSession); settle(&mut state); assert!( - state.defrag.offer.is_some(), + state.bg.defrag.offer.is_some(), "confirming starts the preview" ); // The write asks again, so a mode changed while the preview was up still // holds. Settings drops the session's allow with the mode, as here. state.prefs.edit_mode = EditMode::ReadOnly; - state.retail_edit_session_allow = false; + state.prompts.retail_edit_session_allow = false; state.answer_defrag(true); settle(&mut state); assert_eq!(std::fs::read(&shipped).expect("archive"), original); @@ -267,17 +270,17 @@ fn defragmenting_refuses_unsaved_edits_and_open_tabs() { spoil(rpf(&mut state, doc_id), doc_id, files[0]); state.defragment_archive(doc_id, node); assert!( - !state.defrag.is_running() && state.defrag.offer.is_none(), + !state.bg.defrag.is_running() && state.bg.defrag.offer.is_none(), "{what} refuses the start" ); let (_tmp, path2, original2, mut state2, doc_id2, node2, files2) = staged(); state2.defragment_archive(doc_id2, node2); settle(&mut state2); - assert!(state2.defrag.offer.is_some()); + assert!(state2.bg.defrag.offer.is_some()); spoil(rpf(&mut state2, doc_id2), doc_id2, files2[0]); state2.answer_defrag(true); - assert!(!state2.defrag.is_running(), "{what} refuses the write"); + assert!(!state2.bg.defrag.is_running(), "{what} refuses the write"); assert_eq!(std::fs::read(&path2).expect("archive"), original2); assert_eq!(std::fs::read(&path).expect("archive"), original); } @@ -289,7 +292,7 @@ fn nothing_else_writes_an_archive_being_defragmented() { let (_tmp, path, original, mut state, doc_id, node, files) = staged(); state.defragment_archive(doc_id, node); settle(&mut state); - assert!(state.defrag.offer.is_some()); + assert!(state.bg.defrag.offer.is_some()); assert!(state.rpf_rename_node(doc_id, files[0], "z.bin").is_err()); assert!(state @@ -310,7 +313,7 @@ fn a_file_changed_after_the_preview_is_not_replaced() { let (_tmp, path, original, mut state, doc_id, node, _) = staged(); state.defragment_archive(doc_id, node); settle(&mut state); - assert!(state.defrag.offer.is_some()); + assert!(state.bg.defrag.offer.is_some()); let mut changed = original.clone(); changed.extend_from_slice(&[0; 512]); diff --git a/src/state/tests/destructive_file_operations_ask.rs b/src/state/tests/destructive_file_operations_ask.rs index 4e7dde2e5..ffd4e2ea8 100644 --- a/src/state/tests/destructive_file_operations_ask.rs +++ b/src/state/tests/destructive_file_operations_ask.rs @@ -101,7 +101,7 @@ pub(in crate::state) fn node_at(state: &mut AppState, doc: DocumentId, path: &st for name in path.split('/') { state.request_expand(doc, node); let deadline = Instant::now() + Duration::from_secs(30); - while state.expander.is_in_flight(doc, node) { + while state.bg.expander.is_in_flight(doc, node) { state.poll_expansions(); assert!(Instant::now() < deadline, "the tree's scan never finished"); std::thread::sleep(Duration::from_millis(2)); @@ -130,7 +130,7 @@ fn deleting_a_loose_folder_asks_first_and_sends_it_to_the_recycle_bin() { state .rpf_delete_node(doc, props) .expect("a delete outside an install asks rather than refuses"); - let asked = state.pending_delete.clone().expect("the delete asks first"); + let asked = state.prompts.delete.clone().expect("the delete asks first"); assert!( loose.join("props/lod/chair_lod.ydr").is_file(), "nothing goes before the answer" @@ -151,7 +151,7 @@ fn deleting_a_loose_folder_asks_first_and_sends_it_to_the_recycle_bin() { ); state.answer_delete(false); - assert!(state.pending_delete.is_none()); + assert!(state.prompts.delete.is_none()); assert!(loose.join("props/chair.ydr").is_file(), "a no keeps it"); assert!(child(&state, doc, session(&state, doc).root_id(), "props").is_some()); @@ -180,7 +180,7 @@ fn a_delete_inside_an_archive_asks_and_waits_for_the_save() { let models = child(&state, doc, root, "models").expect("models"); state.rpf_delete_node(doc, models).expect("asks"); - let asked = state.pending_delete.clone().expect("the delete asks first"); + let asked = state.prompts.delete.clone().expect("the delete asks first"); assert_eq!(asked.from, DeleteFrom::Session(Some("fixture.rpf".into()))); assert_eq!(asked.contents(), "2 files in 1 folder, 8 B"); assert!( @@ -263,8 +263,9 @@ fn contents(dest: &Path) -> Vec<(String, Vec)> { fn extracting_over_existing_files_asks_once_and_writes_nothing_until_answered() { let (_tmp, dest, mut state, _, started) = a_clashing_extraction(); assert_eq!(started, ExtractStart::AwaitingConfirmation); - assert!(!state.extract_jobs.is_running()); + assert!(!state.bg.extract_jobs.is_running()); let clash = state + .bg .extract_jobs .clash .as_ref() @@ -274,6 +275,9 @@ fn extracting_over_existing_files_asks_once_and_writes_nothing_until_answered() assert_eq!(before.len(), 2); state.answer_extract_clash(None); - assert!(!state.extract_jobs.is_running(), "cancel extracts nothing"); + assert!( + !state.bg.extract_jobs.is_running(), + "cancel extracts nothing" + ); assert_eq!(contents(&dest), before); } diff --git a/src/state/tests/editing_a_clip.rs b/src/state/tests/editing_a_clip.rs index b85134d28..0ca596c75 100644 --- a/src/state/tests/editing_a_clip.rs +++ b/src/state/tests/editing_a_clip.rs @@ -98,11 +98,11 @@ fn viewing_a_clip_whose_rate_is_past_its_fields_range_edits_nothing() { fn baking_without_a_skeleton_fails_and_keeps_the_edits() { let (mut state, _id) = state_with_clip(); let (key, value) = edit_at(1, 1.0); - state.anim_edits.set(key, value); + state.animation.edits.set(key, value); assert!(state.bake_anim_edits().is_err()); assert_eq!( - state.anim_edits.len(), + state.animation.edits.len(), 1, "edits were lost on a failed bake" ); diff --git a/src/state/tests/every_question_fits_a_narrow_window.rs b/src/state/tests/every_question_fits_a_narrow_window.rs index ff473d973..d252a8e96 100644 --- a/src/state/tests/every_question_fits_a_narrow_window.rs +++ b/src/state/tests/every_question_fits_a_narrow_window.rs @@ -23,7 +23,7 @@ fn told(state: &AppState, what: &str) -> bool { /// A job of `kind` holding the one slot, that runs until it is stopped. fn holding_the_slot(state: &mut AppState, kind: JobKind, dest: &std::path::Path) { - state.extract_jobs.start( + state.bg.extract_jobs.start( kind, "prop.glb".into(), dest.to_path_buf(), @@ -48,7 +48,7 @@ fn a_second_write_names_the_job_that_holds_the_slot_as_the_list_does() { let scratch = tempfile::tempdir().expect("a scratch folder"); holding_the_slot(&mut state, kind, scratch.path()); - state.gltf.asked = Some(exported(Scene::default())); + state.bg.gltf.asked = Some(exported(Scene::default())); state.write_gltf(scratch.path().join("again.glb")); assert!( told(&state, &format!("{noun} is running")), @@ -64,12 +64,12 @@ fn questions() -> Vec<(&'static str, AppState)> { let mut all = Vec::new(); let mut state = AppState::from_prefs(Prefs::default()); - state.gltf.asked = Some(exported(Scene::default())); + state.bg.gltf.asked = Some(exported(Scene::default())); all.push(("the glTF export's", state)); let mut state = AppState::from_prefs(Prefs::default()); let payload = DocPayload::Resource(or_io::Asset::Drawable(Default::default())); - state.gltf.asked = Some(Asked::Import(Import { + state.bg.gltf.asked = Some(Asked::Import(Import { doc: crate::state::DocumentId(1), name: "prop.ydr".into(), mesh: PathBuf::from("prop.glb"), @@ -84,7 +84,7 @@ fn questions() -> Vec<(&'static str, AppState)> { all.push(("the glTF import's", state)); let mut state = AppState::from_prefs(Prefs::default()); - state.pending_delete = Some(PendingDelete { + state.prompts.delete = Some(PendingDelete { doc_id: crate::state::DocumentId(1), node_id: crate::state::RpfNodeId(1), name: "a_file_with_a_name.ytd".into(), @@ -96,7 +96,7 @@ fn questions() -> Vec<(&'static str, AppState)> { all.push(("the delete's", state)); let mut state = AppState::from_prefs(Prefs::default()); - state.extract_jobs.clash = Some(ExtractClash { + state.bg.extract_jobs.clash = Some(ExtractClash { doc_id: crate::state::DocumentId(1), nodes: vec![crate::state::RpfNodeId(1)], dest: PathBuf::from("C:/somewhere/out"), @@ -172,7 +172,7 @@ fn a_conversion_written_while_another_job_holds_the_slot_names_it_and_keeps_the_ .to_bytes() .expect("a Legacy .ytd saves"); let made = or_cli::retarget_file("paint.ytd", &bytes, &Default::default()); - state.convert.done = Some(crate::state::convert::Converted { + state.bg.convert.done = Some(crate::state::convert::Converted { files: vec![crate::state::convert::ConvertedFile { name: "paint.ytd".into(), outcome: Ok(made.expect("it converts")), @@ -188,7 +188,7 @@ fn a_conversion_written_while_another_job_holds_the_slot_names_it_and_keeps_the_ state.toasts.iter().map(|t| &t.message).collect::>() ); assert!( - state.convert.done.is_some() && !dest.exists(), + state.bg.convert.done.is_some() && !dest.exists(), "a refused write must keep the question and write nothing" ); state.cancel_job(kind); diff --git a/src/state/tests/every_write_asks_the_jobs_reading_it.rs b/src/state/tests/every_write_asks_the_jobs_reading_it.rs index 2f6159bd5..6b1bd2eb0 100644 --- a/src/state/tests/every_write_asks_the_jobs_reading_it.rs +++ b/src/state/tests/every_write_asks_the_jobs_reading_it.rs @@ -29,7 +29,7 @@ pub(in crate::state) fn pack_built_from(state: &mut AppState, scratch: &Path) -> std::fs::create_dir_all(&props).expect("the folders"); std::fs::write(props.join("props.ityp"), b"archetypes").expect("a file of the pack"); state.ask_dlc_pack(source); - if let Some(asked) = state.dlc_pack.asked.as_mut() { + if let Some(asked) = state.bg.dlc_pack.asked.as_mut() { asked.spec.name = "mypack".into(); asked.recheck(); } @@ -109,7 +109,7 @@ fn a_conversion_written_into_a_folder_a_pack_is_built_from_is_refused_naming_the [_] => vec![dest.clone()], _ => names.iter().map(|name| dest.join(name)).collect(), }; - state.convert.done = Some(made(names)); + state.bg.convert.done = Some(made(names)); state.write_conversion(dest.clone(), None); written_by_the_job(&mut state); if files.iter().any(|file| file.exists()) { @@ -119,7 +119,7 @@ fn a_conversion_written_into_a_folder_a_pack_is_built_from_is_refused_naming_the "{what}: the refusal names no build: {:?}", errors(&state) )); - } else if state.convert.done.is_none() { + } else if state.bg.convert.done.is_none() { failed.push(format!("{what}: the refusal dropped the question")); } state.toasts.clear(); @@ -128,7 +128,7 @@ fn a_conversion_written_into_a_folder_a_pack_is_built_from_is_refused_naming_the // Nothing the build reads is replaced here, so it goes ahead. let beside = elsewhere.join("prop.ydr"); - state.convert.done = Some(made(&["prop.ydr"])); + state.bg.convert.done = Some(made(&["prop.ydr"])); state.write_conversion(beside.clone(), None); written_by_the_job(&mut state); assert!( @@ -138,7 +138,7 @@ fn a_conversion_written_into_a_folder_a_pack_is_built_from_is_refused_naming_the ); ended(&mut state, JobKind::DlcPack); - state.convert.done = Some(made(&["prop.ydr"])); + state.bg.convert.done = Some(made(&["prop.ydr"])); let dest = props.join("prop.ydr"); state.write_conversion(dest.clone(), None); written_by_the_job(&mut state); diff --git a/src/state/tests/every_write_into_a_folder_a_job_reads_is_refused.rs b/src/state/tests/every_write_into_a_folder_a_job_reads_is_refused.rs index 13c9665bb..12ed8026b 100644 --- a/src/state/tests/every_write_into_a_folder_a_job_reads_is_refused.rs +++ b/src/state/tests/every_write_into_a_folder_a_job_reads_is_refused.rs @@ -29,7 +29,7 @@ fn an_extraction_beside_a_file_a_job_reads_goes_ahead_and_over_it_is_refused() { std::fs::create_dir(folder).expect("a folder to extract into"); } let reads = vec![beside.join("other.txt")]; - (state.compare).start("a pair".into(), reads, |_| Ended::Failed(String::new())); + (state.bg.compare).start("a pair".into(), reads, |_| Ended::Failed(String::new())); state.extract_rpf_node( tree, notes, @@ -46,7 +46,7 @@ fn an_extraction_beside_a_file_a_job_reads_goes_ahead_and_over_it_is_refused() { ended(&mut state, JobKind::Compare); let reads = vec![over.join("notes.txt")]; - (state.compare).start("a pair".into(), reads, |_| Ended::Failed(String::new())); + (state.bg.compare).start("a pair".into(), reads, |_| Ended::Failed(String::new())); state.extract_rpf_node( tree, notes, @@ -89,7 +89,7 @@ fn a_write_into_a_folder_a_job_reads_is_refused_however_the_disk_is_asked_for_it let mut failed = Vec::new(); for (what, folder, refused) in spellings { - state.convert.done = Some(made(&["prop.ydr"])); + state.bg.convert.done = Some(made(&["prop.ydr"])); state.write_conversion(folder.join("prop.ydr"), None); written_by_the_job(&mut state); if named(&state, BUILD) != refused { diff --git a/src/state/tests/gltf_in_and_out_from_the_app.rs b/src/state/tests/gltf_in_and_out_from_the_app.rs index ffee65e50..2c9c6e64f 100644 --- a/src/state/tests/gltf_in_and_out_from_the_app.rs +++ b/src/state/tests/gltf_in_and_out_from_the_app.rs @@ -117,7 +117,7 @@ fn tab_strip() -> egui::Rect { /// Polls until the question's export or import is worked out. fn worked_out(state: &mut AppState) { - let done = |state: &AppState| match &state.gltf.asked { + let done = |state: &AppState| match &state.bg.gltf.asked { Some(Asked::Export(asked)) => asked.made.is_some(), Some(Asked::Import(asked)) => asked.made.is_some(), None => true, @@ -132,7 +132,7 @@ fn worked_out(state: &mut AppState) { fn written_by_the_job(state: &mut AppState) { let until = Instant::now() + DEADLINE; - while state.extract_jobs.is_running() && Instant::now() < until { + while state.bg.extract_jobs.is_running() && Instant::now() < until { state.poll_extract_job(); std::thread::sleep(Duration::from_millis(5)); } @@ -140,7 +140,7 @@ fn written_by_the_job(state: &mut AppState) { fn opened(state: &mut AppState) -> DocumentId { let until = Instant::now() + DEADLINE; - while state.load_receiver.is_some() && Instant::now() < until { + while state.io_queue.load_receiver.is_some() && Instant::now() < until { state.poll_load_result(); std::thread::sleep(Duration::from_millis(5)); } @@ -150,7 +150,7 @@ fn opened(state: &mut AppState) -> DocumentId { fn saved(state: &mut AppState, path: &Path) -> Vec { assert!(state.save_active_document_as(path.to_path_buf())); let until = Instant::now() + DEADLINE; - while state.save_receiver.is_some() && Instant::now() < until { + while state.io_queue.save_receiver.is_some() && Instant::now() < until { state.poll_save_result(); std::thread::sleep(Duration::from_millis(5)); } @@ -410,7 +410,7 @@ fn a_ydr_exports_and_imports_back_from_its_menus_and_saves_what_the_cli_writes() let at = find(&asked, egui::Rect::EVERYTHING, "Replace").at; click(&ctx, &mut state, at); assert!( - state.gltf.asked.is_none(), + state.bg.gltf.asked.is_none(), "{name}: the question is still open" ); let document = state.document(doc).expect("open"); @@ -546,7 +546,7 @@ fn every_level_without_textures_as_gltf(s: &Copied) { ] { choose(&ctx, &mut state, label); } - let Some(Asked::Export(asked)) = &state.gltf.asked else { + let Some(Asked::Export(asked)) = &state.bg.gltf.asked else { panic!("{}: the question closed", s.name); }; let chosen = ExportChoice { @@ -579,7 +579,7 @@ fn every_level_without_textures_as_gltf(s: &Copied) { fn one_drawable(s: &Copied) { let (mut state, ctx) = exporting(s); - let Some(Asked::Export(asked)) = &state.gltf.asked else { + let Some(Asked::Export(asked)) = &state.bg.gltf.asked else { panic!("{}: the question closed", s.name); }; let (entry, drawable) = (asked.drawables.get(1).cloned()) @@ -594,7 +594,7 @@ fn one_drawable(s: &Copied) { // The combo box shows what is chosen, and a click there opens its list. choose(&ctx, &mut state, "Every drawable"); choose(&ctx, &mut state, &format!("{entry} {drawable}")); - let Some(Asked::Export(asked)) = &state.gltf.asked else { + let Some(Asked::Export(asked)) = &state.bg.gltf.asked else { panic!("{}: the question closed", s.name); }; assert_eq!( @@ -691,7 +691,7 @@ fn an_import_the_library_refuses_says_why_and_changes_nothing() { let at = find(&asked, egui::Rect::EVERYTHING, "Cancel").at; click(&ctx, &mut state, at); assert!( - state.gltf.asked.is_none(), + state.bg.gltf.asked.is_none(), "{name}: Cancel left the question open" ); let document = state.document(doc).expect("open"); @@ -748,7 +748,7 @@ fn a_channel_the_mesh_leaves_out_is_refused_in_words_and_never_by_a_flag() { let doc = opened(&mut state); state.import_gltf(doc, mesh); worked_out(&mut state); - let Some(Asked::Import(asked)) = &state.gltf.asked else { + let Some(Asked::Import(asked)) = &state.bg.gltf.asked else { panic!("{name}: the import asked nothing"); }; let Some(Err(why)) = &asked.made else { @@ -770,7 +770,7 @@ fn a_gltf_export_asks_the_edit_gate_where_it_writes() { let mut state = AppState::from_prefs(Prefs::default()); (state.prefs.game_paths).set(Game::GtaVLegacy, Some(install.clone())); state.prefs.edit_mode = EditMode::ReadOnly; - state.gltf.asked = Some(Asked::Export(Export { + state.bg.gltf.asked = Some(Asked::Export(Export { name: "prop.ydr".into(), bytes: Default::default(), choice: ExportChoice { @@ -792,7 +792,7 @@ fn a_gltf_export_asks_the_edit_gate_where_it_writes() { "Read only writes nothing inside the install" ); assert!( - state.gltf.asked.is_some(), + state.bg.gltf.asked.is_some(), "a refused write keeps the question, to choose another place" ); @@ -800,5 +800,8 @@ fn a_gltf_export_asks_the_edit_gate_where_it_writes() { state.write_gltf(outside.clone()); written_by_the_job(&mut state); assert!(outside.is_file(), "outside the install it writes"); - assert!(state.gltf.asked.is_none(), "a write answers the question"); + assert!( + state.bg.gltf.asked.is_none(), + "a write answers the question" + ); } diff --git a/src/state/tests/gta6_textures_resolve_and_save.rs b/src/state/tests/gta6_textures_resolve_and_save.rs index 2a11cd156..2f1a3bbfa 100644 --- a/src/state/tests/gta6_textures_resolve_and_save.rs +++ b/src/state/tests/gta6_textures_resolve_and_save.rs @@ -36,7 +36,7 @@ fn a_pack_saved_over_its_own_file_streams_through_a_file_beside_it_and_reads_its assert!( save_as(&mut state, doc, &same_file), "{}", - state.error_dialog_message + state.error_dialog.message ); let saved = or_io::gta6::TexturePack::open(&source).expect("the saved pack opens"); @@ -78,13 +78,13 @@ fn a_pack_saved_over_another_tab_s_file_leaves_that_tab_s_edits_to_ask_first() { assert!( save_as(&mut state, saved, &target), "{}", - state.error_dialog_message + state.error_dialog.message ); assert!( state.document(edited).expect("open").dirty, "its replacement is kept" ); - assert!(state.reload_conflicts.iter().any(|p| p == &target)); + assert!(state.prompts.reload_conflicts.iter().any(|p| p == &target)); } #[test] diff --git a/src/state/tests/nested_archives_survive_a_save.rs b/src/state/tests/nested_archives_survive_a_save.rs index ca42becaf..619eace30 100644 --- a/src/state/tests/nested_archives_survive_a_save.rs +++ b/src/state/tests/nested_archives_survive_a_save.rs @@ -74,7 +74,7 @@ pub(in crate::state) fn save(state: &mut AppState, doc: DocumentId) { state.set_active_document(doc); assert!(state.save_active_document(), "{:?}", errors(state)); let deadline = Instant::now() + Duration::from_secs(60); - while state.save_receiver.is_some() { + while state.io_queue.save_receiver.is_some() { assert!(Instant::now() < deadline, "the save did not finish"); state.poll_save_result(); std::thread::sleep(Duration::from_millis(5)); @@ -177,7 +177,7 @@ fn an_edit_two_archives_deep_saves(how: Saved) { let outer = archive(&[("mid.rpf", &mid), ("a.txt", b"a")]); let dir = tempfile::tempdir().expect("a scratch directory"); let mut state = AppState::new(); - state.retail_edit_session_allow = false; + state.prompts.retail_edit_session_allow = false; let opened = Opened::InAnInstallTree; if how == Saved::WithTheTree { std::fs::write(dir.path().join("gta5.exe"), b"an install marker").expect("marker"); @@ -197,7 +197,7 @@ fn an_edit_two_archives_deep_saves(how: Saved) { state.set_active_document(doc); assert!(state.save_active_document()); assert!( - state.pending_retail_edit.is_some(), + state.prompts.retail_edit.is_some(), "the gate does not ask about the archive on disk: {:?}", errors(&state) ); @@ -215,6 +215,7 @@ fn an_edit_two_archives_deep_saves(how: Saved) { edited.mark_edited(); assert!(state.save_active_document()); let choice = state + .prompts .save_destination .clone() .expect("saving an archive entry asks where it goes"); diff --git a/src/state/tests/no_save_replaces_a_file_a_job_reads.rs b/src/state/tests/no_save_replaces_a_file_a_job_reads.rs index 784340a25..479e24e1e 100644 --- a/src/state/tests/no_save_replaces_a_file_a_job_reads.rs +++ b/src/state/tests/no_save_replaces_a_file_a_job_reads.rs @@ -44,7 +44,7 @@ pub(in crate::state) fn named(state: &AppState, job: &str) -> bool { /// Wait for a save on a worker, if one started. pub(in crate::state) fn written(state: &mut AppState) { let until = Instant::now() + DEADLINE; - while state.save_receiver.is_some() { + while state.io_queue.save_receiver.is_some() { assert!(Instant::now() < until, "the save never finished"); state.poll_save_result(); std::thread::sleep(Duration::from_millis(5)); @@ -165,7 +165,7 @@ fn a_file_inside_a_folder_saved_while_a_pack_is_built_from_it_is_refused_naming_ let more_entry = finish_load(&mut state).expect("b.txt opens"); state.ask_dlc_pack(source.clone()); - if let Some(asked) = state.dlc_pack.asked.as_mut() { + if let Some(asked) = state.bg.dlc_pack.asked.as_mut() { asked.spec.name = "mypack".into(); asked.recheck(); } diff --git a/src/state/tests/nothing_extracts_into_an_install.rs b/src/state/tests/nothing_extracts_into_an_install.rs index 9aaf56995..2669f6049 100644 --- a/src/state/tests/nothing_extracts_into_an_install.rs +++ b/src/state/tests/nothing_extracts_into_an_install.rs @@ -35,7 +35,7 @@ fn state_holding_two_entries() -> (AppState, DocumentId, RpfNodeId) { let mut state = AppState::new(); state.documents.clear(); state.active_document = None; - state.retail_edit_session_allow = false; + state.prompts.retail_edit_session_allow = false; let mut session = RpfEditSession::empty(); let root = session.root_id(); @@ -71,7 +71,7 @@ fn state_holding_two_entries() -> (AppState, DocumentId, RpfNodeId) { /// reaches it hangs here rather than passing. pub(in crate::state) fn run_to_completion(state: &mut AppState) { let deadline = Instant::now() + Duration::from_secs(30); - while state.extract_jobs.is_running() { + while state.bg.extract_jobs.is_running() { state.poll_extract_job(); if Instant::now() > deadline { panic!("the extraction never reported through the per-frame tick"); @@ -152,7 +152,7 @@ fn a_destination_outside_an_install_extracts_and_one_inside_it_does_not() { refused.display() ); assert!( - !state.extract_jobs.is_running(), + !state.bg.extract_jobs.is_running(), "a refused extraction must not have spawned a worker" ); assert!( @@ -187,10 +187,10 @@ fn declining_a_shipped_destination_writes_nothing_and_grants_nothing() { ExtractStart::AwaitingConfirmation ); state.apply_pending_retail_edit(RetailEditDecision::No); - assert!(!state.extract_jobs.is_running()); + assert!(!state.bg.extract_jobs.is_running()); assert!(!dest.exists()); assert!( - !state.retail_edit_session_allow, + !state.prompts.retail_edit_session_allow, "declining must not widen the gate for the rest of the session" ); } diff --git a/src/state/tests/one_place_for_background_jobs.rs b/src/state/tests/one_place_for_background_jobs.rs index 29363e13b..7b4984670 100644 --- a/src/state/tests/one_place_for_background_jobs.rs +++ b/src/state/tests/one_place_for_background_jobs.rs @@ -64,7 +64,7 @@ fn every_kind_running(scratch: &Path) -> AppState { std::fs::write(scratch.join("a.meta"), b"WEAPON_RAILGUN").expect("a file to search"); std::fs::write(scratch.join("notes.txt"), b"a file to open").expect("a file to open"); - state.extract_jobs.start( + state.bg.extract_jobs.start( JobKind::Extraction, "models".into(), scratch.join("out"), @@ -76,7 +76,7 @@ fn every_kind_running(scratch: &Path) -> AppState { }) }, ); - state.defrag.start( + state.bg.defrag.start( scratch.join("x64a.rpf"), "Defragmenting x64a.rpf".into(), |progress, cancel| { @@ -85,7 +85,7 @@ fn every_kind_running(scratch: &Path) -> AppState { crate::state::defrag_job::Outcome::Stopped }, ); - state.overlay_copy.start( + state.bg.overlay_copy.start( crate::state::overlay_copy::OverlayCopyOffer { source: scratch.join("update.rpf"), dest: scratch.join("mods").join("update.rpf"), @@ -98,7 +98,7 @@ fn every_kind_running(scratch: &Path) -> AppState { Err("stopped".into()) }, ); - state.search.start( + state.find.session.start( crate::state::search_session::SearchRequest { pattern: "railgun".into(), mode: crate::state::search_session::SearchMode::Text, @@ -110,12 +110,15 @@ fn every_kind_running(scratch: &Path) -> AppState { scratch.to_path_buf(), crypto.clone(), ); - state.file_index.walk_with(scratch.to_path_buf(), |stop| { - let until = Instant::now() + DEADLINE; - while !stop.load(std::sync::atomic::Ordering::Relaxed) && Instant::now() < until { - std::thread::sleep(Duration::from_millis(2)); - } - }); + state + .find + .file_index + .walk_with(scratch.to_path_buf(), |stop| { + let until = Instant::now() + DEADLINE; + while !stop.load(std::sync::atomic::Ordering::Relaxed) && Instant::now() < until { + std::thread::sleep(Duration::from_millis(2)); + } + }); state.keys.spawn( "Reading the keys from the game's executable", "Starting", @@ -126,10 +129,11 @@ fn every_kind_running(scratch: &Path) -> AppState { }, ); state + .install .game_pack .begin(sleeper()) .expect("a process that waits can be run"); - state.name_index.start_scan( + state.install.name_index.start_scan( scratch.to_path_buf(), crypto, or_title::MountOptions::install_only(), @@ -140,41 +144,44 @@ fn every_kind_running(scratch: &Path) -> AppState { SaveResult::Stopped }); state + .bg .convert .start("prop.ydr".into(), false, false, Vec::new(), |cancel, _| { until_stopped(&cancel); None }); state + .bg .dlc_pack .start("mypack".into(), scratch.to_path_buf(), |cancel, _| { until_stopped(&cancel); Err("stopped".into()) }); state + .bg .gltf .start("Exporting prop.ydr to glTF".into(), |cancel| { until_stopped(cancel); None }); - state.dependencies.start(|cancel, _| { + state.bg.dependencies.start(|cancel, _| { until_stopped(cancel); Err("stopped".into()) }); // A comparison reads on unheard once dropped, as an open does. state + .bg .compare .start("a.ymt ↔ b.ymt".into(), Vec::new(), |_| { std::thread::sleep(DEADLINE); crate::state::compare::Ended::Failed("stopped".into()) }); - (state.texture_naming).push(crate::state::gta6_texture_naming::TextureNaming::run( - "Naming".into(), - |cancel, _| { + (state.gta6_finders.texture_naming).push( + crate::state::gta6_texture_naming::TextureNaming::run("Naming".into(), |cancel, _| { until_stopped(cancel); crate::state::gta6_texture_naming::NamingEnded::Stopped - }, - )); + }), + ); state } diff --git a/src/state/tests/opening_a_dds.rs b/src/state/tests/opening_a_dds.rs index 32ef7c246..146b109f6 100644 --- a/src/state/tests/opening_a_dds.rs +++ b/src/state/tests/opening_a_dds.rs @@ -53,7 +53,7 @@ fn eight_by_eight_dxt1() -> Dds { fn open(state: &mut AppState, path: PathBuf) -> DocumentId { state.load_file(path.clone()); let deadline = Instant::now() + Duration::from_secs(30); - while state.load_receiver.is_some() && Instant::now() < deadline { + while state.io_queue.load_receiver.is_some() && Instant::now() < deadline { state.poll_load_result(); std::thread::sleep(Duration::from_millis(5)); } @@ -61,7 +61,7 @@ fn open(state: &mut AppState, path: PathBuf) -> DocumentId { matches!(state.loading, LoadingState::Idle), "{}: {}", path.display(), - state.error_dialog_message + state.error_dialog.message ); state .active_document @@ -71,7 +71,7 @@ fn open(state: &mut AppState, path: PathBuf) -> DocumentId { fn saved_as(state: &mut AppState, path: &Path) -> Vec { assert!(state.save_active_document_as(path.to_path_buf())); let deadline = Instant::now() + Duration::from_secs(30); - while state.save_receiver.is_some() && Instant::now() < deadline { + while state.io_queue.save_receiver.is_some() && Instant::now() < deadline { state.poll_save_result(); std::thread::sleep(Duration::from_millis(5)); } diff --git a/src/state/tests/opening_a_gta_vi_body.rs b/src/state/tests/opening_a_gta_vi_body.rs index f74ecb9d0..302bc1468 100644 --- a/src/state/tests/opening_a_gta_vi_body.rs +++ b/src/state/tests/opening_a_gta_vi_body.rs @@ -97,7 +97,7 @@ fn the_cells_across_a_gta_vi_cell_s_borders_are_found_in_its_scan_as_a_job_and_o settle(&mut state); let opened = (state.active_document) .filter(|&d| d != doc) - .unwrap_or_else(|| panic!("the cell: {}", state.error_dialog_message)); + .unwrap_or_else(|| panic!("the cell: {}", state.error_dialog.message)); let path = state .document(opened) .and_then(|d| d.path.clone()) @@ -115,7 +115,7 @@ fn the_cells_across_a_gta_vi_cell_s_borders_are_found_in_its_scan_as_a_job_and_o settle(&mut state); let first = (state.active_document) .filter(|&d| d != doc && d != opened) - .unwrap_or_else(|| panic!("the first east body: {}", state.error_dialog_message)); + .unwrap_or_else(|| panic!("the first east body: {}", state.error_dialog.message)); state.close_document(first); assert!(joins().contains(&east_unjoined), "{}", joins()); diff --git a/src/state/tests/opening_a_nametable.rs b/src/state/tests/opening_a_nametable.rs index e05f198fc..fad85da0e 100644 --- a/src/state/tests/opening_a_nametable.rs +++ b/src/state/tests/opening_a_nametable.rs @@ -11,14 +11,14 @@ use crate::state::{AppState, DocPayload, DocumentId, DocumentKind, LoadingState} fn open(state: &mut AppState, path: PathBuf) -> DocumentId { state.load_file(path); let deadline = Instant::now() + Duration::from_secs(30); - while state.load_receiver.is_some() && Instant::now() < deadline { + while state.io_queue.load_receiver.is_some() && Instant::now() < deadline { state.poll_load_result(); std::thread::sleep(Duration::from_millis(5)); } assert!( matches!(state.loading, LoadingState::Idle), "the load did not finish: {}", - state.error_dialog_message + state.error_dialog.message ); state.active_document.expect("the .nametable opened") } @@ -47,12 +47,12 @@ fn save(state: &mut AppState, path: PathBuf) -> Result, String> { state.clear_error(); assert!(state.save_active_document_as(path.clone())); let deadline = Instant::now() + Duration::from_secs(30); - while state.save_receiver.is_some() && Instant::now() < deadline { + while state.io_queue.save_receiver.is_some() && Instant::now() < deadline { state.poll_save_result(); std::thread::sleep(Duration::from_millis(5)); } - if !state.error_dialog_message.is_empty() { - return Err(state.error_dialog_message.clone()); + if !state.error_dialog.message.is_empty() { + return Err(state.error_dialog.message.clone()); } std::fs::read(&path).map_err(|e| e.to_string()) } diff --git a/src/state/tests/opening_a_rel.rs b/src/state/tests/opening_a_rel.rs index 0e0c3eaf5..18f00b41c 100644 --- a/src/state/tests/opening_a_rel.rs +++ b/src/state/tests/opening_a_rel.rs @@ -102,14 +102,14 @@ fn one_sound_hash_list() -> Vec { fn open(state: &mut AppState, path: PathBuf) -> DocumentId { state.load_file(path); let deadline = Instant::now() + Duration::from_secs(30); - while state.load_receiver.is_some() && Instant::now() < deadline { + while state.io_queue.load_receiver.is_some() && Instant::now() < deadline { state.poll_load_result(); std::thread::sleep(Duration::from_millis(5)); } assert!( matches!(state.loading, LoadingState::Idle), "the load did not finish: {}", - state.error_dialog_message + state.error_dialog.message ); let doc = state .active_document @@ -147,7 +147,7 @@ fn groups(rel: &RelDocument) -> Vec<(&str, Vec)> { fn saved(state: &mut AppState, path: PathBuf) -> Vec { assert!(state.save_active_document_as(path.clone())); let deadline = Instant::now() + Duration::from_secs(30); - while state.save_receiver.is_some() && Instant::now() < deadline { + while state.io_queue.save_receiver.is_some() && Instant::now() < deadline { state.poll_save_result(); std::thread::sleep(Duration::from_millis(5)); } diff --git a/src/state/tests/opening_a_ttpf.rs b/src/state/tests/opening_a_ttpf.rs index 1aa7fbf78..e1dbc9a84 100644 --- a/src/state/tests/opening_a_ttpf.rs +++ b/src/state/tests/opening_a_ttpf.rs @@ -78,7 +78,7 @@ pub(in crate::state) fn pack(rgb565: u16) -> Vec { pub(in crate::state) fn open(state: &mut AppState, path: PathBuf) -> DocumentId { state.load_file(path.clone()); let deadline = Instant::now() + Duration::from_secs(30); - while state.load_receiver.is_some() && Instant::now() < deadline { + while state.io_queue.load_receiver.is_some() && Instant::now() < deadline { state.poll_load_result(); std::thread::sleep(Duration::from_millis(5)); } @@ -86,7 +86,7 @@ pub(in crate::state) fn open(state: &mut AppState, path: PathBuf) -> DocumentId matches!(state.loading, LoadingState::Idle), "{}: {}", path.display(), - state.error_dialog_message + state.error_dialog.message ); state .active_document @@ -104,7 +104,7 @@ pub(in crate::state) fn save_as(state: &mut AppState, doc: DocumentId, to: &Path state.set_active_document(doc); let started = state.save_active_document_as(to.to_path_buf()); let until = Instant::now() + Duration::from_secs(60); - while state.save_receiver.is_some() { + while state.io_queue.save_receiver.is_some() { assert!(Instant::now() < until, "the save did not finish"); state.poll_save_result(); std::thread::sleep(Duration::from_millis(5)); @@ -159,7 +159,7 @@ fn a_ttpf_texture_replaced_from_an_image_saves_as_a_new_pack_that_reads_it_back( assert!( save_as(&mut state, doc, &saved), "{}", - state.error_dialog_message + state.error_dialog.message ); let reopened = or_io::gta6::TexturePack::open(&saved).expect("the saved pack opens"); let texture = reopened @@ -278,7 +278,7 @@ pub(in crate::state) fn named_by_the_rules(state: &mut AppState) { } state.poll_jobs(); assert!( - state.texture_naming.is_empty(), + state.gta6_finders.texture_naming.is_empty(), "a naming run is still running" ); } diff --git a/src/state/tests/opening_a_ydd.rs b/src/state/tests/opening_a_ydd.rs index 20a542ab8..12b630d85 100644 --- a/src/state/tests/opening_a_ydd.rs +++ b/src/state/tests/opening_a_ydd.rs @@ -46,7 +46,7 @@ pub(in crate::state) fn node_at(state: &mut AppState, game: DocumentId, path: &s state.request_expand(game, node); wait_until("the tree's expansion", || { state.poll_expansions(); - !state.expander.is_in_flight(game, node) + !state.bg.expander.is_in_flight(game, node) }); let DocPayload::Rpf(rpf) = &state.document(game).expect("the game root").payload else { unreachable!("the game root is an archive document"); @@ -69,7 +69,7 @@ pub(in crate::state) fn node_at(state: &mut AppState, game: DocumentId, path: &s pub(in crate::state) fn finish_load(state: &mut AppState) -> Result { wait_until("the load", || { state.poll_load_result(); - state.load_receiver.is_none() + state.io_queue.load_receiver.is_none() }); match &state.loading { LoadingState::Error(message) => Err(message.clone()), diff --git a/src/state/tests/opening_an_awc.rs b/src/state/tests/opening_an_awc.rs index 05fd230ba..bc2f99296 100644 --- a/src/state/tests/opening_an_awc.rs +++ b/src/state/tests/opening_an_awc.rs @@ -98,14 +98,14 @@ pub(in crate::state) fn three_streams() -> Vec { fn open(state: &mut AppState, path: PathBuf) -> DocumentId { state.load_file(path); let deadline = Instant::now() + Duration::from_secs(30); - while state.load_receiver.is_some() && Instant::now() < deadline { + while state.io_queue.load_receiver.is_some() && Instant::now() < deadline { state.poll_load_result(); std::thread::sleep(Duration::from_millis(5)); } assert!( matches!(state.loading, LoadingState::Idle), "the load did not finish: {}", - state.error_dialog_message + state.error_dialog.message ); let doc = state .active_document @@ -182,7 +182,7 @@ fn a_replaced_stream_saves_and_reopens_equal() { let path = dir.path().join("saved.awc"); assert!(state.save_active_document_as(path.clone())); let deadline = Instant::now() + Duration::from_secs(30); - while state.save_receiver.is_some() && Instant::now() < deadline { + while state.io_queue.save_receiver.is_some() && Instant::now() < deadline { state.poll_save_result(); std::thread::sleep(Duration::from_millis(5)); } @@ -248,7 +248,7 @@ fn a_replaced_adpcm_stream_saves_and_reopens_within_adpcm_error() { let path = dir.path().join("saved.awc"); assert!(state.save_active_document_as(path.clone())); let deadline = Instant::now() + Duration::from_secs(30); - while state.save_receiver.is_some() && Instant::now() < deadline { + while state.io_queue.save_receiver.is_some() && Instant::now() < deadline { state.poll_save_result(); std::thread::sleep(Duration::from_millis(5)); } @@ -425,7 +425,7 @@ fn a_replaced_two_channel_adpcm_stream_saves_and_decodes_continuous() { let path = dir.path().join("saved.awc"); assert!(state.save_active_document_as(path.clone())); let deadline = Instant::now() + Duration::from_secs(30); - while state.save_receiver.is_some() && Instant::now() < deadline { + while state.io_queue.save_receiver.is_some() && Instant::now() < deadline { state.poll_save_result(); std::thread::sleep(Duration::from_millis(5)); } diff --git a/src/state/tests/opening_an_rpf9_archive.rs b/src/state/tests/opening_an_rpf9_archive.rs index 2fc3a43f5..b05551720 100644 --- a/src/state/tests/opening_an_rpf9_archive.rs +++ b/src/state/tests/opening_an_rpf9_archive.rs @@ -115,7 +115,7 @@ fn load(state: &mut AppState, path: PathBuf) { /// Wait for the loads in flight to end. pub(in crate::state) fn settle(state: &mut AppState) { let deadline = Instant::now() + Duration::from_secs(30); - while state.load_receiver.is_some() || !state.pending_loads.is_empty() { + while state.io_queue.load_receiver.is_some() || !state.io_queue.pending_loads.is_empty() { state.poll_load_result(); assert!(Instant::now() < deadline, "the load never ended"); std::thread::sleep(Duration::from_millis(5)); @@ -126,11 +126,11 @@ pub(in crate::state) fn settle(state: &mut AppState) { pub(in crate::state) fn scanned(state: &mut AppState, path: PathBuf) -> DocumentId { load(state, path); let doc = (state.active_document) - .unwrap_or_else(|| panic!("the archive did not open: {}", state.error_dialog_message)); + .unwrap_or_else(|| panic!("the archive did not open: {}", state.error_dialog.message)); let Some(DocPayload::Rpf9(scan)) = state.document(doc).map(|d| &d.payload) else { panic!( "not a GTA VI archive document: {}", - state.error_dialog_message + state.error_dialog.message ); }; let deadline = Instant::now() + Duration::from_secs(30); diff --git a/src/state/tests/opening_an_unknown_file.rs b/src/state/tests/opening_an_unknown_file.rs index e878d208a..ff2f55225 100644 --- a/src/state/tests/opening_an_unknown_file.rs +++ b/src/state/tests/opening_an_unknown_file.rs @@ -8,14 +8,14 @@ use crate::state::{AppState, DocPayload, DocumentId, DocumentKind, HexDocument, fn wait(state: &mut AppState, what: &str) { let deadline = Instant::now() + Duration::from_secs(30); - while state.load_receiver.is_some() && Instant::now() < deadline { + while state.io_queue.load_receiver.is_some() && Instant::now() < deadline { state.poll_load_result(); std::thread::sleep(Duration::from_millis(5)); } assert!( - matches!(state.loading, LoadingState::Idle) && state.error_dialog_message.is_empty(), + matches!(state.loading, LoadingState::Idle) && state.error_dialog.message.is_empty(), "{what}: {}", - state.error_dialog_message + state.error_dialog.message ); } @@ -53,7 +53,7 @@ fn a_binary_dat_with_no_reader_opens_as_hex_under_its_refusal() { let saved = dir.path().join("saved.dat"); state.save_active_document_as(saved.clone()); let deadline = Instant::now() + Duration::from_secs(30); - while state.save_receiver.is_some() && Instant::now() < deadline { + while state.io_queue.save_receiver.is_some() && Instant::now() < deadline { state.poll_save_result(); std::thread::sleep(Duration::from_millis(5)); } @@ -129,7 +129,7 @@ fn an_unknown_extension_holding_text_opens_as_editable_text() { let saved = dir.path().join("saved.zzlist"); state.save_active_document_as(saved.clone()); let deadline = Instant::now() + Duration::from_secs(30); - while state.save_receiver.is_some() && Instant::now() < deadline { + while state.io_queue.save_receiver.is_some() && Instant::now() < deadline { state.poll_save_result(); std::thread::sleep(Duration::from_millis(5)); } diff --git a/src/state/tests/opening_metadata_without_a_schema.rs b/src/state/tests/opening_metadata_without_a_schema.rs index 252cfd875..1b5ee8b5c 100644 --- a/src/state/tests/opening_metadata_without_a_schema.rs +++ b/src/state/tests/opening_metadata_without_a_schema.rs @@ -38,7 +38,7 @@ fn saved(state: &mut AppState, doc: DocumentId, path: &str) -> Vec { "{path}: no save" ); let deadline = Instant::now() + Duration::from_secs(30); - while state.save_receiver.is_some() && Instant::now() < deadline { + while state.io_queue.save_receiver.is_some() && Instant::now() < deadline { state.poll_save_result(); std::thread::sleep(Duration::from_millis(5)); } diff --git a/src/state/tests/opening_world_dat.rs b/src/state/tests/opening_world_dat.rs index b679c1622..24dc88380 100644 --- a/src/state/tests/opening_world_dat.rs +++ b/src/state/tests/opening_world_dat.rs @@ -60,7 +60,7 @@ fn distant_lights() -> Vec { fn open(state: &mut AppState, path: PathBuf) -> DocumentId { state.load_file(path.clone()); let deadline = Instant::now() + Duration::from_secs(30); - while state.load_receiver.is_some() && Instant::now() < deadline { + while state.io_queue.load_receiver.is_some() && Instant::now() < deadline { state.poll_load_result(); std::thread::sleep(Duration::from_millis(5)); } @@ -68,7 +68,7 @@ fn open(state: &mut AppState, path: PathBuf) -> DocumentId { matches!(state.loading, LoadingState::Idle), "{}: {}", path.display(), - state.error_dialog_message + state.error_dialog.message ); state .active_document @@ -78,7 +78,7 @@ fn open(state: &mut AppState, path: PathBuf) -> DocumentId { fn saved_as(state: &mut AppState, path: &Path) -> Vec { assert!(state.save_active_document_as(path.to_path_buf())); let deadline = Instant::now() + Duration::from_secs(30); - while state.save_receiver.is_some() && Instant::now() < deadline { + while state.io_queue.save_receiver.is_some() && Instant::now() < deadline { state.poll_save_result(); std::thread::sleep(Duration::from_millis(5)); } @@ -144,7 +144,7 @@ fn distant_lights_open_from_an_archive_and_from_disk_and_save_their_bytes() { }; state.open_rpf_entry(archive_doc, entry); let deadline = Instant::now() + Duration::from_secs(30); - while state.load_receiver.is_some() && Instant::now() < deadline { + while state.io_queue.load_receiver.is_some() && Instant::now() < deadline { state.poll_load_result(); std::thread::sleep(Duration::from_millis(5)); } @@ -153,7 +153,7 @@ fn distant_lights_open_from_an_archive_and_from_disk_and_save_their_bytes() { state.document(from_archive).map(|d| d.kind()), Some(DocumentKind::DistantLights), "{}", - state.error_dialog_message + state.error_dialog.message ); let path = dir.path().join("distantlights_hd.dat"); diff --git a/src/state/tests/opus_on_a_worker.rs b/src/state/tests/opus_on_a_worker.rs index bf251ce0c..1665778c4 100644 --- a/src/state/tests/opus_on_a_worker.rs +++ b/src/state/tests/opus_on_a_worker.rs @@ -139,7 +139,7 @@ fn a_scanned_container_s_replaced_stream_is_saved_by_save_as_as_the_container_re let saved = dir.path().join("replaced.awc"); assert!(state.save_active_document_as(saved.clone())); let deadline = Instant::now() + Duration::from_secs(30); - while state.extract_jobs.is_running() { + while state.bg.extract_jobs.is_running() { state.poll_extract_job(); assert!(Instant::now() < deadline, "the save never ended"); std::thread::sleep(Duration::from_millis(5)); diff --git a/src/state/tests/previewing_a_video.rs b/src/state/tests/previewing_a_video.rs index d15fbebe5..7177118fc 100644 --- a/src/state/tests/previewing_a_video.rs +++ b/src/state/tests/previewing_a_video.rs @@ -31,7 +31,7 @@ const SHIPPED_BINK2: (&str, &str) = ("update/update.rpf", "x64/movies/rockstar_l fn open(state: &mut AppState, path: PathBuf) -> DocumentId { state.load_file(path); let deadline = Instant::now() + Duration::from_secs(30); - while state.load_receiver.is_some() && Instant::now() < deadline { + while state.io_queue.load_receiver.is_some() && Instant::now() < deadline { state.poll_load_result(); std::thread::sleep(Duration::from_millis(5)); } diff --git a/src/state/tests/reordering_mods_from_the_app.rs b/src/state/tests/reordering_mods_from_the_app.rs index 13e02f55a..f2d56aa9e 100644 --- a/src/state/tests/reordering_mods_from_the_app.rs +++ b/src/state/tests/reordering_mods_from_the_app.rs @@ -43,7 +43,7 @@ fn state_for(root: &Path, mode: EditMode) -> AppState { } fn winner(state: &AppState) -> &str { - let conflicts = &state.mod_manager.resolution.conflicts; + let conflicts = &state.bg.mod_manager.resolution.conflicts; assert_eq!(conflicts.len(), 1, "the one shared entry: {conflicts:?}"); &conflicts[0].winner } @@ -85,7 +85,7 @@ fn a_mod_moves_to_mods_underscore_only_when_the_mode_permits_and_the_user_confir state.ask_toggle_mod("SmallProps"); assert_eq!( - state.mod_manager.pending_move, None, + state.bg.mod_manager.pending_move, None, "read only does not even ask" ); assert!(!errors(&state).is_empty(), "and says why"); @@ -93,7 +93,7 @@ fn a_mod_moves_to_mods_underscore_only_when_the_mode_permits_and_the_user_confir state.set_edit_mode(EditMode::Overlay); state.ask_toggle_mod("SmallProps"); - let asked = state.mod_manager.pending_move.clone().expect("it asks"); + let asked = state.bg.mod_manager.pending_move.clone().expect("it asks"); assert_eq!( asked, PendingModMove { @@ -110,7 +110,7 @@ fn a_mod_moves_to_mods_underscore_only_when_the_mode_permits_and_the_user_confir ); state.answer_mod_move(false); - assert_eq!(state.mod_manager.pending_move, None); + assert_eq!(state.bg.mod_manager.pending_move, None); assert!( root.join("mods/SmallProps").is_dir(), "No leaves it where it is" @@ -120,12 +120,12 @@ fn a_mod_moves_to_mods_underscore_only_when_the_mode_permits_and_the_user_confir state.answer_mod_move(true); assert!(!root.join("mods/SmallProps").exists()); assert!(root.join("mods_/SmallProps").join(SHARED).is_file()); - let parked = (state.mod_manager.mods.iter()) + let parked = (state.bg.mod_manager.mods.iter()) .find(|m| m.name == "SmallProps") .expect("it is still listed"); assert_eq!(parked.place, or_title::mods::ModPlace::Parked); assert!( - state.mod_manager.resolution.conflicts.is_empty(), + state.bg.mod_manager.resolution.conflicts.is_empty(), "a disabled mod wins nothing" ); diff --git a/src/state/tests/search_results_that_open.rs b/src/state/tests/search_results_that_open.rs index 99f4d3c49..ce50c6e6d 100644 --- a/src/state/tests/search_results_that_open.rs +++ b/src/state/tests/search_results_that_open.rs @@ -250,18 +250,23 @@ fn searched_for(root: &Path, hits: usize) -> (AppState, DocumentId) { under: String::new(), max_hits: 0, }; - state.search.start( + state.find.session.start( request, root.to_path_buf(), Arc::new(NoOpCryptoProvider::new()), ); let deadline = Instant::now() + Duration::from_secs(30); - while state.search.is_running() { + while state.find.session.is_running() { assert!(Instant::now() < deadline, "the search never finished"); - state.search.poll(); + state.find.session.poll(); std::thread::sleep(Duration::from_millis(5)); } - assert_eq!(state.search.hits.len(), hits, "{:?}", state.search.hits); + assert_eq!( + state.find.session.hits.len(), + hits, + "{:?}", + state.find.session.hits + ); (state, install) } @@ -271,7 +276,7 @@ fn a_search_panel_result_inside_a_dlc_sub_pack_in_the_title_update_opens_from_it let root = install_with_a_sub_pack_in_the_title_update(); let (mut state, install) = searched_for(root.path(), 1); assert_eq!( - crate::state::search_session::hit_path(&state.search.hits[0]), + crate::state::search_session::hit_path(&state.find.session.hits[0]), NOTES, "the hit names the whole chain of archives holding the file" ); @@ -296,7 +301,7 @@ fn extract_writes_every_selected_result_through_the_job_and_asks_before_replacin let (mut state, _install) = searched(root.path()); let mut screen = Screen::new(crate::ui::panels::search::draw); let selected = |state: &AppState| -> Vec { - let rows = state.search.selection.selected_ids(RESULTS); + let rows = state.find.session.selection.selected_ids(RESULTS); rows.into_iter() .filter_map(|row| row.row().map(|i| i as usize)) .collect() @@ -334,7 +339,7 @@ fn extract_writes_every_selected_result_through_the_job_and_asks_before_replacin }; state.go_to_search_hits(&rows, extract()); screen.until(&mut state, "the extraction never wrote both", |state| { - !state.extract_jobs.is_running() + !state.bg.extract_jobs.is_running() && dest.path().join("one.txt").is_file() && dest.path().join("two.txt").is_file() }); @@ -349,10 +354,10 @@ fn extract_writes_every_selected_result_through_the_job_and_asks_before_replacin state.go_to_search_hits(&rows, extract()); screen.until(&mut state, "extracting again did not ask", |state| { - state.extract_jobs.clash.is_some() + state.bg.extract_jobs.clash.is_some() }); assert_eq!( - state.extract_jobs.clash.as_ref().map(|c| c.clashes), + state.bg.extract_jobs.clash.as_ref().map(|c| c.clashes), Some(2) ); } diff --git a/src/state/tests/settings_recents_and_small_editor_fixes.rs b/src/state/tests/settings_recents_and_small_editor_fixes.rs index 182c300b1..d682a607c 100644 --- a/src/state/tests/settings_recents_and_small_editor_fixes.rs +++ b/src/state/tests/settings_recents_and_small_editor_fixes.rs @@ -102,12 +102,12 @@ fn questions() -> Vec<(&'static str, Ask)> { ), ( "changed on disk", - Box::new(|state: &mut AppState| state.reload_conflicts.push("a.ypt".into())), + Box::new(|state: &mut AppState| state.prompts.reload_conflicts.push("a.ypt".into())), ), ( "a delete", Box::new(|state: &mut AppState| { - state.pending_delete = Some(PendingDelete { + state.prompts.delete = Some(PendingDelete { doc_id: crate::state::DocumentId(0), node_id: crate::state::RpfNodeId(0), name: "old.ydr".into(), @@ -121,7 +121,7 @@ fn questions() -> Vec<(&'static str, Ask)> { ( "an extraction's clash", Box::new(|state: &mut AppState| { - state.extract_jobs.clash = Some(ExtractClash { + state.bg.extract_jobs.clash = Some(ExtractClash { doc_id: crate::state::DocumentId(0), nodes: Vec::new(), dest: "out".into(), @@ -137,7 +137,7 @@ fn questions() -> Vec<(&'static str, Ask)> { ( "a base-game write", Box::new(|state: &mut AppState| { - state.pending_retail_edit = Some(PendingRetailEditPrompt { + state.prompts.retail_edit = Some(PendingRetailEditPrompt { action: PendingRetailEdit::SaveLooseFile { doc_id: crate::state::DocumentId(0), }, @@ -149,13 +149,13 @@ fn questions() -> Vec<(&'static str, Ask)> { ( "the export fixes", Box::new(|state: &mut AppState| { - state.pending_export_fixes = Some(PendingExportFixes::DragOut) + state.prompts.export_fixes = Some(PendingExportFixes::DragOut) }), ), ( "an Enhanced file", Box::new(|state: &mut AppState| { - state.pending_enhanced_open = Some(PendingEnhancedOpen { + state.prompts.enhanced_open = Some(PendingEnhancedOpen { path: "enhanced.ydr".into(), game: Game::GtaVEnhanced, version: 0, @@ -169,7 +169,7 @@ fn questions() -> Vec<(&'static str, Ask)> { ), ( "a refused write", - Box::new(|state: &mut AppState| state.refused_write = Some("x64a.rpf".into())), + Box::new(|state: &mut AppState| state.prompts.refused_write = Some("x64a.rpf".into())), ), ( "an error", @@ -257,7 +257,7 @@ fn clearing_the_active_games_folder_closes_its_install_once_its_unsaved_work_is_ state.document(file).is_some_and(|d| d.dirty), "Clear dropped a file opened from the install before the user answered" ); - assert!(state.pending_close.is_some(), "Clear asked nothing"); + assert!(state.prompts.close.is_some(), "Clear asked nothing"); state.answer_close(CloseAnswer::Cancel); assert!(state.document(install).is_some()); assert!( diff --git a/src/state/tests/small_faults_in_the_default_views_menus_and_keys.rs b/src/state/tests/small_faults_in_the_default_views_menus_and_keys.rs index ed125a224..a346942ac 100644 --- a/src/state/tests/small_faults_in_the_default_views_menus_and_keys.rs +++ b/src/state/tests/small_faults_in_the_default_views_menus_and_keys.rs @@ -154,7 +154,7 @@ fn delete_pressed_with_several_rows_selected_says_why_nothing_was_deleted() { "the key refused and said nothing: {said:?}" ); assert!( - state.pending_delete.is_none(), + state.prompts.delete.is_none(), "a delete was asked after all" ); } diff --git a/src/state/tests/tabs_that_behave_like_an_editors.rs b/src/state/tests/tabs_that_behave_like_an_editors.rs index 1bb624c27..989c9be74 100644 --- a/src/state/tests/tabs_that_behave_like_an_editors.rs +++ b/src/state/tests/tabs_that_behave_like_an_editors.rs @@ -163,7 +163,7 @@ fn settle(state: &mut AppState) { state.poll_load_result(); state.poll_expansions(); state.tick_navigation(); - if state.load_receiver.is_none() && state.navigation.pending_place().is_none() { + if state.io_queue.load_receiver.is_none() && state.navigation.pending_place().is_none() { return; } assert!(Instant::now() < deadline, "the open never finished"); @@ -309,7 +309,7 @@ fn every_tab_has_a_close_button_and_those_that_do_not_fit_are_in_a_list() { state.document_mut(only).expect("open").mark_edited(); screen.click(&mut state, close, egui::PointerButton::Primary, 1); assert!( - state.document(only).is_some() && state.pending_close.is_some(), + state.document(only).is_some() && state.prompts.close.is_some(), "the close button dropped unsaved work without asking" ); state.answer_close(crate::state::CloseAnswer::DontSave); @@ -383,7 +383,7 @@ fn every_unsaved_tab_carries_one_mark_and_pose_keys_not_yet_baked_are_unsaved() None, ); state.preview_scene.set_clip(clip, 0x1234); - state.anim_edits.set( + state.animation.edits.set( or_anim::EditKey { bone: 0, track: or_anim::EditTrack::Translation, diff --git a/src/state/tests/the_animation_preview_draws_what_its_sources_hold.rs b/src/state/tests/the_animation_preview_draws_what_its_sources_hold.rs index 72961acc8..a78599287 100644 --- a/src/state/tests/the_animation_preview_draws_what_its_sources_hold.rs +++ b/src/state/tests/the_animation_preview_draws_what_its_sources_hold.rs @@ -185,17 +185,21 @@ fn bone_x(state: &AppState, doc: DocumentId, bone: usize) -> (String, or_editor: /// What the preview poses of bone 1: its bind translation along x, and where its world matrix puts it along x. fn posed(state: &AppState) -> (f32, f32) { - let skeleton = state.anim.skeleton().expect("a skeleton is bound"); + let skeleton = state + .animation + .session + .skeleton() + .expect("a skeleton is bound"); ( skeleton.bones[1].bind_translation.x, - state.anim.world_matrices[1].w_axis.x, + state.animation.session.world_matrices[1].w_axis.x, ) } impl Previewing { fn needs_rebuild(&self) -> bool { let epoch = self.state.skeleton_epoch(); - (self.state.anim).needs_rebuild(&self.state.preview_scene, epoch) + (self.state.animation.session).needs_rebuild(&self.state.preview_scene, epoch) } } @@ -298,12 +302,12 @@ fn the_meshes_are_built_again_once_the_session_that_poses_them_is() { /// The clip's own working range and Loop, trimmed and turned on: what a user sets, and the preview must keep. fn trimmed_and_looping(p: &mut Previewing, target: &str) -> TimeRange { assert!( - !p.state.anim_transport.is_looping(), + !p.state.animation.transport.is_looping(), "{target}: the clip's own loop" ); let trimmed = TimeRange::new(0.25, 0.75); - p.state.anim_transport.set_range(trimmed); - p.state.anim_transport.set_looping(true); + p.state.animation.transport.set_range(trimmed); + p.state.animation.transport.set_looping(true); trimmed } @@ -324,11 +328,11 @@ fn an_edit_to_the_skeleton_source_keeps_the_transports_working_range_and_loop() p.state.tick_animation(); assert_eq!(posed(&p.state), (5.0, 5.0), "{target}: the session"); assert_eq!( - p.state.anim_transport.range, trimmed, + p.state.animation.transport.range, trimmed, "{target}: the working range after an edit of a bone" ); assert!( - p.state.anim_transport.is_looping(), + p.state.animation.transport.is_looping(), "{target}: Loop after an edit of a bone" ); } @@ -349,11 +353,11 @@ fn a_key() -> (or_anim::EditKey, or_anim::EditValue) { /// What the Insert key button does, on the clip's document. fn insert_a_key(p: &mut Previewing) { - let before = p.state.anim_edits.clone(); + let before = p.state.animation.edits.clone(); let (key, value) = a_key(); - assert!(p.state.anim_edits.set(key, value)); + assert!(p.state.animation.edits.set(key, value)); p.state.push_anim_edit("insert key", before); - p.state.anim.invalidate(); + p.state.animation.session.invalidate(); } /// What the Edit clip fields section does when `edit` changes the clip's fields. @@ -370,7 +374,7 @@ fn edit_the_clip_fields( other: before, }; p.state.record(p.clips, "Edit clip fields", change); - p.state.anim.invalidate(); + p.state.animation.session.invalidate(); } fn rename_the_clip(p: &mut Previewing) { @@ -387,25 +391,25 @@ fn the_rebuilds_that_choose_nothing() -> Vec { ("Insert key", insert_a_key), ("Clear key", |p| { insert_a_key(p); - let before = p.state.anim_edits.clone(); - assert!(p.state.anim_edits.remove(&a_key().0)); + let before = p.state.animation.edits.clone(); + assert!(p.state.animation.edits.remove(&a_key().0)); p.state.push_anim_edit("clear key", before); - p.state.anim.invalidate(); + p.state.animation.session.invalidate(); }), ("Discard edits", |p| { insert_a_key(p); - let before = p.state.anim_edits.clone(); - p.state.anim_edits.clear(); + let before = p.state.animation.edits.clone(); + p.state.animation.edits.clear(); p.state.push_anim_edit("discard edits", before); - p.state.anim.invalidate(); + p.state.animation.session.invalidate(); }), ("the root-motion toggle", |p| { p.state.preview_scene.apply_root_motion ^= true; - p.state.anim.invalidate(); + p.state.animation.session.invalidate(); }), ("Allow mismatched skeleton", |p| { p.state.preview_scene.allow_mismatched_skeleton ^= true; - p.state.anim.invalidate(); + p.state.animation.session.invalidate(); }), ("a mesh source added", |p| { let source = MeshSource { @@ -413,7 +417,7 @@ fn the_rebuilds_that_choose_nothing() -> Vec { entry: None, }; p.state.preview_scene.add_mesh(source); - p.state.anim.invalidate(); + p.state.animation.session.invalidate(); }), ("a mesh source removed", |p| { let source = MeshSource { @@ -422,7 +426,7 @@ fn the_rebuilds_that_choose_nothing() -> Vec { }; p.state.preview_scene.add_mesh(source); p.state.preview_scene.remove_mesh(source); - p.state.anim.invalidate(); + p.state.animation.session.invalidate(); }), ("a clip field edit", rename_the_clip), ("the undo of a clip field edit", |p| { @@ -442,11 +446,11 @@ fn the_rebuilds_that_choose_nothing() -> Vec { }), ("the clip chosen again", |p| { p.state.preview_scene.set_clip(p.clips, CLIP); - p.state.anim.invalidate(); + p.state.animation.session.invalidate(); }), ("Choose automatically landing on the same skeleton", |p| { p.state.preview_scene.unpin_skeleton(); - p.state.anim.invalidate(); + p.state.animation.session.invalidate(); }), ] } @@ -469,11 +473,11 @@ fn a_rebuild_that_chooses_nothing_new_keeps_the_transports_working_range_and_loo p.state.tick_animation(); assert!(!p.needs_rebuild(), "{target}: {name} is built"); assert_eq!( - p.state.anim_transport.range, trimmed, + p.state.animation.transport.range, trimmed, "{target}: the working range after {name}" ); assert!( - p.state.anim_transport.is_looping(), + p.state.animation.transport.is_looping(), "{target}: Loop after {name}" ); } @@ -491,7 +495,7 @@ fn choose_another_rig(p: &mut Previewing) { let second = open(&mut p.state, &path); let source = SkeletonSource::Drawable(second); p.state.preview_scene.pin_skeleton(Some(source)); - p.state.anim.invalidate(); + p.state.animation.session.invalidate(); } /// ⚠ What a rebuild keeps is for the clip and the skeleton source it plays: choosing either is a @@ -501,7 +505,7 @@ fn choosing_another_clip_or_skeleton_source_hands_the_transport_back_to_the_clip let choices: [Action; 2] = [ ("another clip", |p| { p.state.preview_scene.set_clip(p.clips, OTHER_CLIP); - p.state.anim.invalidate(); + p.state.animation.session.invalidate(); }), ("another skeleton source", choose_another_rig), ]; @@ -509,26 +513,26 @@ fn choosing_another_clip_or_skeleton_source_hands_the_transport_back_to_the_clip for (target, game) in TARGETS { let mut p = previewing_a_rig(game); p.state.tick_animation(); - let clips_own = p.state.anim_transport; + let clips_own = p.state.animation.transport; trimmed_and_looping(&mut p, target); choose(&mut p); p.state.tick_animation(); assert_eq!( - p.state.anim_transport.range, clips_own.range, + p.state.animation.transport.range, clips_own.range, "{target}: the working range after choosing {name}" ); assert!( - !p.state.anim_transport.is_looping(), + !p.state.animation.transport.is_looping(), "{target}: Loop after choosing {name}" ); // The transport is the new choice's now, and a rebuild for it keeps what is set. let trimmed = trimmed_and_looping(&mut p, target); - p.state.anim.invalidate(); + p.state.animation.session.invalidate(); p.state.tick_animation(); assert_eq!( - p.state.anim_transport.range, trimmed, + p.state.animation.transport.range, trimmed, "{target}: the working range on {name}, rebuilt" ); } @@ -546,37 +550,40 @@ fn a_clip_field_edit_moves_the_transports_length_and_keeps_the_users_range_and_l let mut fields = (p.state.clip_field_snapshot(p.clips, CLIP)).expect("the clip"); fields.end_time = end_time; assert!(p.state.apply_clip_fields(p.clips, CLIP, &fields)); - p.state.anim.invalidate(); + p.state.animation.session.invalidate(); p.state.tick_animation(); }; - p.state.anim_transport.set_looping(true); + p.state.animation.transport.set_looping(true); set_the_end(&mut p, 0.5); assert_eq!( - p.state.anim_transport.range, + p.state.animation.transport.range, TimeRange::from_duration(0.5), "{target}: an untrimmed range after the clip is shortened" ); set_the_end(&mut p, 1.0); assert_eq!( - p.state.anim_transport.range, + p.state.animation.transport.range, TimeRange::from_duration(1.0), "{target}: an untrimmed range after the clip is lengthened" ); - p.state.anim_transport.set_range(TimeRange::new(0.25, 0.75)); + p.state + .animation + .transport + .set_range(TimeRange::new(0.25, 0.75)); set_the_end(&mut p, 0.5); assert_eq!( - p.state.anim_transport.bounds, + p.state.animation.transport.bounds, TimeRange::from_duration(0.5), "{target}: the length after the clip is shortened" ); assert_eq!( - p.state.anim_transport.range, + p.state.animation.transport.range, TimeRange::new(0.25, 0.5), "{target}: a trimmed range after the clip is shortened" ); - assert!(p.state.anim_transport.is_looping(), "{target}: Loop"); + assert!(p.state.animation.transport.is_looping(), "{target}: Loop"); } } @@ -588,8 +595,8 @@ fn the_clips_looped_field_sets_the_transports_loop_when_it_changes_and_not_other let mut p = previewing_a_rig(game); p.state.tick_animation(); let trimmed = trimmed_and_looping(&mut p, target); - p.state.anim_transport.set_looping(false); - let loops = |p: &Previewing| p.state.anim_transport.is_looping(); + p.state.animation.transport.set_looping(false); + let loops = |p: &Previewing| p.state.animation.transport.is_looping(); // ⚠ A frame seals the edits, or the three that follow fold into one step of the history. edit_the_clip_fields(&mut p, |fields| fields.looped = true); @@ -597,19 +604,19 @@ fn the_clips_looped_field_sets_the_transports_loop_when_it_changes_and_not_other p.state.tick_animation(); assert!(loops(&p), "{target}: Loop once the field is ticked"); assert_eq!( - p.state.anim_transport.range, trimmed, + p.state.animation.transport.range, trimmed, "{target}: the working range once the field is ticked" ); // The Loop button is the user's while the field stays as it is. - p.state.anim_transport.set_looping(false); + p.state.animation.transport.set_looping(false); rename_the_clip(&mut p); p.state.seal_edits(); p.state.tick_animation(); assert!(!loops(&p), "{target}: Loop after a rename, field ticked"); // The field changed, so it wins over the button. - p.state.anim_transport.set_looping(true); + p.state.animation.transport.set_looping(true); edit_the_clip_fields(&mut p, |fields| fields.looped = false); p.state.seal_edits(); p.state.tick_animation(); @@ -624,7 +631,7 @@ fn the_clips_looped_field_sets_the_transports_loop_when_it_changes_and_not_other assert!(!loops(&p), "{target}: Loop after the redo of the clear"); assert_eq!( - p.state.anim_transport.range, trimmed, + p.state.animation.transport.range, trimmed, "{target}: the working range after the edits of the field" ); } diff --git a/src/state/tests/the_default_views_in_a_modders_words.rs b/src/state/tests/the_default_views_in_a_modders_words.rs index ad00cc515..143276b22 100644 --- a/src/state/tests/the_default_views_in_a_modders_words.rs +++ b/src/state/tests/the_default_views_in_a_modders_words.rs @@ -737,11 +737,14 @@ fn saved_into(state: &mut AppState, scratch: &Path, edit: Option) { edit_the_contents(state, doc, 6.0); } let until = std::time::Instant::now() + std::time::Duration::from_secs(60); - while state.save_receiver.is_some() && std::time::Instant::now() < until { + while state.io_queue.save_receiver.is_some() && std::time::Instant::now() < until { state.poll_save_result(); std::thread::sleep(std::time::Duration::from_millis(5)); } - assert!(state.save_receiver.is_none(), "the save never finished"); + assert!( + state.io_queue.save_receiver.is_none(), + "the save never finished" + ); } #[test] @@ -752,7 +755,7 @@ fn after_a_save_the_edition_row_says_the_version_the_file_now_has_and_no_other() assert!( !state.document(doc).expect("open").dirty, "the save left the document unsaved: {}", - state.error_dialog_message + state.error_dialog.message ); assert_eq!(edition(&mut state), format!("Legacy, version {written}")); } @@ -765,7 +768,7 @@ fn an_edit_made_while_a_save_is_written_leaves_the_edition_row_no_old_version_of assert!( state.document(doc).expect("open").dirty, "the edit made during the save was lost: {}", - state.error_dialog_message + state.error_dialog.message ); let row = edition(&mut state); assert!( diff --git a/src/state/tests/the_dressed_ped.rs b/src/state/tests/the_dressed_ped.rs index e16b0aa49..f2cda136b 100644 --- a/src/state/tests/the_dressed_ped.rs +++ b/src/state/tests/the_dressed_ped.rs @@ -450,14 +450,15 @@ fn the_ped_wears_its_own_drawables_from_the_install_in_every_slot_nothing_select fn a_cook_that_lands_lets_a_model_ask_the_project_for_its_textures_again() { let mut state = AppState::from_prefs(Prefs::default()); state - .attempted_texture_project + .textures + .attempted_project .insert(crate::state::DocumentId(7)); state.took_recook(Recook::Cooked { source: PathBuf::from("logo.textures.src"), output: PathBuf::from("vfs/id/logo.ytd"), }); assert!( - state.attempted_texture_project.is_empty(), + state.textures.attempted_project.is_empty(), "a model opened before its textures were first cooked asks again" ); } @@ -482,7 +483,7 @@ fn a_file_a_recook_wrote_is_asked_about_as_refreshed_and_not_as_changed_by_someb output: cooked.clone(), }); assert_eq!( - state.reload_conflicts, + state.prompts.reload_conflicts, std::slice::from_ref(&cooked), "a tab with edits asks first" ); @@ -490,11 +491,11 @@ fn a_file_a_recook_wrote_is_asked_about_as_refreshed_and_not_as_changed_by_someb // Somebody else changing a file is not a refresh. let other = dir.path().join("other.ytd"); - state.reload_conflicts.push(other.clone()); + state.prompts.reload_conflicts.push(other.clone()); assert!(!state.workbench.refreshed.contains(&other)); state.answer_reload_conflicts(false); - assert!(state.reload_conflicts.is_empty()); + assert!(state.prompts.reload_conflicts.is_empty()); assert!( state.workbench.refreshed.is_empty(), "the answer forgets what was asked" diff --git a/src/state/tests/the_edit_mode_is_visible_and_honest.rs b/src/state/tests/the_edit_mode_is_visible_and_honest.rs index 5372bde05..3adbb7670 100644 --- a/src/state/tests/the_edit_mode_is_visible_and_honest.rs +++ b/src/state/tests/the_edit_mode_is_visible_and_honest.rs @@ -15,7 +15,7 @@ fn mounted_install() -> (tempfile::TempDir, PathBuf, AppState, DocumentId, RpfNo std::fs::create_dir_all(install.join("update")).expect("install dirs"); std::fs::write(install.join("gta5.exe"), b"an install marker").expect("marker"); let mut state = AppState::new(); - state.retail_edit_session_allow = false; + state.prompts.retail_edit_session_allow = false; state.prefs.edit_mode = EditMode::Everything; state.open_game_root(install.clone()); let doc = state.documents[0].id; @@ -110,7 +110,7 @@ fn a_base_game_yes_ends_when_the_menu_bar_switches_to_read_only() { assert!(state.rpf_add_folder(doc, update, "granted").is_err()); assert!( - state.pending_retail_edit.is_some(), + state.prompts.retail_edit.is_some(), "the first base-game write of a session asks" ); state.apply_pending_retail_edit(RetailEditDecision::YesSession); @@ -138,7 +138,7 @@ fn a_base_game_yes_ends_when_the_menu_bar_switches_to_read_only() { choose_in_menu_bar(&ctx, &mut state, EditMode::Everything); assert!(state.rpf_add_folder(doc, update, "asked_again").is_err()); assert!( - state.pending_retail_edit.is_some(), + state.prompts.retail_edit.is_some(), "switching back asks again rather than reviving the old Yes" ); choose_in_menu_bar(&ctx, &mut state, EditMode::ReadOnly); @@ -155,7 +155,7 @@ fn a_base_game_yes_ends_when_the_menu_bar_switches_to_read_only() { fn a_session_yes_never_outlives_the_mode_it_was_given_in() { let (_tmp, install, mut state, _doc, _update) = mounted_install(); let shipped = install.join("update"); - state.retail_edit_session_allow = true; + state.prompts.retail_edit_session_allow = true; for mode in [EditMode::ReadOnly, EditMode::Overlay] { state.prefs.edit_mode = mode; assert_eq!( @@ -174,7 +174,7 @@ fn a_refused_write_offers_to_change_the_mode() { state.prefs.edit_mode = EditMode::ReadOnly; assert!(state.rpf_add_folder(doc, update, "wanted").is_err()); assert_eq!( - state.refused_write.as_deref(), + state.prompts.refused_write.as_deref(), Some(install.join("update").as_path()), "the refusal offers the mode, naming what it refused" ); @@ -190,13 +190,13 @@ fn a_refused_write_offers_to_change_the_mode() { click(&ctx, &mut state, prompt, row(EditMode::Everything)); assert_eq!(state.prefs.edit_mode, EditMode::Everything); assert_eq!( - state.refused_write, None, + state.prompts.refused_write, None, "choosing a mode answers the offer" ); assert!(state.rpf_add_folder(doc, update, "wanted").is_err()); assert!( - state.pending_retail_edit.is_some(), + state.prompts.retail_edit.is_some(), "the base game still asks before its first write" ); state.apply_pending_retail_edit(RetailEditDecision::YesSession); diff --git a/src/state/tests/the_files_view_in_the_centre/keys.rs b/src/state/tests/the_files_view_in_the_centre/keys.rs index 3845524b9..2df80d8c1 100644 --- a/src/state/tests/the_files_view_in_the_centre/keys.rs +++ b/src/state/tests/the_files_view_in_the_centre/keys.rs @@ -99,7 +99,7 @@ fn delete_asks_before_anything_goes() { settled(&ctx, &mut state); key(&ctx, &mut state, egui::Key::End); pressed(&ctx, &mut state, delete_key()); - let asked = state.pending_delete.clone().expect("Delete asks first"); + let asked = state.prompts.delete.clone().expect("Delete asks first"); assert_eq!(asked.name, "notes.txt"); assert_eq!( listed(&state, doc).len(), @@ -128,7 +128,7 @@ fn the_files_view_deletes_on_the_key_the_user_bound_to_delete_and_no_other() { ); assert_eq!(pressed(&ctx, &mut state, delete_key()), None); assert!( - state.pending_delete.is_none(), + state.prompts.delete.is_none(), "the Files view asked to delete on Delete, which is bound to something else" ); assert_eq!(listed(&state, doc).len(), 4); @@ -136,13 +136,14 @@ fn the_files_view_deletes_on_the_key_the_user_bound_to_delete_and_no_other() { assert_eq!(pressed(&ctx, &mut state, f8), Some(Action::Delete)); assert_eq!( state - .pending_delete + .prompts + .delete .as_ref() .map(|asked| asked.name.as_str()), Some("notes.txt"), "the key Delete was bound to asks to delete" ); - state.pending_delete = None; + state.prompts.delete = None; frame(&ctx, &mut state, Vec::new()); // And Delete bound to another command runs that command, not a delete. @@ -158,6 +159,6 @@ fn the_files_view_deletes_on_the_key_the_user_bound_to_delete_and_no_other() { Some(Action::ShowGrid) ); assert_ne!(state.prefs.viewport.show_grid, grid); - assert!(state.pending_delete.is_none()); + assert!(state.prompts.delete.is_none()); assert_eq!(listed(&state, doc).len(), 4); } diff --git a/src/state/tests/the_front_door.rs b/src/state/tests/the_front_door.rs index 48e7a4601..76fe823fc 100644 --- a/src/state/tests/the_front_door.rs +++ b/src/state/tests/the_front_door.rs @@ -108,7 +108,7 @@ fn a_restart_opens_the_remembered_install_in_browse_with_its_tree_open() { ); let deadline = Instant::now() + Duration::from_secs(30); - while state.expander.is_in_flight(id, root) { + while state.bg.expander.is_in_flight(id, root) { assert!( Instant::now() < deadline, "the install's folder was never read" @@ -207,7 +207,8 @@ fn switching_the_game_asks_before_it_closes_a_file_opened_from_the_old_install() state.request_game_switch(Game::GtaVEnhanced, enhanced.clone()); let pending = state - .pending_close + .prompts + .close .clone() .expect("the switch asked nothing"); assert_eq!(state.unsaved_documents(&pending.documents), [file]); diff --git a/src/state/tests/the_front_door_opens_and_closes.rs b/src/state/tests/the_front_door_opens_and_closes.rs index ad34775f6..dc441d1e7 100644 --- a/src/state/tests/the_front_door_opens_and_closes.rs +++ b/src/state/tests/the_front_door_opens_and_closes.rs @@ -31,7 +31,7 @@ fn close_project_asks_when_the_project_changed_and_closes_at_once_when_it_did_no state.project_carried.changed = true; state.close_project(); assert!( - state.pending_close.is_some(), + state.prompts.close.is_some(), "a project with a change nothing wrote down was closed without a question" ); assert_eq!( @@ -42,7 +42,7 @@ fn close_project_asks_when_the_project_changed_and_closes_at_once_when_it_did_no state.answer_close(CloseAnswer::Cancel); assert_eq!(state.project_path.as_deref(), Some(file.as_path())); - assert!(state.pending_close.is_none()); + assert!(state.prompts.close.is_none()); state.close_project(); state.answer_close(CloseAnswer::DontSave); diff --git a/src/state/tests/the_gate_in_front_of_every_write.rs b/src/state/tests/the_gate_in_front_of_every_write.rs index 9f35b2661..0fcd6ed6f 100644 --- a/src/state/tests/the_gate_in_front_of_every_write.rs +++ b/src/state/tests/the_gate_in_front_of_every_write.rs @@ -184,7 +184,7 @@ fn the_gate_stands_in_front_of_every_write() { "writing GTA VI AWC Ogg Opus streams into a folder a picker chose", ), ( - "../audio/opus_job.rs", + "media_playback.rs", "awc_opus_decode", "decoding an Opus stream to a WAV path a picker chose", ), @@ -319,13 +319,14 @@ fn an_edit_outside_the_overlay_offers_the_copy() { std::fs::write(&shipped, b"shipped archive").expect("archive"); let mut state = crate::state::AppState::new(); - state.retail_edit_session_allow = false; + state.prompts.retail_edit_session_allow = false; state.prefs.edit_mode = EditMode::Overlay; assert!(matches!( state.gate_permits(Some(&shipped)), crate::state::GateOutcome::Refused )); let offer = state + .bg .overlay_copy .offer .clone() @@ -336,13 +337,13 @@ fn an_edit_outside_the_overlay_offers_the_copy() { install.join("mods").join("update").join("update.rpf") ); - state.overlay_copy.offer = None; + state.bg.overlay_copy.offer = None; state.prefs.edit_mode = EditMode::ReadOnly; assert!(matches!( state.gate_permits(Some(&shipped)), crate::state::GateOutcome::Refused )); - assert_eq!(state.overlay_copy.offer, None); + assert_eq!(state.bg.overlay_copy.offer, None); } /// Saving or editing a shipped archive in the mounted install is refused and offers the copy. @@ -359,7 +360,7 @@ fn a_refused_archive_in_the_mounted_install_is_not_written() { let dest = install.join("mods").join("update").join("update.rpf"); let mut state = crate::state::AppState::new(); - state.retail_edit_session_allow = false; + state.prompts.retail_edit_session_allow = false; state.prefs.edit_mode = EditMode::Overlay; let bytes = crate::state::document_io::serialize_archive_records( vec![("a.txt".to_string(), b"entry".to_vec(), false)], @@ -411,11 +412,11 @@ fn a_refused_archive_in_the_mounted_install_is_not_written() { std::fs::read(&shipped).expect("shipped") == bytes, "a save the gate refuses must leave the shipped archive alone" ); - let offered = state.overlay_copy.offer.take().map(|o| o.dest); + let offered = state.bg.overlay_copy.offer.take().map(|o| o.dest); assert_eq!(offered.as_ref(), Some(&dest), "and offer the overlay copy"); assert!(state.rpf_rename_node(doc_id, entry, "b.txt").is_err()); - let offered = state.overlay_copy.offer.take().map(|o| o.dest); + let offered = state.bg.overlay_copy.offer.take().map(|o| o.dest); assert_eq!( offered.as_ref(), Some(&dest), @@ -437,7 +438,7 @@ fn read_only_refuses_saving_an_archive_in_the_overlay() { let overlay = install.join("mods").join("update").join("update.rpf"); let mut state = crate::state::AppState::new(); - state.retail_edit_session_allow = false; + state.prompts.retail_edit_session_allow = false; state.prefs.edit_mode = EditMode::ReadOnly; let bytes = crate::state::document_io::serialize_archive_records( vec![("a.txt".to_string(), b"entry".to_vec(), false)], @@ -505,7 +506,7 @@ fn no_mode_writes_into_gta_vi_s_install() { let in_mods = tmp.path().join("mods").join("common.rpf"); let mut state = crate::state::AppState::new(); - state.retail_edit_session_allow = true; + state.prompts.retail_edit_session_allow = true; for mode in EditMode::ALL { state.prefs.edit_mode = mode; for target in [tmp.path(), shipped.as_path(), in_mods.as_path()] { @@ -517,11 +518,11 @@ fn no_mode_writes_into_gta_vi_s_install() { } } assert_eq!( - state.refused_write, None, + state.prompts.refused_write, None, "no mode permits it, so none is offered" ); assert_eq!( - state.overlay_copy.offer, None, + state.bg.overlay_copy.offer, None, "nor a copy the gate would refuse" ); } diff --git a/src/state/tests/the_map_screen_holds_a_session.rs b/src/state/tests/the_map_screen_holds_a_session.rs index 82ae733b5..99c779176 100644 --- a/src/state/tests/the_map_screen_holds_a_session.rs +++ b/src/state/tests/the_map_screen_holds_a_session.rs @@ -732,7 +732,7 @@ fn a_project_closed_without_saving_writes_no_edit_and_one_closed_with_save_write move_to(&mut state, HARBOUR, 0, 12.5); state.close_project(); assert!( - state.pending_close.is_some(), + state.prompts.close.is_some(), "an edit of the maps is asked about" ); state.answer_close(CloseAnswer::Cancel); @@ -808,7 +808,7 @@ fn a_source_changed_on_disk_under_the_session_is_read_again_or_asked_about_as_a_ assert_eq!(state.workbench.maps.undo.len(), 1); moved_outside(&pack, 40.0); scanned(&mut state); - assert_eq!(state.reload_conflicts, Vec::::new()); + assert_eq!(state.prompts.reload_conflicts, Vec::::new()); assert_eq!(held_xs(&mut state, HARBOUR), [12.5, 40.0]); assert_eq!(shown_xs(&state, HARBOUR), [12.5, 40.0]); assert!( @@ -831,7 +831,7 @@ fn a_source_changed_on_disk_under_the_session_is_read_again_or_asked_about_as_a_ "a refused save writes nothing" ); scanned(&mut state); - assert_eq!(state.reload_conflicts, std::slice::from_ref(&file)); + assert_eq!(state.prompts.reload_conflicts, std::slice::from_ref(&file)); assert_eq!( shown_xs(&state, HARBOUR), [14.0, 40.0], @@ -840,10 +840,10 @@ fn a_source_changed_on_disk_under_the_session_is_read_again_or_asked_about_as_a_ // Kept, the edit is written over the file at the next save, and what was done outside is gone. state.answer_reload_conflicts(false); - assert!(state.reload_conflicts.is_empty()); + assert!(state.prompts.reload_conflicts.is_empty()); scanned(&mut state); assert!( - state.reload_conflicts.is_empty(), + state.prompts.reload_conflicts.is_empty(), "the question is asked once" ); save(&mut state); @@ -857,15 +857,15 @@ fn a_source_changed_on_disk_under_the_session_is_read_again_or_asked_about_as_a_ move_to(&mut state, HARBOUR, 0, 18.0); moved_outside(&pack, 60.0); scanned(&mut state); - assert_eq!(state.reload_conflicts, std::slice::from_ref(&file)); + assert_eq!(state.prompts.reload_conflicts, std::slice::from_ref(&file)); state.answer_reload_conflicts(true); - assert!(state.reload_conflicts.is_empty()); + assert!(state.prompts.reload_conflicts.is_empty()); assert!(state.workbench.maps.undo.is_empty()); assert!(!state.map_edits_unwritten()); assert_eq!(held_xs(&mut state, HARBOUR), [14.0, 60.0]); scanned(&mut state); assert_eq!(shown_xs(&state, HARBOUR), [14.0, 60.0]); - assert!(state.reload_conflicts.is_empty()); + assert!(state.prompts.reload_conflicts.is_empty()); } /// What a move costs on the Map screen on a large map: the operation in the session, and what the session then holds laid over diff --git a/src/state/tests/the_map_screen_saves_with_the_project.rs b/src/state/tests/the_map_screen_saves_with_the_project.rs index 8e52a651f..a1074db5a 100644 --- a/src/state/tests/the_map_screen_saves_with_the_project.rs +++ b/src/state/tests/the_map_screen_saves_with_the_project.rs @@ -43,7 +43,7 @@ fn save_with_a_tab_in_front_writes_the_maps_on_the_map_screen_and_the_tab_everyw let ctx = egui::Context::default(); crate::ui::commands::run_action(state, &ctx, crate::ui::commands::Action::Save); let deadline = Instant::now() + Duration::from_secs(30); - while state.save_receiver.is_some() { + while state.io_queue.save_receiver.is_some() { assert!(Instant::now() < deadline, "the save never ended"); state.poll_save_result(); std::thread::sleep(Duration::from_millis(5)); diff --git a/src/state/tests/the_skeleton_files_own_model_can_be_hidden.rs b/src/state/tests/the_skeleton_files_own_model_can_be_hidden.rs index 92aa6dfa0..70a9b7728 100644 --- a/src/state/tests/the_skeleton_files_own_model_can_be_hidden.rs +++ b/src/state/tests/the_skeleton_files_own_model_can_be_hidden.rs @@ -217,10 +217,14 @@ impl Preview { /// Whether the viewport has bones to draw: the skeleton is bound and its lines are not empty. fn draws_the_skeleton(&self) -> bool { - let skeleton = self.state.anim.skeleton(); + let skeleton = self.state.animation.session.skeleton(); skeleton.is_some_and(|skeleton| { - let lines = - build_pose_comparison(skeleton, &self.state.anim.world_matrices, false, None); + let lines = build_pose_comparison( + skeleton, + &self.state.animation.session.world_matrices, + false, + None, + ); !lines.is_empty() }) } diff --git a/src/state/tests/the_unsaved_marker_tells_the_truth.rs b/src/state/tests/the_unsaved_marker_tells_the_truth.rs index c8c32e17a..17a4e8722 100644 --- a/src/state/tests/the_unsaved_marker_tells_the_truth.rs +++ b/src/state/tests/the_unsaved_marker_tells_the_truth.rs @@ -23,7 +23,7 @@ fn detaching_a_dictionary_with_unsaved_edits_asks_first() { Some(PathBuf::from("C:/mods/attached.ytd")), DocPayload::Resource(or_io::Asset::TextureDict(Default::default())), )); - state.attached_texture_docs.push(AttachedDictionary { + state.textures.attached_docs.push(AttachedDictionary { document: id, opened_by_attach: true, }); @@ -34,7 +34,7 @@ fn detaching_a_dictionary_with_unsaved_edits_asks_first() { marked(&state, id), "detaching dropped the dictionary's edits before the user answered" ); - assert!(state.pending_close.is_some(), "detaching asked nothing"); + assert!(state.prompts.close.is_some(), "detaching asked nothing"); state.answer_close(CloseAnswer::Cancel); assert!( state.is_attached_texture_dictionary(id) && marked(&state, id), diff --git a/src/state/tests/the_viewport_picks_every_line_it_draws.rs b/src/state/tests/the_viewport_picks_every_line_it_draws.rs index b0d9f043f..a6131cff5 100644 --- a/src/state/tests/the_viewport_picks_every_line_it_draws.rs +++ b/src/state/tests/the_viewport_picks_every_line_it_draws.rs @@ -28,7 +28,7 @@ fn the_ghost_of() { for holder in Holder::ALL { let mut p = previewing::(holder); // The pose has carried every bone far from where the bind pose stands, which the ghost draws. - for world in &mut p.state.anim.world_matrices { + for world in &mut p.state.animation.session.world_matrices { *world = Mat4::from_translation(MOVED) * *world; } let click = || ray(MIDDLE_OF_THE_BONE, Vec3::X, 2.0, egui::Vec2::ZERO); @@ -79,8 +79,9 @@ fn a_bone_over_its_ghost() { let mut p = previewing::(holder); // The pose rests where the bind pose stands, so a bone and its ghost lie on one segment, // and the one picked is the one that comes first in `bone_under`. - let bind = (p.state.anim.skeleton()).map(|skeleton| skeleton.bind_world.clone()); - p.state.anim.world_matrices = bind.expect("a skeleton to pose"); + let bind = + (p.state.animation.session.skeleton()).map(|skeleton| skeleton.bind_world.clone()); + p.state.animation.session.world_matrices = bind.expect("a skeleton to pose"); p.state.preview_scene.show_bind_pose_ghost = true; select_under( @@ -363,7 +364,10 @@ fn a_bone_is_picked_while_every_mesh_the_preview_was_given_draws_nothing() { entry: Some(0), }); assert_eq!(p.state.preview_scene.drawn_sources(), [(empty, Some(0))]); - assert!(p.state.anim.skeleton().is_some(), "the skeleton is shown"); + assert!( + p.state.animation.session.skeleton().is_some(), + "the skeleton is shown" + ); let clip_row = SelectionKey::dict_entry(CLIP); p.state.selection.select(p.clips, clip_row); diff --git a/src/state/tests/the_viewport_picks_what_it_draws.rs b/src/state/tests/the_viewport_picks_what_it_draws.rs index 84e284793..03b18e778 100644 --- a/src/state/tests/the_viewport_picks_what_it_draws.rs +++ b/src/state/tests/the_viewport_picks_what_it_draws.rs @@ -327,7 +327,10 @@ pub(in crate::state) fn previewing(holder: Holder) -> Preview { state.preview_scene.pin_skeleton(Some(holder.skeleton(rig))); state.preview_scene.show_bones = true; state.tick_animation(); - assert!(state.anim.skeleton().is_some(), "the clip binds to the rig"); + assert!( + state.animation.session.skeleton().is_some(), + "the clip binds to the rig" + ); Preview { state, rig, clips } } diff --git a/src/state/tests/what_a_comparison_still_missed.rs b/src/state/tests/what_a_comparison_still_missed.rs index e4465f8fe..5d7b477c6 100644 --- a/src/state/tests/what_a_comparison_still_missed.rs +++ b/src/state/tests/what_a_comparison_still_missed.rs @@ -264,7 +264,7 @@ fn compare_with_selected_is_disabled_with_its_reason_on_an_archive_being_defragm state.defragment_archive(folder, a); settle(&mut state); - assert!(state.defrag.holds(&held), "the size preview is on offer"); + assert!(state.bg.defrag.holds(&held), "the size preview is on offer"); assert_eq!( with_selected(&state, a), Err("The archive this is read from is being defragmented: compare once that is done") @@ -319,12 +319,12 @@ fn compare_with_original_is_disabled_and_refused_while_a_defragment_holds_either // The game's own copy, which a defragment asks about first, then the overlay's. for (held, name) in [(shipped, "the game's"), (modded, "the overlay's")] { state.defragment_archive(game, held); - if state.pending_retail_edit.is_some() { + if state.prompts.retail_edit.is_some() { state.apply_pending_retail_edit(RetailEditDecision::YesSession); } settle(&mut state); assert!( - state.defrag.offer.is_some(), + state.bg.defrag.offer.is_some(), "{name}: a size preview is on offer" ); assert_eq!(with_original(&state), Err(HELD), "{name}"); diff --git a/src/state/tests/what_archive_rows_still_get_wrong.rs b/src/state/tests/what_archive_rows_still_get_wrong.rs index 833cce879..49ccf24c9 100644 --- a/src/state/tests/what_archive_rows_still_get_wrong.rs +++ b/src/state/tests/what_archive_rows_still_get_wrong.rs @@ -50,7 +50,7 @@ fn a_folder_dropped_onto_itself_or_a_folder_inside_it_is_refused_with_nothing_wr std::fs::write(dropped.join("f.txt"), b"f").expect("a file"); let (mut state, tree) = install(dir.path(), &[]); state.prefs.edit_mode = EditMode::Everything; - state.retail_edit_session_allow = false; + state.prompts.retail_edit_session_allow = false; let before = everything_under(dir.path()); for onto in ["a/b", "a"] { @@ -61,7 +61,7 @@ fn a_folder_dropped_onto_itself_or_a_folder_inside_it_is_refused_with_nothing_wr DropTarget::Folder { doc: tree, folder }, ); assert!( - state.pending_retail_edit.is_none(), + state.prompts.retail_edit.is_none(), "the drop onto {onto} asked to write rather than refusing" ); let refusals = errors(&state).split_off(said); diff --git a/src/state/texture_edit.rs b/src/state/texture_edit.rs index 90d627f27..ca059861f 100644 --- a/src/state/texture_edit.rs +++ b/src/state/texture_edit.rs @@ -305,7 +305,7 @@ impl AppState { // ⚠ The decoded preview is keyed by name and the pixels behind it have // just changed, so leaving it cached shows the old encoding until the // document is closed. - self.texture_cache.forget_document(doc); + self.textures.cache.forget_document(doc); } /// Whether an in-place edit can reach this document's dictionary at all. diff --git a/src/state/texture_resolution.rs b/src/state/texture_resolution.rs index 2845674f4..816516014 100644 --- a/src/state/texture_resolution.rs +++ b/src/state/texture_resolution.rs @@ -401,7 +401,7 @@ impl Candidate { .document(self.document) .map(document_label) .unwrap_or_default(), - implicitly_opened: state.auto_opened_texture_docs.contains(&self.document), + implicitly_opened: state.textures.auto_opened_docs.contains(&self.document), document: self.document, rule: self.rule, } @@ -424,7 +424,8 @@ fn rank_candidates(state: &AppState, from: Option, name: &str) -> Ve .filter_map(|(index, doc)| { let pin_index = pins.iter().position(|id| *id == doc.id); let attach_index = state - .attached_texture_docs + .textures + .attached_docs .iter() .position(|attached| attached.document == doc.id); let rule = if Some(doc.id) == active.map(|asked| asked.id) { @@ -450,7 +451,7 @@ fn rank_candidates(state: &AppState, from: Option, name: &str) -> Ve // The exceptions are what every vehicle shares, which serves each vehicle alike, and a // GTA VI pack, whose 64-bit key names one texture. if rule > ResolutionRule::DetailVariant - && state.auto_opened_texture_docs.contains(&doc.id) + && state.textures.auto_opened_docs.contains(&doc.id) && !matches!(doc.payload, DocPayload::Ttpf(_)) && !(active.is_some_and(|a| a.kind() == DocumentKind::Yft) && is_shared_vehicle_dictionary(doc)) @@ -555,11 +556,11 @@ pub(crate) fn wanted_dictionaries(stem: &str) -> Vec { /// The active document's stem, when a texture report about it names a missing texture. pub(super) fn stem_missing_textures(state: &AppState) -> Option<(DocumentId, String)> { - if state.texture_report.missing().is_empty() { + if state.textures.report.missing().is_empty() { return None; } let doc = state.active_document()?; - if state.texture_report.document != Some(doc.id) { + if state.textures.report.document != Some(doc.id) { return None; } Some((doc.id, stem(doc)?)) @@ -625,11 +626,12 @@ pub struct AttachedDictionary { impl AppState { pub fn attached_texture_dictionaries(&self) -> &[AttachedDictionary] { - &self.attached_texture_docs + &self.textures.attached_docs } pub fn is_attached_texture_dictionary(&self, doc: DocumentId) -> bool { - self.attached_texture_docs + self.textures + .attached_docs .iter() .any(|attached| attached.document == doc) } @@ -716,16 +718,17 @@ impl AppState { /// Stop consulting it, closing it again if attaching is what opened it. pub fn detach_texture_dictionary(&mut self, doc: DocumentId) { let Some(index) = self - .attached_texture_docs + .textures + .attached_docs .iter() .position(|attached| attached.document == doc) else { return; }; - let attached = self.attached_texture_docs[index]; + let attached = self.textures.attached_docs[index]; self.retry_texture_search(); if !attached.opened_by_attach { - self.attached_texture_docs.remove(index); + self.textures.attached_docs.remove(index); } else if self.unsaved_documents(&[doc]).is_empty() { self.drop_document(doc); } else { @@ -738,7 +741,7 @@ impl AppState { if self.is_attached_texture_dictionary(doc) { return; } - self.attached_texture_docs.push(AttachedDictionary { + self.textures.attached_docs.push(AttachedDictionary { document: doc, opened_by_attach, }); @@ -748,9 +751,7 @@ impl AppState { } fn retry_texture_search(&mut self) { - self.attempted_texture_siblings.clear(); - self.attempted_shared_dictionaries.clear(); - self.attempted_texture_search_paths.clear(); + self.textures.clear_automatic_attempts(); } /// Read an archive entry into a document without leaving the frame. @@ -797,30 +798,31 @@ impl AppState { } pub fn pinned_texture_dictionaries(&self, doc: DocumentId) -> &[DocumentId] { - self.pinned_texture_docs + self.textures + .pinned_docs .get(&doc) .map(Vec::as_slice) .unwrap_or_default() } pub fn pin_texture_dictionary(&mut self, doc: DocumentId, dictionary: DocumentId) { - let pins = self.pinned_texture_docs.entry(doc).or_default(); + let pins = self.textures.pinned_docs.entry(doc).or_default(); if !pins.contains(&dictionary) { pins.push(dictionary); } } pub fn unpin_texture_dictionary(&mut self, doc: DocumentId, dictionary: DocumentId) { - if let Some(pins) = self.pinned_texture_docs.get_mut(&doc) { + if let Some(pins) = self.textures.pinned_docs.get_mut(&doc) { pins.retain(|id| *id != dictionary); if pins.is_empty() { - self.pinned_texture_docs.remove(&doc); + self.textures.pinned_docs.remove(&doc); } } } pub fn clear_texture_pins(&mut self, doc: DocumentId) { - self.pinned_texture_docs.remove(&doc); + self.textures.pinned_docs.remove(&doc); } /// The documents the viewport's textures are asked for: what the Animation preview draws, else the active one. @@ -857,22 +859,7 @@ impl AppState { } pub(super) fn forget_texture_resolution(&mut self, id: DocumentId) { - self.pinned_texture_docs.remove(&id); - self.pinned_texture_docs.retain(|_, pins| { - pins.retain(|pinned| *pinned != id); - !pins.is_empty() - }); - self.auto_opened_texture_docs.remove(&id); - self.attached_texture_docs - .retain(|attached| attached.document != id); - self.attempted_texture_siblings.remove(&id); - self.attempted_shared_dictionaries - .retain(|(doc, _)| *doc != id); - self.attempted_texture_search_paths.remove(&id); - self.attempted_texture_project.remove(&id); - if self.texture_report.document == Some(id) { - self.texture_report = TextureResolutionReport::default(); - } + self.textures.clear_for_document(id); } pub fn try_auto_open_texture_sibling(&mut self) -> bool { @@ -886,12 +873,12 @@ impl AppState { doc.kind(), DocumentKind::Ydr | DocumentKind::Ydd | DocumentKind::Yft ); - let misses = self.texture_report.document == Some(doc_id) - && !self.texture_report.missing().is_empty(); + let misses = self.textures.report.document == Some(doc_id) + && !self.textures.report.missing().is_empty(); if !is_model && !misses { return false; } - if self.attempted_texture_siblings.contains(&doc_id) { + if self.textures.attempted_siblings.contains(&doc_id) { return false; } let Some(binding) = doc.rpf_entry_binding else { @@ -900,7 +887,7 @@ impl AppState { let Some(stem) = stem(doc) else { return false; }; - self.attempted_texture_siblings.insert(doc_id); + self.textures.attempted_siblings.insert(doc_id); let wanted = wanted_dictionaries(&stem); let Some((sibling_node, sibling_path)) = wanted @@ -923,7 +910,7 @@ impl AppState { return false; } }; - self.auto_opened_texture_docs.insert(id); + self.textures.auto_opened_docs.insert(id); tracing::info!(sibling = %sibling_path, "opened a texture sibling from the archive"); true } @@ -937,8 +924,8 @@ impl AppState { return false; }; let doc_id = doc.id; - let misses = self.texture_report.document == Some(doc_id) - && !self.texture_report.missing().is_empty(); + let misses = self.textures.report.document == Some(doc_id) + && !self.textures.report.missing().is_empty(); if doc.kind() != DocumentKind::Yft || !misses { return false; } @@ -946,13 +933,13 @@ impl AppState { return false; }; for name in SHARED_VEHICLE_DICTIONARIES { - if self.attempted_shared_dictionaries.contains(&(doc_id, name)) { + if self.textures.attempted_shared.contains(&(doc_id, name)) { continue; } let Some((node, path)) = self.sibling_archive_entry(binding, name) else { continue; }; - self.attempted_shared_dictionaries.insert((doc_id, name)); + self.textures.attempted_shared.insert((doc_id, name)); if self.rpf_entry_is_open(binding.parent_doc_id, node) { continue; } @@ -962,7 +949,7 @@ impl AppState { }); match opened { Ok(id) => { - self.auto_opened_texture_docs.insert(id); + self.textures.auto_opened_docs.insert(id); tracing::info!(shared = %path, "opened a shared vehicle dictionary from the archive"); return true; } @@ -983,23 +970,23 @@ impl AppState { /// Opening a folder's worth of dictionaries to find one name would make /// every later resolution ambiguous by flooding `also_in`. pub fn try_open_texture_from_search_paths(&mut self) -> bool { - if self.texture_report.missing().is_empty() { + if self.textures.report.missing().is_empty() { return false; } let Some(doc) = self.active_document() else { return false; }; let doc_id = doc.id; - if self.texture_report.document != Some(doc_id) { + if self.textures.report.document != Some(doc_id) { return false; } - if self.attempted_texture_search_paths.contains(&doc_id) { + if self.textures.attempted_search_paths.contains(&doc_id) { return false; } let Some(stem) = stem(doc) else { return false; }; - self.attempted_texture_search_paths.insert(doc_id); + self.textures.attempted_search_paths.insert(doc_id); let wanted = wanted_dictionaries(&stem); let roots = self.prefs.texture_search_paths.clone(); @@ -1041,7 +1028,7 @@ impl AppState { let id = self.alloc_doc_id(); self.documents .push(Document::new(id, Some(path.to_path_buf()), payload).with_resource(resource)); - self.auto_opened_texture_docs.insert(id); + self.textures.auto_opened_docs.insert(id); tracing::info!(path = %path.display(), "opened a texture dictionary"); true } diff --git a/src/state/undo.rs b/src/state/undo.rs index 8eb2997e5..ffe29807e 100644 --- a/src/state/undo.rs +++ b/src/state/undo.rs @@ -29,7 +29,7 @@ impl AppState { /// Read `doc`'s payload back from its image if an image edit has not reached it, and forget the previews drawn from the old payload. pub(super) fn catch_up(&mut self, doc: DocumentId) { if self.document_mut(doc).is_some_and(|d| d.catch_up()) { - self.texture_cache.forget_document(doc); + self.textures.cache.forget_document(doc); self.rebuild_after_an_edit(doc); } } @@ -125,7 +125,7 @@ impl AppState { self.file_replaced(path); } // ⚠ Decoded previews are keyed by name, so a step that swapped a texture's pixels would leave the old ones shown. - self.texture_cache.forget_document(doc); + self.textures.cache.forget_document(doc); self.rebuild_after_an_edit(doc); // ⚠ A removal the World screen made across several maps is one step: the others' go with this one. self.world_step_follows(doc, id, direction); @@ -154,7 +154,7 @@ impl AppState { GateOutcome::Refused => false, GateOutcome::Confirm(target) => { // The gate asks about this write as it asks about any other, and the answer takes the step - self.pending_retail_edit = Some(PendingRetailEditPrompt { + self.prompts.retail_edit = Some(PendingRetailEditPrompt { action: PendingRetailEdit::Step { doc_id: doc, direction, @@ -176,8 +176,8 @@ impl AppState { let gone = || crate::i18n::tr(super::edit_history::GONE).to_string(); match change { Change::Pose(other) => { - std::mem::swap(&mut self.anim_edits, other); - self.anim.invalidate(); + std::mem::swap(&mut self.animation.edits, other); + self.animation.session.invalidate(); Ok(()) } Change::ClipFields { clip_key, other } => { @@ -186,7 +186,7 @@ impl AppState { return Err(gone()); } *other = now; - self.anim.invalidate(); + self.animation.session.invalidate(); Ok(()) } change => (self.document_mut(doc)) @@ -205,7 +205,7 @@ impl AppState { ) { for held in &self.documents { if matches!(held.payload, DocPayload::Gta6Drawable(_)) { - self.texture_cache.forget_document(held.id); + self.textures.cache.forget_document(held.id); } } } diff --git a/src/state/vfs_session.rs b/src/state/vfs_session.rs index e0e326ed2..a3e4b9004 100644 --- a/src/state/vfs_session.rs +++ b/src/state/vfs_session.rs @@ -167,10 +167,11 @@ impl super::AppState { /// Called every repaint: only the files the index found since the last call are matched. pub fn deep_find_tick(&mut self, doc_id: DocumentId, pattern: &str) { self.tick_file_index(); - let root = self.file_index.root_of(doc_id); + let root = self.find.file_index.root_of(doc_id); let generation = root.map_or(0, |root| root.generation); let found = self - .deep_find + .find + .deep .found .entry(doc_id) .or_insert_with(|| DeepFind::new(pattern, generation)); @@ -201,7 +202,7 @@ impl super::AppState { let Some(source) = self.document(doc_id).and_then(|doc| doc.path.clone()) else { return; }; - let Some(found) = self.deep_find.found.get(&doc_id) else { + let Some(found) = self.find.deep.found.get(&doc_id) else { return; }; let inners = rows diff --git a/src/state/workbench/commands.rs b/src/state/workbench/commands.rs index 82a57f540..745a35c15 100644 --- a/src/state/workbench/commands.rs +++ b/src/state/workbench/commands.rs @@ -173,11 +173,11 @@ impl AppState { self.workbench .note(tr!("Compiled {source}", source = leaf(&source))); // ⚠ A model opened before its textures were first cooked was told there were none: it is allowed to ask for them again. - self.attempted_texture_project.clear(); - let was_waiting = self.reload_conflicts.contains(&output); + self.textures.attempted_project.clear(); + let was_waiting = self.prompts.reload_conflicts.contains(&output); let read = self.reload_open_file(&output, false); // ⚠ A tab with unsaved edits asks first, and a file OpenRage recooked itself is not a file somebody else changed. - if !was_waiting && self.reload_conflicts.contains(&output) { + if !was_waiting && self.prompts.reload_conflicts.contains(&output) { self.workbench.refreshed.insert(output.clone()); } if let Err(why) = read { @@ -318,7 +318,7 @@ impl AppState { root: build_root(project), members: self.member_paths(), outputs, - remap: Arc::clone(&self.shader_defs.remap), + remap: Arc::clone(&self.install.shader_defs.remap), extensions, reproducible: false, }) diff --git a/src/state/workbench/dressed/alone.rs b/src/state/workbench/dressed/alone.rs index 32f226a96..70bc17494 100644 --- a/src/state/workbench/dressed/alone.rs +++ b/src/state/workbench/dressed/alone.rs @@ -211,7 +211,7 @@ impl AppState { /// Where the bone named `bone` of `ped`'s skeleton is at rest. fn ped_bone(&self, ped: Ped, bone: &str) -> Result { - let Base::Ready(mounted) = &self.workbench.wardrobe.dressed.base else { + let Base::Ready(mounted) = &self.workbench.wardrobe.dressed.install.base else { return Err( tr!("no game install is chosen, so the ped's skeleton is not read").to_string(), ); diff --git a/src/state/workbench/dressed/assemble.rs b/src/state/workbench/dressed/assemble.rs index 4ac11d0c6..1ac3337eb 100644 --- a/src/state/workbench/dressed/assemble.rs +++ b/src/state/workbench/dressed/assemble.rs @@ -45,9 +45,9 @@ impl AppState { }) .collect(); let dressed = &mut self.workbench.wardrobe.dressed; - match &dressed.base { + match &dressed.install.base { Base::Failed(why) => notes.push(tr!("The ped's own drawables: {why}", why = why)), - Base::Idle if dressed.base_root.is_none() => { + Base::Idle if dressed.install.base_root.is_none() => { notes.push(crate::i18n::tr(NO_GAME).to_string()) } Base::Idle => notes.push( @@ -79,7 +79,7 @@ impl AppState { let mut waiting = false; let mut fell_back = 0; for slot in &plan.slots { - let model = match dressed.loaded.get(&slot.model) { + let model = match dressed.cache.loaded.get(&slot.model) { Some(Loaded::Model(model)) => Some(Arc::clone(model)), Some(Loaded::Failed(why)) => { notes.push(format!("{}: {why}", describe(&slot.model))); @@ -90,20 +90,20 @@ impl AppState { None } }; - let diffuse = slot - .texture - .as_ref() - .and_then(|need| match dressed.loaded.get(need) { - Some(Loaded::Texture(diffuse)) => Some(Arc::clone(diffuse)), - Some(Loaded::Failed(why)) => { - notes.push(format!("{}: {why}", describe(need))); - None - } - _ => { - waiting = true; - None - } - }); + let diffuse = + slot.texture + .as_ref() + .and_then(|need| match dressed.cache.loaded.get(need) { + Some(Loaded::Texture(diffuse)) => Some(Arc::clone(diffuse)), + Some(Loaded::Failed(why)) => { + notes.push(format!("{}: {why}", describe(need))); + None + } + _ => { + waiting = true; + None + } + }); let Some(model) = model else { continue; }; @@ -203,10 +203,10 @@ impl AppState { .with_skins(skins) .with_aux(aux) .with_shaded(shaded); - let to_frame = dressed.framed_for != Some(plan.ped) || dressed.needs_frame; + let to_frame = dressed.head.framed_for != Some(plan.ped) || dressed.needs_frame; if to_frame && !scene.parts.is_empty() { dressed.camera.frame_sphere(scene.centre, scene.radius); - dressed.framed_for = Some(plan.ped); + dressed.head.framed_for = Some(plan.ped); dressed.needs_frame = false; } dressed.scene = Some(Arc::new(scene)); diff --git a/src/state/workbench/dressed/controls.rs b/src/state/workbench/dressed/controls.rs new file mode 100644 index 000000000..9058c4690 --- /dev/null +++ b/src/state/workbench/dressed/controls.rs @@ -0,0 +1,203 @@ +//! Encapsulated queries and controls on [`Dressed`] used by the Wardrobe preview and drop handlers. + +use glam::Mat4; +use or_renderer::ShadingMode; +use or_wardrobe::dress::BaseEdit; +use or_wardrobe::{Component, Ped}; + +use super::scene::{Counts, DressedScene}; +use super::{Dressed, ViewMode, NO_GAME}; +use crate::render::debug_channel::DebugChannel; + +impl Dressed { + /// Wear variation `index` of garment `id`. + pub fn set_variation(&mut self, id: String, index: usize) { + self.variation.insert(id, index); + } + + /// Record the variation tile currently targeted by an OS file drop. + pub fn set_drop_tile(&mut self, tile: (String, usize)) { + self.drop_tile = Some(tile); + } + + /// The variation tile currently targeted by an OS file drop, if any. + pub fn drop_tile(&self) -> Option<(&str, usize)> { + self.drop_tile + .as_ref() + .map(|(garment, variation)| (garment.as_str(), *variation)) + } + + /// Take and clear the variation tile targeted by an OS file drop. + pub fn take_drop_tile(&mut self) -> Option<(String, usize)> { + self.drop_tile.take() + } + + /// Whether `ped`'s skeleton is available for bones display or motion. + pub fn has_skeleton(&self, ped: Ped) -> bool { + self.skeleton(ped).is_some() + } + + /// Whether `ped`'s head bone position is known for first-person view. + pub fn has_head(&self, ped: Ped) -> bool { + self.eyes(ped).is_some() + } + + /// Whether the first-person head camera is active. + pub fn is_first_person(&self) -> bool { + self.first_person + } + + /// Exit the first-person head camera back to the orbit view. + pub fn leave_first_person(&mut self) { + self.first_person = false; + } + + /// Whether a clip is active or currently being read for playback. + pub fn is_playing_clip(&self) -> bool { + self.motion.is_some() || self.is_animating() + } + + /// Whether background work (file reads or catalogue capture) wants periodic repaints. + pub fn needs_poll_repaint(&self) -> bool { + self.is_reading() || self.is_cataloguing() + } + + /// Triangle and vertex counts currently drawn, when non-empty. + pub fn drawn_counts(&self) -> Option { + self.scene() + .map(DressedScene::drawn) + .filter(|d| d.triangles > 0) + } + + /// `(resolved, clip_tags)` bone drive counts of the active clip, if one is playing. + pub fn motion_drive_counts(&self) -> Option<(usize, usize)> { + self.motion + .as_ref() + .map(|m| (m.report.resolved, m.report.clip_tags())) + } + + /// The active clip's skinning revision and bone matrices, if one is playing. + pub fn pose_skin(&self) -> Option<(u64, &[Mat4])> { + self.motion.as_ref().map(|m| (m.revision(), m.skin())) + } + + /// The renderer shading mode and optional debug channel for the current view mode. + pub fn shading_and_channel(&self) -> (ShadingMode, Option) { + (self.view.shading(), self.view.channel()) + } + + /// Whether the preview is currently in the game-shaded view mode. + pub fn is_shaded(&self) -> bool { + self.view == ViewMode::Shaded + } + + /// Switch the preview to the plain textured Material view mode. + pub fn switch_to_material(&mut self) { + self.view = ViewMode::Material; + } + + /// Select `ped` as the preview ped and ask the camera to frame it. + pub fn select_ped(&mut self, ped: Ped) { + self.ped = Some(ped); + self.frame_again(); + } + + /// Show the ped without the pack (the A of A/B). + pub fn show_original(&mut self) { + (self.original, self.previous) = (true, false); + } + + /// Show the ped wearing the current pack (the B of A/B). + pub fn show_current_pack(&mut self) { + (self.original, self.previous) = (false, false); + } + + /// Whether garment `id` is currently in the outfit. + pub fn is_in_outfit(&self, id: &str) -> bool { + self.outfit.iter().any(|g| g == id) + } + + /// Toggle garment `id` in the outfit and enable wearing the outfit together. + pub fn toggle_and_wear_outfit(&mut self, id: &str) { + self.toggle_in_outfit(id); + self.outfit_on = true; + } + + /// The override applied to base component `slot`, if any. + pub fn base_edit(&self, slot: Component) -> Option { + self.base_edits.get(&slot).copied() + } + + /// Set or clear the override for base component `slot`. + pub fn set_base_edit(&mut self, slot: Component, edit: Option) { + match edit { + Some(value) => { + self.base_edits.insert(slot, value); + } + None => { + self.base_edits.remove(&slot); + } + } + } + + /// Whether any base component of the ped has an override. + pub fn has_base_edits(&self) -> bool { + !self.base_edits.is_empty() + } + + /// Restore all base components of the ped to the game's defaults. + pub fn reset_base_edits(&mut self) { + self.base_edits.clear(); + } + + /// The alternate-variation set driving garment `id`, if any: `(set_name, alt_index, overridden)`. + pub fn driven_for_garment(&self, id: &str) -> Option<(String, usize, bool)> { + let target = or_wardrobe::alternate::Asset::garment(id); + self.driven + .iter() + .find(|d| d.target == target) + .map(|d| (d.name.clone(), usize::from(d.alt), d.overridden)) + } + + /// The manual alternate model index chosen for garment `id`, if any. + pub fn chosen_alternate(&self, id: &str) -> Option { + self.alternate.get(id).copied() + } + + /// Clear any manual alternate override for garment `id` so active sets apply. + pub fn clear_alternate(&mut self, id: &str) { + self.alternate.remove(id); + } + + /// Set the alternate model index for garment `id`; index 0 clears the entry when no set drives it. + pub fn set_alternate(&mut self, id: String, index: usize, has_driven: bool) { + match (index, has_driven) { + (0, false) => { + self.alternate.remove(&id); + } + (n, _) => { + self.alternate.insert(id, n); + } + } + } + + /// Up to `max` preview notes (excluding the missing-game banner), plus any clip note and overflow count. + pub fn visible_notes(&self, max: usize) -> (Vec, usize) { + let no_game = crate::i18n::tr(NO_GAME); + let mut lines: Vec = self + .notes + .iter() + .filter(|note| note.as_str() != no_game) + .take(max) + .cloned() + .collect(); + let more = self + .notes + .iter() + .filter(|note| note.as_str() != no_game) + .count() + .saturating_sub(max); + lines.extend(self.clip_note.clone()); + (lines, more) + } +} diff --git a/src/state/workbench/dressed/first_person.rs b/src/state/workbench/dressed/first_person.rs index 4e047fd35..925f74766 100644 --- a/src/state/workbench/dressed/first_person.rs +++ b/src/state/workbench/dressed/first_person.rs @@ -39,19 +39,19 @@ impl Dressed { return false; }; let mut turn = OrbitCamera { - yaw: self.look.0, - pitch: self.look.1, + yaw: self.head.look.0, + pitch: self.head.look.1, ..OrbitCamera::default() }; turn.orbit(inputs.orbit.x, inputs.orbit.y); - self.look = (turn.yaw, turn.pitch); + self.head.look = (turn.yaw, turn.pitch); // The way from the target to the eye is the way the head does not look. let behind = Vec3::new( turn.pitch.cos() * turn.yaw.cos(), turn.pitch.cos() * turn.yaw.sin(), turn.pitch.sin(), ); - self.first_person_camera = OrbitCamera { + self.head.first_person_camera = OrbitCamera { target: eyes - behind * AHEAD, distance: AHEAD, fov_y: FIELD_OF_VIEW.to_radians(), @@ -63,6 +63,6 @@ impl Dressed { /// The camera of the view from the head, as the last frame placed it. pub(super) fn head_camera(&self) -> &OrbitCamera { - &self.first_person_camera + &self.head.first_person_camera } } diff --git a/src/state/workbench/dressed/mod.rs b/src/state/workbench/dressed/mod.rs index 7c7fb5889..026c4c23e 100644 --- a/src/state/workbench/dressed/mod.rs +++ b/src/state/workbench/dressed/mod.rs @@ -27,6 +27,7 @@ mod alone; mod assemble; pub mod catalogue; mod clips; +mod controls; pub mod first_person; pub mod light; pub mod motion; @@ -182,6 +183,58 @@ struct Loading { receiver: Receiver>, } +/// Background file reads, decoded assets and thumbnail cache for the preview. +#[derive(Default)] +struct ReadCache { + loaded: HashMap, + /// What the scene and the tiles asked for in the last frame. + wanted: std::collections::HashSet, + loading: Option, + /// How many recooks that read a tab again the preview has seen. + seen_recooked: u64, + /// The pictures of textures, by file, with the file as it was when read: the tiles of the garment selected and the rows of the list. + thumbs: HashMap)>, + /// The textures the list asked a picture of in its last frame: the first of each row it drew, and every one of the row under the pointer. + row_wanted: Vec, +} + +/// Mounted game install state and optional unit-test skeleton for the base ped. +#[derive(Default)] +struct BaseInstall { + base: Base, + base_root: Option, + /// A skeleton for a ped that has no install to read it from, for a unit. + own_skeleton: Option<(Ped, or_anim::Skeleton)>, +} + +/// Camera framing and first-person head-look state. +struct HeadCamera { + framed_for: Option, + /// Where the head looks in the first person view: the heading and the pitch. + look: (f32, f32), + /// The camera of the first person view, once there is a head to put it at. + first_person_camera: OrbitCamera, +} + +impl Default for HeadCamera { + fn default() -> Self { + Self { + framed_for: None, + look: first_person::LOOK, + first_person_camera: OrbitCamera::default(), + } + } +} + +/// Runtime state for background clip loading and per-frame playback stepping. +#[derive(Default)] +struct ClipPlayback { + reading_clip: Option, + /// The ped the clip was bound to: another ped is another skeleton. + motion_ped: Option, + last_tick: Option, +} + /// What the Wardrobe's preview shows and how it is set. pub struct Dressed { /// The ped to dress; the selected garment's when none is chosen. @@ -207,13 +260,9 @@ pub struct Dressed { pub lod: usize, /// The camera is placed on the scene the next time one stands. pub needs_frame: bool, - framed_for: Option, - loaded: HashMap, - /// What the scene and the tiles asked for in the last frame. - wanted: std::collections::HashSet, - loading: Option, - base: Base, - base_root: Option, + head: HeadCamera, + cache: ReadCache, + install: BaseInstall, scene: Option>, /// Sentences about what is not on screen and why, for the panel. pub notes: Vec, @@ -233,10 +282,6 @@ pub struct Dressed { pub driven: Vec, /// The view from the ped's head, the field of view the engine starts a camera with. pub first_person: bool, - /// Where the head looks in the first person view: the heading and the pitch. - look: (f32, f32), - /// The camera of the first person view, once there is a head to put it at. - first_person_camera: OrbitCamera, /// The game's shadows are drawn in the Shaded view. pub shadows: bool, /// Draw the ped's skeleton over it. @@ -249,20 +294,9 @@ pub struct Dressed { pub clips: Vec<(u32, String)>, /// Why a clip is not playing. pub clip_note: Option, - reading_clip: Option, - /// The ped the clip was bound to: another ped is another skeleton. - motion_ped: Option, - last_tick: Option, - /// A skeleton for a ped that has no install to read it from, for a unit. - own_skeleton: Option<(Ped, or_anim::Skeleton)>, + playback: ClipPlayback, /// The pictures of the pack being drawn, or just drawn. pub catalogue: Option, - /// How many recooks that read a tab again the preview has seen. - seen_recooked: u64, - /// The pictures of textures, by file, with the file as it was when read: the tiles of the garment selected and the rows of the list. - thumbs: HashMap)>, - /// The textures the list asked a picture of in its last frame: the first of each row it drew, and every one of the row under the pointer. - row_wanted: Vec, } impl Default for Dressed { @@ -281,12 +315,9 @@ impl Default for Dressed { camera: OrbitCamera::default(), lod: 0, needs_frame: true, - framed_for: None, - loaded: HashMap::new(), - wanted: Default::default(), - loading: None, - base: Base::Idle, - base_root: None, + head: HeadCamera::default(), + cache: ReadCache::default(), + install: BaseInstall::default(), scene: None, notes: Vec::new(), lift: 0.0, @@ -297,22 +328,14 @@ impl Default for Dressed { sets: dress::Sets::default(), driven: Vec::new(), first_person: false, - look: first_person::LOOK, - first_person_camera: OrbitCamera::default(), shadows: true, bones: false, base_edits: BTreeMap::new(), motion: None, clips: Vec::new(), clip_note: None, - reading_clip: None, - motion_ped: None, - last_tick: None, - own_skeleton: None, + playback: ClipPlayback::default(), catalogue: None, - seen_recooked: 0, - thumbs: HashMap::new(), - row_wanted: Vec::new(), } } } @@ -330,12 +353,13 @@ impl Dressed { /// Whether a read of files is under way. pub fn is_reading(&self) -> bool { - self.loading.is_some() || matches!(self.base, Base::Mounting(_)) + self.cache.loading.is_some() || matches!(self.install.base, Base::Mounting(_)) } /// Whether a clip is being read, or one is playing and so wants a frame again. pub fn is_animating(&self) -> bool { - self.reading_clip.is_some() || self.motion.as_ref().is_some_and(|m| m.transport.playing) + self.playback.reading_clip.is_some() + || self.motion.as_ref().is_some_and(|m| m.transport.playing) } /// Whether a catalogue of the pack is being drawn, which wants a frame again. @@ -345,10 +369,10 @@ impl Dressed { /// The skeleton of `ped`: the install's, once read. pub fn skeleton(&self, ped: Ped) -> Option<&or_anim::Skeleton> { - if let Some((own, skeleton)) = &self.own_skeleton { + if let Some((own, skeleton)) = &self.install.own_skeleton { return (*own == ped).then_some(skeleton); } - match &self.base { + match &self.install.base { Base::Ready(mounted) => mounted.skeletons.get(&ped)?.as_ref().ok(), _ => None, } @@ -356,12 +380,12 @@ impl Dressed { /// Stand `skeleton` up as the skeleton of `ped`, for a unit that has no install to read it from. pub fn show_skeleton(&mut self, ped: Ped, skeleton: or_anim::Skeleton) { - self.own_skeleton = Some((ped, skeleton)); + self.install.own_skeleton = Some((ped, skeleton)); } /// The ped's drawables of `slot` and how many it has, once its metadata is read. pub fn base_drawables(&self, ped: Ped, slot: Component) -> usize { - match &self.base { + match &self.install.base { Base::Ready(mounted) => match mounted.outfits.get(&ped) { Some(Ok(outfit)) => outfit.drawables(slot), _ => 0, @@ -372,7 +396,7 @@ impl Dressed { /// The slots the ped wears something in, once its metadata is read. pub fn base_slots(&self, ped: Ped) -> Vec { - match &self.base { + match &self.install.base { Base::Ready(mounted) => match mounted.outfits.get(&ped) { Some(Ok(outfit)) => outfit.slots().collect(), _ => Vec::new(), @@ -384,7 +408,7 @@ impl Dressed { /// Let the ped stand at rest again. pub fn stop_clip(&mut self) { self.motion = None; - self.reading_clip = None; + self.playback.reading_clip = None; self.clips.clear(); self.clip_note = None; } @@ -422,7 +446,7 @@ impl Dressed { } motion.transport.playing = playing; self.clips = motion::clips_of(&motion.dictionary); - self.motion_ped = Some(ped); + self.playback.motion_ped = Some(ped); self.motion = Some(motion); self.clip_note = None; } @@ -435,7 +459,7 @@ impl Dressed { /// Take a dictionary a worker has read, and play its clip. fn take_clip(&mut self, ped: Ped) { - let Some(reading) = &self.reading_clip else { + let Some(reading) = &self.playback.reading_clip else { return; }; let read = match reading.receiver.try_recv() { @@ -443,7 +467,7 @@ impl Dressed { Err(TryRecvError::Empty) => return, Err(TryRecvError::Disconnected) => Err(tr!("the read stopped").to_string()), }; - let Some(reading) = self.reading_clip.take() else { + let Some(reading) = self.playback.reading_clip.take() else { return; }; let preset = reading.wanted.is_some(); @@ -479,10 +503,11 @@ impl Dressed { fn tick_clip(&mut self, ped: Ped) { let now = std::time::Instant::now(); let dt = self + .playback .last_tick .replace(now) .map_or(0.0, |t| (now - t).as_secs_f32().min(0.1)); - if self.motion_ped.is_some_and(|bound| bound != ped) { + if self.playback.motion_ped.is_some_and(|bound| bound != ped) { self.stop_clip(); } if let Some(motion) = &mut self.motion { @@ -492,7 +517,7 @@ impl Dressed { /// Why the ped's own drawables are not there, none where they are or are being read. pub fn base_missing(&self) -> Option<&str> { - match &self.base { + match &self.install.base { Base::Failed(why) => Some(why), _ => None, } @@ -500,25 +525,25 @@ impl Dressed { /// The tile of the texture at `file`, once read. pub fn thumb(&self, file: &Path) -> Option<&Arc> { - self.thumbs.get(file).map(|(_, thumb)| thumb) + self.cache.thumbs.get(file).map(|(_, thumb)| thumb) } /// The textures the list wants a picture of in this frame; each is decoded once, and again only when its file changes. pub fn ask_row_thumbs(&mut self, files: Vec) { - self.row_wanted = files; + self.cache.row_wanted = files; } /// Whether `need` is read already: held, or a picture made of the file as it is. fn has(&self, need: &Need) -> bool { - self.loaded.contains_key(need) + self.cache.loaded.contains_key(need) || matches!(need, Need::Pack(Kind::Thumb, path, stamp) - if self.thumbs.get(path).is_some_and(|(read, _)| read == stamp)) + if self.cache.thumbs.get(path).is_some_and(|(read, _)| read == stamp)) } /// Start over reading the ped's own drawables from the install. pub fn retry_base(&mut self) { - self.base = Base::Idle; - self.base_root = None; + self.install.base = Base::Idle; + self.install.base_root = None; } pub fn clear_outfit(&mut self) { @@ -579,7 +604,7 @@ impl AppState { }; let (ped, crypto) = (self.dressed_ped(), self.keys.provider()); let dressed = &mut self.workbench.wardrobe.dressed; - let Base::Ready(mounted) = &dressed.base else { + let Base::Ready(mounted) = &dressed.install.base else { dressed.clip_note = Some( tr!("The presets are read from the game install, which needs to be chosen in Settings") .into(), @@ -592,7 +617,7 @@ impl AppState { let _ = sender.send(clips::read_preset(&mounted, ped, &crypto)); }); dressed.clip_note = None; - dressed.reading_clip = Some(clips::Reading { + dressed.playback.reading_clip = Some(clips::Reading { label: crate::i18n::tr(preset.label).to_string(), wanted: Some(preset.clip), receiver, @@ -611,7 +636,7 @@ impl AppState { }); let dressed = &mut self.workbench.wardrobe.dressed; dressed.clip_note = None; - dressed.reading_clip = Some(clips::Reading { + dressed.playback.reading_clip = Some(clips::Reading { label, wanted: None, receiver, @@ -673,7 +698,7 @@ impl AppState { let choice = self.dressed_choice(); let ped = choice.ped; let empty = BaseOutfit::default(); - let base = match &self.workbench.wardrobe.dressed.base { + let base = match &self.workbench.wardrobe.dressed.install.base { Base::Ready(mounted) => match mounted.outfits.get(&ped) { Some(Ok(outfit)) => outfit, _ => &empty, @@ -739,7 +764,7 @@ impl AppState { .collect() }) .unwrap_or_default(); - let rows = (self.workbench.wardrobe.dressed.row_wanted.iter()) + let rows = (self.workbench.wardrobe.dressed.cache.row_wanted.iter()) .map(|path| { let stamp = Stamp::of(path).unwrap_or(Stamp { len: 0, @@ -760,10 +785,11 @@ impl AppState { /// Read what the preview lacks, and make the scene the viewport draws of what it has; once a frame. pub(super) fn poll_dressed(&mut self) { // ⚠ A recook that read a tab again also reads the pack's files again: the files are the cook's to change and the stamps below are only the first way to see it. - if self.workbench.wardrobe.dressed.seen_recooked != self.recooked { + if self.workbench.wardrobe.dressed.cache.seen_recooked != self.recooked { let dressed = &mut self.workbench.wardrobe.dressed; - dressed.seen_recooked = self.recooked; + dressed.cache.seen_recooked = self.recooked; dressed + .cache .loaded .retain(|need, _| !matches!(need, Need::Pack(..))); } @@ -771,7 +797,7 @@ impl AppState { self.poll_catalogue(); self.poll_dressed_base(); if self.active_workspace != Workspace::Wardrobe { - self.workbench.wardrobe.dressed.last_tick = None; + self.workbench.wardrobe.dressed.playback.last_tick = None; return; } let ped = self.dressed_ped(); @@ -790,7 +816,8 @@ impl AppState { wanted.extend(slot.texture.clone()); } wanted.extend(plan.tiles.iter().cloned()); - self.workbench.wardrobe.dressed.wanted = wanted.iter().chain(&plan.rows).cloned().collect(); + self.workbench.wardrobe.dressed.cache.wanted = + wanted.iter().chain(&plan.rows).cloned().collect(); let dressed = &self.workbench.wardrobe.dressed; // A file read under an older stamp is no longer the file. let mut missing: Vec = wanted @@ -805,8 +832,8 @@ impl AppState { .cloned() .collect::>(), ); - if !missing.is_empty() && dressed.loading.is_none() { - let install = match &dressed.base { + if !missing.is_empty() && dressed.cache.loading.is_none() { + let install = match &dressed.install.base { Base::Ready(mounted) => Some(Arc::clone(mounted)), _ => None, }; @@ -832,13 +859,13 @@ impl AppState { .collect(); let _ = sender.send(read); }); - self.workbench.wardrobe.dressed.loading = Some(Loading { needs, receiver }); + self.workbench.wardrobe.dressed.cache.loading = Some(Loading { needs, receiver }); } /// Take what a finished read made, and forget the oldest files once there are many. fn take_dressed_reads(&mut self) { - let dressed = &mut self.workbench.wardrobe.dressed; - let Some(loading) = &dressed.loading else { + let cache = &mut self.workbench.wardrobe.dressed.cache; + let Some(loading) = &cache.loading else { return; }; let read = match loading.receiver.try_recv() { @@ -856,34 +883,34 @@ impl AppState { }) .collect(), }; - dressed.loading = None; + cache.loading = None; for (need, loaded) in read { if let (Need::Pack(Kind::Thumb, path, stamp), Loaded::Thumb(thumb)) = (&need, &loaded) { - dressed + cache .thumbs .insert(path.clone(), (*stamp, Arc::clone(thumb))); continue; } - dressed.loaded.insert(need, loaded); + cache.loaded.insert(need, loaded); } // ⚠ The pictures of rows that are no longer asked for go once there are many; one that is asked for and lacks is read again at once. - if dressed.thumbs.len() > KEPT_THUMBS { - let asked: std::collections::HashSet<&PathBuf> = (dressed.wanted.iter()) + if cache.thumbs.len() > KEPT_THUMBS { + let asked: std::collections::HashSet<&PathBuf> = (cache.wanted.iter()) .filter_map(|need| match need { Need::Pack(Kind::Thumb, path, _) => Some(path), _ => None, }) .collect(); - dressed.thumbs.retain(|path, _| asked.contains(path)); + cache.thumbs.retain(|path, _| asked.contains(path)); } // ⚠ Only what the scene and the tiles do not ask for is let go: a file they ask for and lack is read again at once. - if dressed.loaded.len() > KEPT { - let unwanted: Vec = (dressed.loaded.keys()) - .filter(|need| !dressed.wanted.contains(*need)) + if cache.loaded.len() > KEPT { + let unwanted: Vec = (cache.loaded.keys()) + .filter(|need| !cache.wanted.contains(*need)) .cloned() .collect(); - for need in unwanted.into_iter().take(dressed.loaded.len() - KEPT) { - dressed.loaded.remove(&need); + for need in unwanted.into_iter().take(cache.loaded.len() - KEPT) { + cache.loaded.remove(&need); } } } @@ -895,37 +922,40 @@ impl AppState { let mount = self.prefs.mount_options(); let keys = self.keys.has_keys(); let dressed = &mut self.workbench.wardrobe.dressed; - if let Base::Mounting(receiver) = &dressed.base { + if let Base::Mounting(receiver) = &dressed.install.base { match receiver.try_recv() { - Ok(Ok(mounted)) => dressed.base = Base::Ready(mounted), - Ok(Err(why)) => dressed.base = Base::Failed(why), + Ok(Ok(mounted)) => dressed.install.base = Base::Ready(mounted), + Ok(Err(why)) => dressed.install.base = Base::Failed(why), Err(TryRecvError::Empty) => {} Err(TryRecvError::Disconnected) => { - dressed.base = Base::Failed(tr!("the install could not be read").to_string()) + dressed.install.base = + Base::Failed(tr!("the install could not be read").to_string()) } } - if !matches!(dressed.base, Base::Mounting(_)) { + if !matches!(dressed.install.base, Base::Mounting(_)) { // Everything read under the old base is read again with it. dressed + .cache .loaded .retain(|need, _| matches!(need, Need::Pack(..))); } } - if dressed.base_root != root { - dressed.base_root = root.clone(); - dressed.base = Base::Idle; + if dressed.install.base_root != root { + dressed.install.base_root = root.clone(); + dressed.install.base = Base::Idle; dressed + .cache .loaded .retain(|need, _| matches!(need, Need::Pack(..))); } // ⚠ Not before the game's keys are read: an archive that has no key to open it fails the mount, and the failure is not one a retry mends by itself. let ready = keys && self.active_workspace == Workspace::Wardrobe; - if let (Base::Idle, Some(root), true) = (&dressed.base, root, ready) { + if let (Base::Idle, Some(root), true) = (&dressed.install.base, root, ready) { let (sender, receiver) = channel(); std::thread::spawn(move || { let _ = sender.send(mount_install(root, crypto, mount)); }); - dressed.base = Base::Mounting(receiver); + dressed.install.base = Base::Mounting(receiver); } } @@ -961,14 +991,14 @@ impl AppState { /// Whether the scene stands for the choice as the last poll saw it: every file it wants read, and the ped's own drawables read or given up on. pub fn dressed_is_settled(&self) -> bool { let dressed = &self.workbench.wardrobe.dressed; - let base_done = match dressed.base { + let base_done = match dressed.install.base { Base::Ready(_) | Base::Failed(_) => true, - Base::Idle => dressed.base_root.is_none() || !self.keys.has_keys(), + Base::Idle => dressed.install.base_root.is_none() || !self.keys.has_keys(), Base::Mounting(_) => false, }; base_done - && dressed.loading.is_none() - && dressed.wanted.iter().all(|need| dressed.has(need)) + && dressed.cache.loading.is_none() + && dressed.cache.wanted.iter().all(|need| dressed.has(need)) && dressed.scene.is_some() } } @@ -1007,7 +1037,14 @@ mod tests { fn read_the_clip(state: &mut AppState) { state.active_workspace = Workspace::Wardrobe; let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30); - while state.workbench.wardrobe.dressed.reading_clip.is_some() { + while state + .workbench + .wardrobe + .dressed + .playback + .reading_clip + .is_some() + { state.poll_dressed(); assert!( std::time::Instant::now() < deadline, diff --git a/src/state/workbench/dressed/read.rs b/src/state/workbench/dressed/read.rs index a7e08d51e..4aa461bc0 100644 --- a/src/state/workbench/dressed/read.rs +++ b/src/state/workbench/dressed/read.rs @@ -358,7 +358,7 @@ pub(in crate::state::workbench) fn thumb_with( impl super::Dressed { /// The bones of `ped`'s skeleton, as a skin without a skeleton of its own is bound to them: the install's, once read. pub fn bones(&self, ped: Ped) -> Option<&[or_interchange::Bone]> { - match &self.base { + match &self.install.base { super::Base::Ready(mounted) => { mounted.bones.get(&ped)?.as_ref().ok().map(Vec::as_slice) } diff --git a/src/state/workbench/maps_edit.rs b/src/state/workbench/maps_edit.rs index 53cae6dd6..ac55ac486 100644 --- a/src/state/workbench/maps_edit.rs +++ b/src/state/workbench/maps_edit.rs @@ -480,7 +480,7 @@ impl AppState { return; }; for name in typed.iter().filter(|n| !n.trim().is_empty()) { - self.name_index.add( + self.install.name_index.add( crate::state::name_index::NameIndexCategory::Model, name.trim(), ); diff --git a/src/state/workbench/maps_session.rs b/src/state/workbench/maps_session.rs index 9f6031702..22784b1e4 100644 --- a/src/state/workbench/maps_session.rs +++ b/src/state/workbench/maps_session.rs @@ -295,8 +295,8 @@ impl AppState { } } for path in asked { - if !self.reload_conflicts.contains(&path) { - self.reload_conflicts.push(path); + if !self.prompts.reload_conflicts.contains(&path) { + self.prompts.reload_conflicts.push(path); } } for (folder, source) in read_again { diff --git a/src/state/workbench/mod.rs b/src/state/workbench/mod.rs index e1b406196..fd176d1fc 100644 --- a/src/state/workbench/mod.rs +++ b/src/state/workbench/mod.rs @@ -478,6 +478,56 @@ impl Workbench { self.scan.as_ref().map_or(&[], |scan| &scan.packs) } + /// One clothing content by its module id, as the last scan read it. + pub fn pack(&self, module: &str) -> Option<&Pack> { + self.packs().iter().find(|p| p.module == module) + } + + /// Whether a modal question is open on screen. + pub fn is_asking(&self) -> bool { + self.asking.is_some() + } + + /// Present `question` to the user. + pub fn ask(&mut self, question: Question) { + self.asking = Some(question); + } + + /// Choose the build output that the Build button builds. + pub fn select_output(&mut self, output: Option) { + self.selected_output = output; + } + + /// The Wardrobe workspace's state. + pub fn wardrobe(&self) -> &WardrobeWork { + &self.wardrobe + } + + /// Mutable access to the Wardrobe workspace's state. + pub fn wardrobe_mut(&mut self) -> &mut WardrobeWork { + &mut self.wardrobe + } + + /// The dressed ped preview state. + pub fn dressed(&self) -> &Dressed { + &self.wardrobe.dressed + } + + /// Mutable access to the dressed ped preview state. + pub fn dressed_mut(&mut self) -> &mut Dressed { + &mut self.wardrobe.dressed + } + + /// The Weapons workspace's state. + pub fn weapons(&self) -> &WeaponsWork { + &self.weapons + } + + /// Mutable access to the Weapons workspace's state. + pub fn weapons_mut(&mut self) -> &mut WeaponsWork { + &mut self.weapons + } + /// How many peds each addon ped content held when the last scan read it, or why its model could not be read. pub fn peds(&self) -> &[(String, Result)] { self.scan.as_ref().map_or(&[], |scan| &scan.peds) diff --git a/src/state/workbench/wardrobe.rs b/src/state/workbench/wardrobe.rs index 6bb1a5079..7a41e8456 100644 --- a/src/state/workbench/wardrobe.rs +++ b/src/state/workbench/wardrobe.rs @@ -357,6 +357,79 @@ impl WardrobeWork { pub fn undo_label(&self) -> Option<&str> { self.undo.last().map(|step| step.label.as_str()) } + + /// Switch the clothing content shown in the Wardrobe and clear the garment selection. + pub fn select_module(&mut self, module: String) { + self.module = Some(module); + self.selected = None; + } + + /// The id of the currently selected garment, if any. + pub fn selected_garment_id(&self) -> Option<&str> { + self.selected.as_ref().map(|(_, id)| id.as_str()) + } + + /// Consume any pending request to focus the rename input. + pub fn take_rename_request(&mut self) -> bool { + std::mem::take(&mut self.rename_asked) + } + + /// Whether the docked quick-look panel is open. + pub fn is_quick_look_open(&self) -> bool { + self.quick_look + } + + /// Close the docked quick-look panel. + pub fn close_quick_look(&mut self) { + self.quick_look = false; + } + + /// Generation counter bumped whenever the scanned packs change. + pub fn generation(&self) -> u64 { + self.generation + } + + /// Earlier versions of the current pack, once loaded. + pub fn versions(&self) -> Option<&super::Versions> { + self.versions.as_ref() + } + + /// Read-only access to the mesh doctor state. + pub fn mesh(&self) -> &super::MeshDesk { + &self.mesh + } + + /// Toggle flag for whether Fix all safe also adds missing LOD levels. + pub fn fix_levels_mut(&mut self) -> &mut bool { + &mut self.mesh.fix_levels + } + + /// Update the target shares and replacement flag for LOD generation. + pub fn set_mesh_levels(&mut self, medium: u8, low: u8, replace: bool) { + (self.mesh.medium, self.mesh.low, self.mesh.replace) = (medium, low, replace); + } + + /// Show or hide the previous model replaced by the last mesh-doctor step. + pub fn set_mesh_show_before(&mut self, shown: bool) { + if let Some(before) = self.mesh.before.as_mut() { + before.shown = shown; + } + } + + /// Watched external-editor folder bindings belonging to `garment`. + pub fn bindings_for_garment(&self, garment: &str) -> Vec<&or_wardrobe::slots::Binding> { + self.textures + .bindings() + .iter() + .map(|(_, _, b)| b) + .filter(|b| b.garment == garment) + .collect() + } + + /// Mutable access to the quick-look thumbnail reader. + pub fn glance_mut(&mut self) -> &mut super::Glance { + &mut self.glance + } } impl AppState { @@ -736,7 +809,7 @@ impl AppState { /// Put the image dropped on a tile into the texture of that tile's variation. pub fn replace_dropped_image(&mut self, image: PathBuf) { - if let Some((garment, variation)) = self.workbench.wardrobe.dressed.drop_tile.take() { + if let Some((garment, variation)) = self.workbench.dressed_mut().take_drop_tile() { self.replace_variation_image(garment, variation, image); } } diff --git a/src/state/workbench/weapons.rs b/src/state/workbench/weapons.rs index 7a68013c1..116ea1899 100644 --- a/src/state/workbench/weapons.rs +++ b/src/state/workbench/weapons.rs @@ -115,6 +115,87 @@ pub struct WeaponsWork { pub adding: Option<(usize, String)>, } +impl WeaponsWork { + /// Submit or clear the preview scene request, poll for completion, and report whether a read is still in flight. + pub fn sync_preview( + &mut self, + request: Option, + crypto: std::sync::Arc, + ) -> bool { + match request { + Some(request) => self.scene.want(request, crypto), + None => self.scene.clear(), + } + self.scene.poll(); + self.scene.is_reading() + } + + /// The assembled weapon scene ready to render, if any. + pub fn preview_scene(&self) -> Option<&super::dressed::scene::DressedScene> { + self.scene.scene.as_ref() + } + + /// Overlay status caption for the weapon preview when no model is drawn or a read is in flight. + pub fn preview_status(&self) -> Option { + match (&self.scene.error, self.scene.is_reading()) { + (Some(why), _) => Some(why.clone()), + (None, true) => Some(tr!("Reading the files…").to_string()), + (None, false) if self.scene.scene.is_none() => { + Some(tr!("The weapon has no model in the pack to draw").to_string()) + } + _ => None, + } + } + + /// The active shading/view mode for the assembled weapon. + pub fn view_mode(&self) -> ViewMode { + self.view + } + + /// Change the shading/view mode for the assembled weapon. + pub fn set_view_mode(&mut self, mode: ViewMode) { + self.view = mode; + } + + /// The component choices currently worn on each attach bone. + pub fn choice(&self) -> &Choice { + &self.choice + } + + /// Pick `component` (or none) for `bone` in the assembled weapon preview. + pub fn choose_part(&mut self, bone: String, component: Option) { + self.choice.insert(bone, component); + } + + /// The current weapon list filter text. + pub fn filter(&self) -> &str { + &self.filter + } + + /// Mutable access to the weapon list filter text. + pub fn filter_mut(&mut self) -> &mut String { + &mut self.filter + } + + /// The id of the currently selected weapon, if any. + pub fn selected_id(&self) -> Option<&str> { + self.selected.as_deref() + } + + /// Mutable reference to the in-progress rename text for weapon `id`, initialized to `current`. + pub fn rename_draft(&mut self, id: &str, current: &str) -> &mut String { + match &mut self.renaming { + Some((held, typed)) if held == id => typed, + slot => &mut slot.insert((id.to_string(), current.to_string())).1, + } + } + + /// Clear any in-progress weapon rename buffer. + pub fn clear_rename(&mut self) { + self.renaming = None; + } +} + impl Workbench { /// The weapons contents as the last scan read them. pub fn weapons_read(&self) -> &[WeaponsRead] { diff --git a/src/ui/commands/files.rs b/src/ui/commands/files.rs index 2151b769d..4a367736e 100644 --- a/src/ui/commands/files.rs +++ b/src/ui/commands/files.rs @@ -765,12 +765,12 @@ fn paths(state: &AppState, target: &Target) -> Result, &'static str> fn hit_paths(state: &AppState, list: Hits, rows: &[usize]) -> Vec { match list { Hits::Search => (rows.iter()) - .filter_map(|&row| state.search.hits.get(row)) + .filter_map(|&row| state.find.session.hits.get(row)) .map(crate::state::search_session::hit_path) .collect(), Hits::Inside(doc) => { let pattern = hierarchy::ui_state_ref(state).map_or("", |ui| ui.filter.trim()); - let Some(found) = state.deep_find.found_for(doc, pattern) else { + let Some(found) = state.find.deep.found_for(doc, pattern) else { return Vec::new(); }; (rows.iter()) diff --git a/src/ui/commands/target.rs b/src/ui/commands/target.rs index 82814f5ac..af42b4f2e 100644 --- a/src/ui/commands/target.rs +++ b/src/ui/commands/target.rs @@ -77,7 +77,7 @@ pub fn selection(state: &AppState) -> Result { let is_tree = |payload: &DocPayload| matches!(payload, DocPayload::Rpf(_)); match state.workspace_docks.focused(state.active_workspace) { Some(ids::FILES) => match open(is_tree).filter(|&doc| searched_inside(state, doc)) { - Some(doc) => hits(&state.deep_find.selection, Hits::Inside(doc)), + Some(doc) => hits(&state.find.deep.selection, Hits::Inside(doc)), None => in_files(state), }, Some(ids::DOCUMENT | ids::META_EDITOR) if open(is_meta).is_some() => open(is_meta) @@ -104,7 +104,7 @@ pub fn selection(state: &AppState) -> Result { centre: true, }) } - Some(ids::SEARCH) => hits(&state.search.selection, Hits::Search), + Some(ids::SEARCH) => hits(&state.find.session.selection, Hits::Search), Some(ids::OUTLINE) => { let doc = open(|p| { matches!( @@ -229,7 +229,7 @@ fn in_files(state: &AppState) -> Result { fn searched_inside(state: &AppState, doc: DocumentId) -> bool { hierarchy::ui_state_ref(state).is_some_and(|ui| { let pattern = ui.filter.trim(); - ui.deep && state.deep_find.found_for(doc, pattern).is_some() + ui.deep && state.find.deep.found_for(doc, pattern).is_some() }) } diff --git a/src/ui/commands/tools_and_help.rs b/src/ui/commands/tools_and_help.rs index bd2f28b6d..78ea84d51 100644 --- a/src/ui/commands/tools_and_help.rs +++ b/src/ui/commands/tools_and_help.rs @@ -13,15 +13,23 @@ pub(super) const BAKE_SHADERS: Spec = Spec { "Translate your install's shaders so the viewport draws models as the \ game does. Runs in the background, once; later launches reuse the result." ), - enabled: |state| none_if(state.game_pack.is_baking(), tr!("A bake is under way")), + enabled: |state| { + none_if( + state.install.game_pack.is_baking(), + tr!("A bake is under way"), + ) + }, label_now: Some(|state| { use crate::state::GamePackStatus; - if state.game_pack.is_baking() { + if state.install.game_pack.is_baking() { tr!( "{short_label} (View ▸ Background jobs cancels it)", - short_label = state.game_pack.status().short_label() + short_label = state.install.game_pack.status().short_label() ) - } else if matches!(state.game_pack.status(), GamePackStatus::Ready { .. }) { + } else if matches!( + state.install.game_pack.status(), + GamePackStatus::Ready { .. } + ) { tr!("Re-bake game shaders").to_string() } else { tr!("Bake game shaders").to_string() diff --git a/src/ui/os_drop.rs b/src/ui/os_drop.rs index 80b8c38dd..43611aeec 100644 --- a/src/ui/os_drop.rs +++ b/src/ui/os_drop.rs @@ -99,7 +99,7 @@ fn target_at(ctx: &egui::Context, state: &mut AppState, p: egui::Pos2) -> DropTa { // A tile of a texture variation takes the image for its own texture; the rest of the Wardrobe adds clothes. if let Some(tile) = crate::ui::panels::wardrobe::variant_at(ctx, state, p) { - state.workbench.wardrobe.dressed.drop_tile = Some(tile); + state.workbench.dressed_mut().set_drop_tile(tile); return DropTarget::Variant; } return DropTarget::Wardrobe; @@ -270,9 +270,9 @@ fn paint_hint( ) } DropTarget::Variant => { - if let Some((garment, variation)) = state.workbench.wardrobe.dressed.drop_tile.clone() { + if let Some((garment, variation)) = state.workbench.dressed().drop_tile() { if let Some(rect) = - crate::ui::panels::wardrobe::variant_rect(state, &garment, variation) + crate::ui::panels::wardrobe::variant_rect(state, garment, variation) { outline(rect.shrink(1.0), 4.0, egui::StrokeKind::Inside); } diff --git a/src/ui/panels/command_palette.rs b/src/ui/panels/command_palette.rs index b042ed1ec..56e68895b 100644 --- a/src/ui/panels/command_palette.rs +++ b/src/ui/panels/command_palette.rs @@ -46,7 +46,7 @@ pub fn open(state: &mut AppState) { pub fn go_to_file(state: &mut AppState) { open_with(state, ""); // Each opening looks again for what changed on disk outside the tree. - state.file_index.recheck = true; + state.find.file_index.recheck = true; } fn open_with(state: &mut AppState, query: &'static str) { @@ -54,7 +54,7 @@ fn open_with(state: &mut AppState, query: &'static str) { palette.open = true; palette.opening = Some(query); palette.highlighted = 0; - state.file_index.forget_search(); + state.find.file_index.forget_search(); } pub fn draw(ctx: &egui::Context, state: &mut AppState) { @@ -263,7 +263,7 @@ fn draw_files( "Type a file's name, such as adder, or the hash of one, such as {example}", example = format!("0x{example:08X}") ) - } else if state.file_index.is_walking() || working { + } else if state.find.file_index.is_walking() || working { tr!("Nothing matches yet").to_string() } else { tr!("No file matches").to_string() @@ -341,7 +341,7 @@ fn draw_problems(ui: &mut egui::Ui, problems: &[String]) { /// How far the index has come, where its results are listed. fn draw_index_status(ui: &mut egui::Ui, state: &AppState) { - let index = &state.file_index; + let index = &state.find.file_index; let files = index.files(); let secondary = |text: String| { egui::RichText::new(text) @@ -392,7 +392,7 @@ fn offers( let palette = state.panels.get_or_default_mut::(); let install = state.prefs.active_game_root().map(|root| root.as_path()); let recent = &palette.recent_files; - let found = (state.file_index).find(seeker, query, palette.scope, install, recent, SHOWN); + let found = (state.find.file_index).find(seeker, query, palette.scope, install, recent, SHOWN); if found.1 { ctx.request_repaint_after(AWAITING); } @@ -424,7 +424,7 @@ fn go(state: &mut AppState, offer: Offer, reveal: bool) { palette.recent_files.retain(|known| *known != offer); palette.recent_files.insert(0, offer.clone()); palette.recent_files.truncate(REMEMBERED); - state.file_index.forget_search(); + state.find.file_index.forget_search(); let then = if reveal { Arrival::Reveal } else { @@ -451,7 +451,7 @@ pub(crate) fn begin_finding(state: &mut AppState) { .panels .get_or_default_mut::() .highlighted = 0; - state.file_index.forget_search(); + state.find.file_index.forget_search(); } /// The first row is the highlighted one again, which a change of the words asks for. diff --git a/src/ui/panels/dlc_pack.rs b/src/ui/panels/dlc_pack.rs index e7b4c1560..8dea0d652 100644 --- a/src/ui/panels/dlc_pack.rs +++ b/src/ui/panels/dlc_pack.rs @@ -25,7 +25,7 @@ pub fn draw(ctx: &egui::Context, state: &mut AppState) { } fn draw_question(ctx: &egui::Context, state: &mut AppState) { - let Some(asked) = state.dlc_pack.asked.as_mut() else { + let Some(asked) = state.bg.dlc_pack.asked.as_mut() else { return; }; let mut answer: Option = None; @@ -151,13 +151,13 @@ fn draw_question(ctx: &egui::Context, state: &mut AppState) { state.create_dlc_pack(dest); } } - Some(false) => state.dlc_pack.asked = None, + Some(false) => state.bg.dlc_pack.asked = None, None => {} } } fn draw_built(ctx: &egui::Context, state: &mut AppState) { - let Some(built) = &state.dlc_pack.built else { + let Some(built) = &state.bg.dlc_pack.built else { return; }; let mut close = false; @@ -186,6 +186,6 @@ fn draw_built(ctx: &egui::Context, state: &mut AppState) { }); }); if close { - state.dlc_pack.built = None; + state.bg.dlc_pack.built = None; } } diff --git a/src/ui/panels/edit_mode.rs b/src/ui/panels/edit_mode.rs index 06233d97c..a889a6458 100644 --- a/src/ui/panels/edit_mode.rs +++ b/src/ui/panels/edit_mode.rs @@ -42,7 +42,7 @@ pub fn choice(ui: &mut egui::Ui, label: &str, sentence: &str, selected: bool) -> /// /// ⚠ No "don't ask again": what it changes is the mode, which stays in view. pub fn draw_refused_write(ctx: &egui::Context, state: &mut AppState) { - let Some(path) = state.refused_write.clone() else { + let Some(path) = state.prompts.refused_write.clone() else { return; }; let current = state.prefs.edit_mode; @@ -68,6 +68,6 @@ pub fn draw_refused_write(ctx: &egui::Context, state: &mut AppState) { state.set_edit_mode(mode); } if chosen.is_some() || close { - state.refused_write = None; + state.prompts.refused_write = None; } } diff --git a/src/ui/panels/file_prompts.rs b/src/ui/panels/file_prompts.rs index 18b714374..fe06122c6 100644 --- a/src/ui/panels/file_prompts.rs +++ b/src/ui/panels/file_prompts.rs @@ -34,7 +34,7 @@ enum Answer { /// What a glTF export carries before it is written, and what an import replaces before the model changes. fn draw_gltf(ctx: &egui::Context, state: &mut AppState) { let mut answer = None; - let rerun = match &mut state.gltf.asked { + let rerun = match &mut state.bg.gltf.asked { Some(Asked::Export(asked)) => { let title = tr!("Export {name} to glTF", name = asked.name); question_within(ctx, &title, 640.0, |ui| export_body(ui, asked, &mut answer)) @@ -60,7 +60,7 @@ fn draw_gltf(ctx: &egui::Context, state: &mut AppState) { } Some(Answer::Import) => state.apply_gltf_import(), Some(Answer::Cancel) => { - state.gltf.cancel(); + state.bg.gltf.cancel(); } None => {} } @@ -339,10 +339,10 @@ fn import_body(ui: &mut egui::Ui, asked: &mut Import, answer: &mut Option state.convert.done = None, + Some(false) => state.bg.convert.done = None, None => {} } } @@ -424,7 +424,7 @@ fn report_line(ui: &mut egui::Ui, text: &str) { } fn draw_delete(ctx: &egui::Context, state: &mut AppState) { - let Some(asked) = state.pending_delete.clone() else { + let Some(asked) = state.prompts.delete.clone() else { return; }; let mut answer: Option = None; @@ -451,8 +451,11 @@ fn draw_delete(ctx: &egui::Context, state: &mut AppState) { /// The files an extraction or a conversion finds already in its folder, asked about once for the whole job. fn draw_clash(ctx: &egui::Context, state: &mut AppState) { - let converting = state.extract_jobs.clash.is_none(); - let (asked, dest, made) = match (state.extract_jobs.clash.as_ref(), &state.convert.clash) { + let converting = state.bg.extract_jobs.clash.is_none(); + let (asked, dest, made) = match ( + state.bg.extract_jobs.clash.as_ref(), + &state.bg.convert.clash, + ) { (Some(clash), _) => (clash.question(), &clash.dest, "extracted"), (None, Some(clash)) => (clash.question(), &clash.dest, "converted"), (None, None) => return, diff --git a/src/ui/panels/gallery.rs b/src/ui/panels/gallery.rs index 09f90b8d7..0e0b00d50 100644 --- a/src/ui/panels/gallery.rs +++ b/src/ui/panels/gallery.rs @@ -804,7 +804,7 @@ fn tile_picture( ) -> Tile { let view = ChannelView::preview_default(tex.format); let key = (doc_id, tex.name.clone(), view); - if let Some(tile) = state.texture_cache.tile(ctx, &key) { + if let Some(tile) = state.textures.cache.tile(ctx, &key) { return tile; } let held = state.document(doc_id).and_then(|d| { @@ -822,7 +822,7 @@ fn tile_picture( // A GTA VI drawable's listing knows no format: its texture lies in another document. None => textures::resolved_for_gta6(state, doc_id, None, &tex.name), }; - (state.texture_cache).ask_tile(ctx, key, TILE_PICTURE_SIDE, texture) + (state.textures.cache).ask_tile(ctx, key, TILE_PICTURE_SIDE, texture) } #[derive(Clone, Copy)] diff --git a/src/ui/panels/game_picker.rs b/src/ui/panels/game_picker.rs index 29ae59780..78ab7f638 100644 --- a/src/ui/panels/game_picker.rs +++ b/src/ui/panels/game_picker.rs @@ -98,7 +98,7 @@ fn draw_installs(ui: &mut egui::Ui, state: &mut AppState) { } } } - if state.discovery.is_running() { + if state.bg.discovery.is_running() { ui.horizontal(|ui| { ui.spinner(); ui.label( diff --git a/src/ui/panels/gxt2_table.rs b/src/ui/panels/gxt2_table.rs index 16b52582c..641f4df99 100644 --- a/src/ui/panels/gxt2_table.rs +++ b/src/ui/panels/gxt2_table.rs @@ -103,7 +103,7 @@ pub fn draw(ui: &mut egui::Ui, state: &mut AppState) { key == typed || hex_contains(key, hash_needle) || contains_ascii_lowercase(value, &needle) - || (state.name_index.name_of(key)) + || (state.install.name_index.name_of(key)) .is_some_and(|n| contains_ascii_lowercase(n, &needle)) }) }) @@ -174,7 +174,7 @@ pub fn draw(ui: &mut egui::Ui, state: &mut AppState) { Some(DocPayload::Gta6Text(t)) => match t.row(entry_idx) { Some((hash, form, text)) => { let line = crate::state::gta6_dialogue::line_of(hash); - let name = match state.name_index.name_of(hash) { + let name = match state.install.name_index.name_of(hash) { Some(name) => name.to_string(), None if hash == typed => query.trim().to_string(), // A dialogue line names its label. diff --git a/src/ui/panels/hierarchy/defrag.rs b/src/ui/panels/hierarchy/defrag.rs index 382fb8f3a..6fd6d17aa 100644 --- a/src/ui/panels/hierarchy/defrag.rs +++ b/src/ui/panels/hierarchy/defrag.rs @@ -6,7 +6,7 @@ use crate::ui::theme; /// The size preview that asks before a defragment writes. pub(super) fn draw_defrag(ctx: &egui::Context, state: &mut AppState) { - let Some(offer) = &state.defrag.offer else { + let Some(offer) = &state.bg.defrag.offer else { return; }; let (before, after) = (offer.before, offer.after); diff --git a/src/ui/panels/hierarchy/files/folder_view.rs b/src/ui/panels/hierarchy/files/folder_view.rs index 9490efd98..b87cfc9ca 100644 --- a/src/ui/panels/hierarchy/files/folder_view.rs +++ b/src/ui/panels/hierarchy/files/folder_view.rs @@ -132,7 +132,7 @@ pub(super) fn draw_listing( let mut asked: Option = None; if listing.order.is_empty() { - let busy = state.expander.is_in_flight(doc, listing.folder); + let busy = state.bg.expander.is_in_flight(doc, listing.folder); // An archive that did not open is not an empty folder: it says why it did not. let refused = match state.document(doc).map(|d| &d.payload) { Some(DocPayload::Rpf(rpf)) => match rpf.session.node(listing.folder) { @@ -252,7 +252,7 @@ fn row_of(state: &AppState, doc: DocumentId, id: RpfNodeId) -> Option { }; Some(Row { supported: node.is_dir() || rpf_path_supported(&icon_node.name) || kind.is_some(), - in_flight: state.expander.is_in_flight(doc, id), + in_flight: state.bg.expander.is_in_flight(doc, id), unsaved: rpf.session.archive_unsaved(id), node, icon_node, diff --git a/src/ui/panels/hierarchy/files/mod.rs b/src/ui/panels/hierarchy/files/mod.rs index c5061b87a..f2554c5e3 100644 --- a/src/ui/panels/hierarchy/files/mod.rs +++ b/src/ui/panels/hierarchy/files/mod.rs @@ -154,7 +154,7 @@ fn filter_row(ui: &mut egui::Ui, state: &mut AppState) { .clicked() { ui_state(state).filter.clear(); - state.deep_find.clear(); + state.find.deep.clear(); } let mut toggled = deep; let search = crate::ui::accessible_name::named( @@ -170,7 +170,7 @@ fn filter_row(ui: &mut egui::Ui, state: &mut AppState) { .changed() { ui_state(state).deep = toggled; - state.deep_find.clear(); + state.find.deep.clear(); } }); } diff --git a/src/ui/panels/hierarchy/navigation.rs b/src/ui/panels/hierarchy/navigation.rs index eea1485c1..0f1de4ec5 100644 --- a/src/ui/panels/hierarchy/navigation.rs +++ b/src/ui/panels/hierarchy/navigation.rs @@ -97,7 +97,7 @@ pub(crate) fn go_to_file(state: &mut AppState) { (state.workspace_docks).reveal(on_screen, crate::ui::panels::registry::ids::FILES); state.hide_start_page(); // Each asking looks again for what changed on disk outside the tree. - state.file_index.recheck = true; + state.find.file_index.recheck = true; crate::ui::panels::command_palette::begin_finding(state); let files = ui_state(state); files.filter.clear(); @@ -151,7 +151,7 @@ pub(super) fn escalate_button(ui: &mut egui::Ui, state: &mut AppState, filter: & let hierarchy = ui_state(state); hierarchy.filter = explorer::escalated_glob(filter); hierarchy.deep = true; - state.deep_find.clear(); + state.find.deep.clear(); } } diff --git a/src/ui/panels/hierarchy/rpf.rs b/src/ui/panels/hierarchy/rpf.rs index 66ddcb5c8..711ed62aa 100644 --- a/src/ui/panels/hierarchy/rpf.rs +++ b/src/ui/panels/hierarchy/rpf.rs @@ -132,7 +132,7 @@ const SHOWN: usize = 1_000; /// the index and not in `RpfEditSession` until somebody expands its way down. fn draw_deep_find(ui: &mut egui::Ui, state: &mut AppState, doc_id: DocumentId, pattern: &str) { state.deep_find_tick(doc_id, pattern); - let Some(found) = state.deep_find.found_for(doc_id, pattern) else { + let Some(found) = state.find.deep.found_for(doc_id, pattern) else { return; }; let total = found.matches().len(); @@ -211,7 +211,7 @@ fn draw_deep_find(ui: &mut egui::Ui, state: &mut AppState, doc_id: DocumentId, p }; let text = egui::RichText::new(path).color(color); ui.add_space(ui.spacing().indent); - let selection = &mut state.deep_find.selection; + let selection = &mut state.find.deep.selection; let resp = search::result_row(ui, selection, row, rows, text); search::hits_menu(&resp, state, list, row, &mut asked); if resp.double_clicked() { @@ -373,7 +373,7 @@ pub(super) fn rpf_context_menu( } else if ui .add_enabled( state.prefs.edit_mode.permits_overlay() - && state.overlay_copy.running().is_none(), + && state.bg.overlay_copy.running().is_none(), egui::Button::new(crate::ui::commands::behind_gutter(tr!( "Copy to mods overlay…" ))), @@ -392,6 +392,7 @@ pub(super) fn rpf_context_menu( let copy = crate::state::retail::overlay_copy_target(archive, &state.prefs) .unwrap_or_else(|| archive.to_path_buf()); state + .bg .overlay_copy .stale_copy(©) .map(|stale| stale.copy.clone()) @@ -400,7 +401,7 @@ pub(super) fn rpf_context_menu( if ui .add_enabled( state.prefs.edit_mode.permits_overlay() - && state.overlay_copy.running().is_none(), + && state.bg.overlay_copy.running().is_none(), egui::Button::new(crate::ui::commands::behind_gutter(tr!( "Refresh from the patched archive…" ))), @@ -422,7 +423,7 @@ pub(super) fn rpf_context_menu( if state.defrag_target(doc_id, node_id).is_some() && ui .add_enabled( - !state.defrag.is_running() && state.defrag.offer.is_none(), + !state.bg.defrag.is_running() && state.bg.defrag.offer.is_none(), egui::Button::new(crate::ui::commands::behind_gutter(tr!("Defragment…"))), ) .on_hover_text(tr!( diff --git a/src/ui/panels/hierarchy/rpf_tree.rs b/src/ui/panels/hierarchy/rpf_tree.rs index 70aee2b20..57cdb5c8a 100644 --- a/src/ui/panels/hierarchy/rpf_tree.rs +++ b/src/ui/panels/hierarchy/rpf_tree.rs @@ -338,7 +338,7 @@ pub(super) fn list_rows( expand.push(id); } let children = explorer::sorted_children_at(session, epoch, id, sort); - if shown && children.is_empty() && state.expander.is_in_flight(doc_id, id) { + if shown && children.is_empty() && state.bg.expander.is_in_flight(doc_id, id) { rows.push(ListedRow { node: id, depth: depth + 1, @@ -465,7 +465,7 @@ pub(super) fn draw_row( let key = SelectionKey::ArchiveNode(node_id); let selected = state.selection.is_selected(doc_id, key); let sole = state.selection.selected_ids(doc_id) == [key]; - let in_flight = state.expander.is_in_flight(doc_id, node_id); + let in_flight = state.bg.expander.is_in_flight(doc_id, node_id); let mut taken_rename: Option = if super::ui_state(state).is_renaming_rpf(doc_id, node_id) { @@ -490,7 +490,7 @@ pub(super) fn draw_row( let outgrown = node .backing .fs_path() - .is_some_and(|path| state.overlay_copy.stale_copy(path).is_some()); + .is_some_and(|path| state.bg.overlay_copy.stale_copy(path).is_some()); let label_color = if selected { theme::ACCENT_TEXT } else if archive_open_error.is_some() && !scans { diff --git a/src/ui/panels/hierarchy/ycd.rs b/src/ui/panels/hierarchy/ycd.rs index 66bc927f3..a9d504e20 100644 --- a/src/ui/panels/hierarchy/ycd.rs +++ b/src/ui/panels/hierarchy/ycd.rs @@ -95,7 +95,7 @@ pub(super) fn draw_ycd( if resp.clicked() { state.selection.select(doc_id, sel); state.preview_scene.set_clip(doc_id, *key); - state.anim.invalidate(); + state.animation.session.invalidate(); } }); } diff --git a/src/ui/panels/inspector/gta6/dialogue.rs b/src/ui/panels/inspector/gta6/dialogue.rs index ce0eea03a..dd3fc4d6e 100644 --- a/src/ui/panels/inspector/gta6/dialogue.rs +++ b/src/ui/panels/inspector/gta6/dialogue.rs @@ -200,7 +200,7 @@ fn draw_station( /// shown name of the station of the wheel it is the twin of where it is one; else its key. fn hidden_name(state: &AppState, lines: &Lines, language: &str, station: &Station) -> String { let Some(name) = lines.station_name(station.key) else { - return hash_text(station.key, state.name_index.name_of(station.key)); + return hash_text(station.key, state.install.name_index.name_of(station.key)); }; let twin = name .strip_prefix("hidden_") diff --git a/src/ui/panels/inspector/gta6/text.rs b/src/ui/panels/inspector/gta6/text.rs index d49eeb106..a5504aa01 100644 --- a/src/ui/panels/inspector/gta6/text.rs +++ b/src/ui/panels/inspector/gta6/text.rs @@ -221,7 +221,7 @@ fn draw_audio_items(ui: &mut egui::Ui, state: &AppState, doc_id: DocumentId) -> let pool = pool_names(); let name = |key: u32| { let pooled = pool.get(&key).map(String::as_str); - match pooled.or_else(|| state.name_index.name_of(key)) { + match pooled.or_else(|| state.install.name_index.name_of(key)) { Some(known) => hash_text(key, Some(known)), None => hash_text(key, crate::state::hash_text_name(key).as_deref()), } diff --git a/src/ui/panels/inspector/gta6/text_entries.rs b/src/ui/panels/inspector/gta6/text_entries.rs index a99d655a6..d6e61b8c4 100644 --- a/src/ui/panels/inspector/gta6/text_entries.rs +++ b/src/ui/panels/inspector/gta6/text_entries.rs @@ -215,7 +215,7 @@ fn results(ui: &mut egui::Ui, state: &AppState, running: bool) -> Option .show(ui, |ui| { for group in searched.groups.iter_mut().take(SHOWN) { let key = group.key; - let name = state.name_index.name_of(key); + let name = state.install.name_index.name_of(key); ui.strong(match name { Some(name) => format!("{name} {key:#010X}"), None => format!("{key:#010X}"), diff --git a/src/ui/panels/inspector/move_network.rs b/src/ui/panels/inspector/move_network.rs index 421be5bc0..d74f69052 100644 --- a/src/ui/panels/inspector/move_network.rs +++ b/src/ui/panels/inspector/move_network.rs @@ -16,7 +16,8 @@ pub(super) fn draw_move_network(ui: &mut egui::Ui, state: &mut AppState, doc_id: } }; let name = |hash: u32| { - (state.name_index.name_of(hash)).map_or_else(|| hash_text(hash, None), str::to_string) + (state.install.name_index.name_of(hash)) + .map_or_else(|| hash_text(hash, None), str::to_string) }; let edges = network.edges(); ui.label(format!( diff --git a/src/ui/panels/inspector/structure.rs b/src/ui/panels/inspector/structure.rs index 41ee69182..fb681ad00 100644 --- a/src/ui/panels/inspector/structure.rs +++ b/src/ui/panels/inspector/structure.rs @@ -118,9 +118,11 @@ pub(super) fn draw_editable_summary( // Each hash row's name, read before the rows' menus borrow the state. let names: Vec> = (summary.rows.iter()) .map(|r| match (&r.held, r.hash) { - (Some(ScalarValue::Int(v)), true) => { - state.name_index.name_of(*v as u32).map(str::to_string) - } + (Some(ScalarValue::Int(v)), true) => state + .install + .name_index + .name_of(*v as u32) + .map(str::to_string), _ => None, }) .collect(); diff --git a/src/ui/panels/inspector/ycd.rs b/src/ui/panels/inspector/ycd.rs index 2c3027b96..9c90a899e 100644 --- a/src/ui/panels/inspector/ycd.rs +++ b/src/ui/panels/inspector/ycd.rs @@ -55,7 +55,11 @@ pub(super) fn draw_ycd( ui.separator(); grid(ui, "ycd_clip", |ui| { - row(ui, "Key", &hash_text(key, state.name_index.name_of(key))); + row( + ui, + "Key", + &hash_text(key, state.install.name_index.name_of(key)), + ); row( ui, "Type", diff --git a/src/ui/panels/inspector/ydd.rs b/src/ui/panels/inspector/ydd.rs index 9cdba96dd..39c390df3 100644 --- a/src/ui/panels/inspector/ydd.rs +++ b/src/ui/panels/inspector/ydd.rs @@ -68,7 +68,7 @@ pub(super) fn draw_ydd( ), ( "Hash".into(), - hash_text(code, state.name_index.name_of(code)), + hash_text(code, state.install.name_index.name_of(code)), ), ]; facts.extend(drawable_facts( diff --git a/src/ui/panels/inspector/yld.rs b/src/ui/panels/inspector/yld.rs index e32e9a99e..37bd623ee 100644 --- a/src/ui/panels/inspector/yld.rs +++ b/src/ui/panels/inspector/yld.rs @@ -79,7 +79,10 @@ pub(super) fn draw_yld( row( ui, "Hash", - &hash_text(dict.codes[idx], state.name_index.name_of(dict.codes[idx])), + &hash_text( + dict.codes[idx], + state.install.name_index.name_of(dict.codes[idx]), + ), ); row(ui, "Name", cloth_name(cloth)); row(ui, "Active", &cloth.is_active.get().to_string()); diff --git a/src/ui/panels/maps/mod.rs b/src/ui/panels/maps/mod.rs index d5e8d1ff2..71ce6b59c 100644 --- a/src/ui/panels/maps/mod.rs +++ b/src/ui/panels/maps/mod.rs @@ -65,7 +65,13 @@ pub fn accepts_drop_at(ctx: &egui::Context, state: &AppState, at: egui::Pos2) -> pub(super) fn shown(state: &AppState, name: &or_maps::Name) -> String { name.text .clone() - .or_else(|| state.name_index.name_of(name.hash).map(str::to_string)) + .or_else(|| { + state + .install + .name_index + .name_of(name.hash) + .map(str::to_string) + }) .unwrap_or_else(|| name.shown()) } diff --git a/src/ui/panels/menu.rs b/src/ui/panels/menu.rs index a468dccb6..fde61fd5a 100644 --- a/src/ui/panels/menu.rs +++ b/src/ui/panels/menu.rs @@ -184,7 +184,7 @@ fn what_the_banner_says(state: &AppState) -> Option<(theme::Themed, String, Stri let (colour, text) = match mode { EditMode::ReadOnly => (theme::TEXT_DIM, tr!("Read only")), EditMode::Overlay => (theme::INFO, tr!("Editing: mods overlay")), - EditMode::Everything if state.retail_edit_session_allow => { + EditMode::Everything if state.prompts.retail_edit_session_allow => { (theme::ERROR, tr!("Editing: BASE GAME (confirmed)")) } EditMode::Everything => (theme::WARNING, tr!("Editing: base game")), @@ -613,7 +613,7 @@ fn tools_menu(ui: &mut egui::Ui, state: &mut AppState) { item(ui, state, Action::HarvestGta6Names); ui.separator(); ui.label( - egui::RichText::new(state.game_pack.status().short_label()) + egui::RichText::new(state.install.game_pack.status().short_label()) .color(theme::TEXT_SECONDARY), ); diff --git a/src/ui/panels/meta_editor/mod.rs b/src/ui/panels/meta_editor/mod.rs index f2ea0046c..a8da211c7 100644 --- a/src/ui/panels/meta_editor/mod.rs +++ b/src/ui/panels/meta_editor/mod.rs @@ -76,7 +76,7 @@ fn draw_visual_view(ui: &mut egui::Ui, state: &mut AppState, doc_id: crate::stat // ⚠ Built only for an open picker: sorting every name the install holds took 150 ms, again each // frame the scan added names. let name_index = match picker::any_picker_open(ui.ctx()) { - true => state.name_index.snapshot(), + true => state.install.name_index.snapshot(), false => Default::default(), }; let text_names = match state.document(doc_id).map(|d| &d.payload) { @@ -101,15 +101,21 @@ fn draw_visual_view(ui: &mut egui::Ui, state: &mut AppState, doc_id: crate::stat let tables = match &install { Some(root) => { let crypto = state.keys.provider(); - state.game_tables.ensure(root.clone(), crypto, mount); - state.game_tables.poll_current() + state + .install + .game_tables + .ensure(root.clone(), crypto, mount); + state.install.game_tables.poll_current() } None => Default::default(), }; let interiors = match (places_an_interior, install) { (true, Some(root)) => { - state.interiors.ensure(root, state.keys.provider(), mount); - state.interiors.poll_current() + state + .install + .interiors + .ensure(root, state.keys.provider(), mount); + state.install.interiors.poll_current() } _ => Default::default(), }; diff --git a/src/ui/panels/mods.rs b/src/ui/panels/mods.rs index fabc23d69..4fff8168c 100644 --- a/src/ui/panels/mods.rs +++ b/src/ui/panels/mods.rs @@ -20,10 +20,10 @@ struct Asked { } pub fn draw(ui: &mut egui::Ui, state: &mut AppState) { - if state.mod_manager.root.as_ref() != state.prefs.active_game_root() { + if state.bg.mod_manager.root.as_ref() != state.prefs.active_game_root() { state.refresh_mods(); } - let Some(root) = state.mod_manager.root.clone() else { + let Some(root) = state.bg.mod_manager.root.clone() else { theme::empty_message(ui, tr!("Choose a game install to see its mods")); return; }; @@ -36,7 +36,7 @@ pub fn draw(ui: &mut egui::Ui, state: &mut AppState) { if gta6 { super::mods_gta6::draw(ui, state); // The loose-mods part reads a `mods` folder, which a GTA VI install without one lacks. - if state.mod_manager.mods.is_empty() { + if state.bg.mod_manager.mods.is_empty() { return; } } @@ -59,7 +59,7 @@ pub fn draw(ui: &mut egui::Ui, state: &mut AppState) { ) .on_hover_text(path); }); - let manager = &state.mod_manager; + let manager = &state.bg.mod_manager; let in_order: Vec<&InstalledMod> = (manager.mods.iter()) .filter(|m| m.place == ModPlace::Overlay) .collect(); @@ -271,7 +271,7 @@ fn list(ui: &mut egui::Ui, lines: &[String]) { } fn draw_question(ctx: &egui::Context, state: &mut AppState) { - let Some(pending) = state.mod_manager.pending_move.clone() else { + let Some(pending) = state.bg.mod_manager.pending_move.clone() else { return; }; let (title, words) = if pending.enable { diff --git a/src/ui/panels/overlay_copy.rs b/src/ui/panels/overlay_copy.rs index 57e17a72f..bb6c0fbe5 100644 --- a/src/ui/panels/overlay_copy.rs +++ b/src/ui/panels/overlay_copy.rs @@ -11,7 +11,7 @@ use crate::ui::theme; const SHOWN: usize = 8; pub fn draw(ctx: &egui::Context, state: &mut AppState) { - let Some(offer) = state.overlay_copy.offer.clone() else { + let Some(offer) = state.bg.overlay_copy.offer.clone() else { return; }; let mut answer: Option = None; @@ -180,7 +180,7 @@ mod tests { #[test] fn a_refresh_that_discards_lists_each_change_before_it_asks() { let mut state = AppState::default(); - state.overlay_copy.offer = Some(refresh_offer(RefreshPlan { + state.bg.overlay_copy.offer = Some(refresh_offer(RefreshPlan { yours: vec![ Discard::new("data/handling.meta", Change::Edited), Discard::new("data/mine.txt", Change::Added), diff --git a/src/ui/panels/preview_settings.rs b/src/ui/panels/preview_settings.rs index 10acab6ee..c752a304d 100644 --- a/src/ui/panels/preview_settings.rs +++ b/src/ui/panels/preview_settings.rs @@ -122,13 +122,13 @@ fn draw_clip_fields(ui: &mut egui::Ui, state: &mut AppState) { other: before, }; state.record(selection.document, "Edit clip fields", change); - state.anim.invalidate(); + state.animation.session.invalidate(); } } fn draw_edit_section(ui: &mut egui::Ui, state: &mut AppState) { section_header(ui, "EDITS"); - let count = state.anim_edits.len(); + let count = state.animation.edits.len(); if count == 0 { ui.label( egui::RichText::new( @@ -141,7 +141,7 @@ fn draw_edit_section(ui: &mut egui::Ui, state: &mut AppState) { return; } - let bones = state.anim_edits.edited_bones(); + let bones = state.animation.edits.edited_bones(); ui.label( egui::RichText::new(format!( "{count} edited value{} across {} bone{}", @@ -153,7 +153,7 @@ fn draw_edit_section(ui: &mut egui::Ui, state: &mut AppState) { .color(theme::ACCENT_TEXT), ); - if let Some(skeleton) = state.anim.skeleton() { + if let Some(skeleton) = state.animation.session.skeleton() { let names: Vec = bones .iter() .take(10) @@ -178,10 +178,10 @@ fn draw_edit_section(ui: &mut egui::Ui, state: &mut AppState) { .on_hover_text("Revert to the source clip. Undoable.") .clicked() { - let before = state.anim_edits.clone(); - state.anim_edits.clear(); + let before = state.animation.edits.clone(); + state.animation.edits.clear(); state.push_anim_edit("discard edits", before); - state.anim.invalidate(); + state.animation.session.invalidate(); } }); } @@ -198,7 +198,7 @@ fn section_header(ui: &mut egui::Ui, text: &str) { fn draw_clip_section(ui: &mut egui::Ui, state: &mut AppState) { section_header(ui, "CLIP"); - match state.anim.binding.as_ref() { + match state.animation.session.binding.as_ref() { Some(binding) => { ui.label(egui::RichText::new(&binding.clip_name).monospace()); ui.label( @@ -288,7 +288,7 @@ fn draw_skeleton_section(ui: &mut egui::Ui, state: &mut AppState) { // Choosing from the list is a decision, including choosing none, so // the automatic resolver stops overriding it. state.preview_scene.pin_skeleton(chosen); - state.anim.invalidate(); + state.animation.session.invalidate(); } if state.preview_scene.skeleton_pinned { @@ -307,7 +307,7 @@ fn draw_skeleton_section(ui: &mut egui::Ui, state: &mut AppState) { .clicked() { state.preview_scene.unpin_skeleton(); - state.anim.invalidate(); + state.animation.session.invalidate(); } }); } else if let Some(suggestion) = suggest(state, &candidates) { @@ -338,7 +338,7 @@ fn draw_skeleton_section(ui: &mut egui::Ui, state: &mut AppState) { .changed() { state.preview_scene.allow_mismatched_skeleton = allow; - state.anim.invalidate(); + state.animation.session.invalidate(); } let mut model = state.preview_scene.draw_skeleton_model; @@ -382,7 +382,7 @@ fn suggest( fn draw_binding_report(ui: &mut egui::Ui, state: &mut AppState) { section_header(ui, "BINDING"); - let Some(binding) = state.anim.binding.as_ref() else { + let Some(binding) = state.animation.session.binding.as_ref() else { ui.label( egui::RichText::new("Nothing bound yet.") .small() @@ -475,7 +475,7 @@ fn draw_binding_report(ui: &mut egui::Ui, state: &mut AppState) { ); } - let errors = state.anim.last_errors(); + let errors = state.animation.session.last_errors(); if !errors.is_empty() { egui::CollapsingHeader::new(format!("{} decode problems", errors.len())) .id_salt("anim_decode_errors") @@ -520,7 +520,7 @@ fn draw_mesh_section(ui: &mut egui::Ui, state: &mut AppState) { } if let Some(source) = remove { state.preview_scene.remove_mesh(source); - state.anim.invalidate(); + state.animation.session.invalidate(); } let candidates: Vec = state @@ -544,7 +544,7 @@ fn draw_mesh_section(ui: &mut egui::Ui, state: &mut AppState) { }); if let Some(source) = to_add { state.preview_scene.add_mesh(source); - state.anim.invalidate(); + state.animation.session.invalidate(); } } @@ -581,7 +581,7 @@ fn draw_display_section(ui: &mut egui::Ui, state: &mut AppState) { ) .changed() { - state.anim.invalidate(); + state.animation.session.invalidate(); } } diff --git a/src/ui/panels/save_destination.rs b/src/ui/panels/save_destination.rs index a5f8a362c..e2179fa85 100644 --- a/src/ui/panels/save_destination.rs +++ b/src/ui/panels/save_destination.rs @@ -8,7 +8,7 @@ use crate::state::save_destination::SaveDestination; use crate::state::{AppState, EditMode}; pub fn draw(ctx: &egui::Context, state: &mut AppState) { - let Some(choice) = state.save_destination.clone() else { + let Some(choice) = state.prompts.save_destination.clone() else { return; }; let kind = state.document(choice.doc_id).map(|d| d.kind()); diff --git a/src/ui/panels/search.rs b/src/ui/panels/search.rs index 50b1d0fd5..182b9172e 100644 --- a/src/ui/panels/search.rs +++ b/src/ui/panels/search.rs @@ -10,7 +10,7 @@ use crate::ui::theme; pub(crate) const RESULTS: DocumentId = DocumentId(0); pub fn draw(ui: &mut egui::Ui, state: &mut AppState) { - if state.search.is_running() { + if state.find.session.is_running() { ui.ctx() .request_repaint_after(std::time::Duration::from_millis(100)); } @@ -41,9 +41,9 @@ fn draw_query(ui: &mut egui::Ui, state: &mut AppState, install: std::path::PathB let mut submit = false; ui.horizontal(|ui| { let resp = ui.add( - egui::TextEdit::singleline(&mut state.search_query.pattern) + egui::TextEdit::singleline(&mut state.find.query.pattern) .desired_width(280.0) - .hint_text(match state.search_query.mode { + .hint_text(match state.find.query.mode { SearchMode::Hex => "52 50 46 37", _ => "WEAPON_RAILGUN", }), @@ -51,14 +51,14 @@ fn draw_query(ui: &mut egui::Ui, state: &mut AppState, install: std::path::PathB submit |= resp.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)); for mode in SearchMode::ALL { - let selected = state.search_query.mode == mode; + let selected = state.find.query.mode == mode; if ui.selectable_label(selected, mode.label()).clicked() { - state.search_query.mode = mode; + state.find.query.mode = mode; } } ui.add_enabled( - state.search_query.mode != SearchMode::Hex, - egui::Checkbox::new(&mut state.search_query.case_sensitive, "Aa"), + state.find.query.mode != SearchMode::Hex, + egui::Checkbox::new(&mut state.find.query.case_sensitive, "Aa"), ) .on_hover_text(tr!("Case sensitive. Hex is always exact.")); }); @@ -66,7 +66,7 @@ fn draw_query(ui: &mut egui::Ui, state: &mut AppState, install: std::path::PathB ui.horizontal(|ui| { ui.label(tr!("Only")); ui.add( - egui::TextEdit::singleline(&mut state.search_query.extensions) + egui::TextEdit::singleline(&mut state.find.query.extensions) .desired_width(120.0) .hint_text("meta,ytd"), ) @@ -76,7 +76,7 @@ fn draw_query(ui: &mut egui::Ui, state: &mut AppState, install: std::path::PathB )); ui.label(tr!("under")); ui.add( - egui::TextEdit::singleline(&mut state.search_query.under) + egui::TextEdit::singleline(&mut state.find.query.under) .desired_width(200.0) .hint_text(tr!("whole install")), ) @@ -85,16 +85,16 @@ fn draw_query(ui: &mut egui::Ui, state: &mut AppState, install: std::path::PathB )); ui.separator(); - if state.search.is_running() { + if state.find.session.is_running() { if ui.button(tr!("Stop")).clicked() { state.cancel_job(crate::state::jobs::JobKind::Search); } } else if ui.button(tr!("Search")).clicked() { submit = true; } - if !state.search.hits.is_empty() { + if !state.find.session.hits.is_empty() { if ui.button(tr!("Copy results")).clicked() { - ui.ctx().copy_text(state.search.export()); + ui.ctx().copy_text(state.find.session.export()); } if ui.button(tr!("Export…")).clicked() { export_to_file(state); @@ -102,32 +102,32 @@ fn draw_query(ui: &mut egui::Ui, state: &mut AppState, install: std::path::PathB } }); - if submit && !state.search.is_running() { + if submit && !state.find.session.is_running() { let request = SearchRequest { - pattern: state.search_query.pattern.clone(), - mode: state.search_query.mode, - case_sensitive: state.search_query.case_sensitive, - extensions: split_extensions(&state.search_query.extensions), - under: state.search_query.under.clone(), + pattern: state.find.query.pattern.clone(), + mode: state.find.query.mode, + case_sensitive: state.find.query.case_sensitive, + extensions: split_extensions(&state.find.query.extensions), + under: state.find.query.under.clone(), max_hits: 0, }; let provider = state.keys.provider(); - state.search.start(request, install, provider); + state.find.session.start(request, install, provider); } } fn draw_status(ui: &mut egui::Ui, state: &AppState) { - if let Some(error) = &state.search.error { + if let Some(error) = &state.find.session.error { ui.colored_label(theme::ERROR, error); return; } - let progress = &state.search.progress; + let progress = &state.find.session.progress; let line = format!( "{} match(es) · {} file(s) read of {} seen · {}", progress.hits, progress.files_read, progress.files_seen, - if state.search.is_running() { + if state.find.session.is_running() { "searching…" } else if progress.stopped { "stopped" @@ -138,7 +138,7 @@ fn draw_status(ui: &mut egui::Ui, state: &AppState) { } ); ui.colored_label(theme::TEXT_SECONDARY, egui::RichText::new(line).small()); - if state.search.truncated() { + if state.find.session.truncated() { ui.colored_label( theme::WARNING, egui::RichText::new(tr!( @@ -150,12 +150,12 @@ fn draw_status(ui: &mut egui::Ui, state: &AppState) { } fn draw_results(ui: &mut egui::Ui, state: &mut AppState) { - if state.search.hits.is_empty() { + if state.find.session.hits.is_empty() { ui.add_space(theme::SPACING_RELAXED); ui.vertical_centered(|ui| { ui.colored_label( theme::TEXT_DIM, - if state.search.is_running() { + if state.find.session.is_running() { tr!("No matches yet.") } else { tr!("No results.") @@ -166,7 +166,7 @@ fn draw_results(ui: &mut egui::Ui, state: &mut AppState) { } let row_height = ui.text_style_height(&egui::TextStyle::Body) + 6.0; - let count = state.search.hits.len(); + let count = state.find.session.hits.len(); let mut asked: Option = None; // ⚠ The selected hit's lines below keep their room whether or not one is // selected: the list fills the height it is given, and a layout that @@ -178,7 +178,7 @@ fn draw_results(ui: &mut egui::Ui, state: &mut AppState) { .max_height((ui.available_height() - foot).max(row_height)) .show_rows(ui, row_height, count, |ui, range| { for i in range { - let hit = &state.search.hits[i]; + let hit = &state.find.session.hits[i]; let label = format!( "{} ({} hit{})", hit.path, @@ -187,7 +187,7 @@ fn draw_results(ui: &mut egui::Ui, state: &mut AppState) { ); let text = egui::RichText::new(label).monospace(); let container = hit.container.clone(); - let resp = result_row(ui, &mut state.search.selection, i, count, text); + let resp = result_row(ui, &mut state.find.session.selection, i, count, text); hits_menu(&resp, state, Hits::Search, i, &mut asked); if resp.on_hover_text(container).double_clicked() { asked = open_hit(state, Hits::Search, i); @@ -199,11 +199,12 @@ fn draw_results(ui: &mut egui::Ui, state: &mut AppState) { } let Some(hit) = state - .search + .find + .session .selection .selected(RESULTS) .and_then(crate::state::SelectionKey::row) - .and_then(|i| state.search.hits.get(i as usize)) + .and_then(|i| state.find.session.hits.get(i as usize)) else { return; }; @@ -266,8 +267,8 @@ pub(crate) fn hits_menu( ) { resp.context_menu(|ui| { let selection = match list { - Hits::Search => &state.search.selection, - Hits::Inside(_) => &state.deep_find.selection, + Hits::Search => &state.find.session.selection, + Hits::Inside(_) => &state.find.deep.selection, }; let picked = selection.selected_ids(RESULTS); let mut rows = vec![row]; @@ -294,7 +295,7 @@ pub(crate) fn hits_menu( /// The tree on screen with nothing filtered out of it, so a revealed row is drawn. pub(crate) fn show_tree(state: &mut AppState) { super::hierarchy::ui_state(state).filter.clear(); - state.deep_find.clear(); + state.find.deep.clear(); let ws = state.active_workspace; state .workspace_docks diff --git a/src/ui/panels/settings/editing.rs b/src/ui/panels/settings/editing.rs index 00f3f1faf..f373f52ed 100644 --- a/src/ui/panels/settings/editing.rs +++ b/src/ui/panels/settings/editing.rs @@ -33,7 +33,7 @@ fn draw_edit_mode_section(ui: &mut egui::Ui, state: &mut AppState) { state.set_edit_mode(mode); } - if state.retail_edit_session_allow { + if state.prompts.retail_edit_session_allow { ui.add_space(theme::SPACING_TIGHT); if ui .button(tr!("Revoke this session's base-game permission")) @@ -43,7 +43,7 @@ fn draw_edit_mode_section(ui: &mut egui::Ui, state: &mut AppState) { )) .clicked() { - state.retail_edit_session_allow = false; + state.prompts.retail_edit_session_allow = false; state.show_toast(tr!("Base-game writes will be confirmed again")); } } diff --git a/src/ui/panels/settings/materials.rs b/src/ui/panels/settings/materials.rs index 9faba14dd..e358ad0fd 100644 --- a/src/ui/panels/settings/materials.rs +++ b/src/ui/panels/settings/materials.rs @@ -95,7 +95,7 @@ fn draw_texture_paths_section(ui: &mut egui::Ui, state: &mut AppState) { if swap.is_some() || remove.is_some() { // ⚠ A changed order can change which dictionary answers, and the // refusal to retry is remembered per document. - state.attempted_texture_search_paths.clear(); + state.textures.attempted_search_paths.clear(); } } @@ -114,7 +114,7 @@ fn draw_shader_definitions_section(ui: &mut egui::Ui, state: &AppState) { ); ui.add_space(theme::SPACING_TIGHT); - let (colour, text) = match &state.shader_defs.status { + let (colour, text) = match &state.install.shader_defs.status { ShaderDefsStatus::Absent => ( theme::WARNING, tr!("None loaded; material parameters show as hashes").to_string(), @@ -141,7 +141,7 @@ fn draw_shader_definitions_section(ui: &mut egui::Ui, state: &AppState) { ), }; ui.colored_label(colour, text); - if let Some(message) = state.shader_defs.status.failure_message() { + if let Some(message) = state.install.shader_defs.status.failure_message() { ui.add_space(theme::SPACING_HAIR); ui.colored_label(theme::ERROR, tr!("Error: {message}", message = message)); } @@ -161,9 +161,9 @@ pub(super) fn draw_materials_page(ui: &mut egui::Ui, state: &mut AppState) { ); ui.add_space(theme::SPACING_TIGHT); - let palette = state.materials_palette.palette(); + let palette = state.install.materials_palette.palette(); let entry_count = palette.len(); - let (badge_color, badge_text) = match &state.materials_palette.status { + let (badge_color, badge_text) = match &state.install.materials_palette.status { MaterialPaletteStatus::NotLoaded => ( theme::WARNING, tr!("Source: not loaded — no install read yet").to_string(), @@ -191,7 +191,7 @@ pub(super) fn draw_materials_page(ui: &mut egui::Ui, state: &mut AppState) { }; ui.colored_label(badge_color, badge_text); - if let Some(message) = state.materials_palette.status.failure_message() { + if let Some(message) = state.install.materials_palette.status.failure_message() { ui.add_space(theme::SPACING_HAIR); ui.colored_label(theme::ERROR, tr!("Error: {message}", message = message)); } @@ -201,7 +201,7 @@ pub(super) fn draw_materials_page(ui: &mut egui::Ui, state: &mut AppState) { let reload_button = egui::Button::new(tr!("Reload from GTA install")); let response = ui .add_enabled( - can_reload && !state.materials_palette.is_loading(), + can_reload && !state.install.materials_palette.is_loading(), reload_button, ) .on_hover_text(tr!( diff --git a/src/ui/panels/settings/overlay.rs b/src/ui/panels/settings/overlay.rs index cb9b830e2..4cc696aca 100644 --- a/src/ui/panels/settings/overlay.rs +++ b/src/ui/panels/settings/overlay.rs @@ -46,7 +46,7 @@ pub fn draw_overlay_section(ui: &mut egui::Ui, state: &mut AppState) { /// The overlay copies the game was updated past, each with the refresh that replaces it. fn draw_outgrown(ui: &mut egui::Ui, state: &mut AppState) { - if state.overlay_copy.stale.is_empty() { + if state.bg.overlay_copy.stale.is_empty() { return; } ui.add_space(theme::SPACING_DEFAULT); @@ -54,9 +54,9 @@ fn draw_outgrown(ui: &mut egui::Ui, state: &mut AppState) { theme::WARNING, tr!("The game was updated since these copies were made, so they hide what the update changed:"), ); - let idle = state.prefs.edit_mode.permits_overlay() && state.overlay_copy.running().is_none(); + let idle = state.prefs.edit_mode.permits_overlay() && state.bg.overlay_copy.running().is_none(); let mut asked = None; - for stale in &state.overlay_copy.stale { + for stale in &state.bg.overlay_copy.stale { ui.horizontal(|ui| { ui.label(egui::RichText::new(state.overlay_name(&stale.copy)).monospace()); let refresh = ui diff --git a/src/ui/panels/statistics.rs b/src/ui/panels/statistics.rs index 7d500b3c1..2959dd1ae 100644 --- a/src/ui/panels/statistics.rs +++ b/src/ui/panels/statistics.rs @@ -64,7 +64,7 @@ fn walked_lately(ctx: &egui::Context, state: &AppState) -> Walked { } fn readings_of(state: &AppState, ctx: &egui::Context, walked: Walked) -> Readings { - let previews = state.texture_cache.texture_ids(); + let previews = state.textures.cache.texture_ids(); let egui_texture_bytes = ctx .tex_manager() .read() @@ -73,14 +73,14 @@ fn readings_of(state: &AppState, ctx: &egui::Context, walked: Walked) -> Reading .map(|(_, meta)| meta.bytes_used()) .sum(); Readings { - fps: state.frame_stats.fps(), - frame_ms: state.frame_stats.frame_ms(), - phase_ms: state.frame_stats.phase_ms(), - cache_bytes: state.texture_cache.bytes(), - cache_budget: state.texture_cache.budget(), - gpu: state.gpu_usage, + fps: state.perf.frame_stats.fps(), + frame_ms: state.perf.frame_stats.frame_ms(), + phase_ms: state.perf.frame_stats.phase_ms(), + cache_bytes: state.textures.cache.bytes(), + cache_budget: state.textures.cache.budget(), + gpu: state.perf.gpu_usage, gpu_budget: state.prefs.gpu_texture_budget(), - gpu_stages: state.gpu_stages.clone(), + gpu_stages: state.perf.gpu_stages.clone(), egui_texture_bytes, cpu: walked.cpu, documents: walked.documents, diff --git a/src/ui/panels/status_bar.rs b/src/ui/panels/status_bar.rs index c9a753094..51414c7c6 100644 --- a/src/ui/panels/status_bar.rs +++ b/src/ui/panels/status_bar.rs @@ -112,7 +112,7 @@ fn draw_installs_found(ui: &mut egui::Ui, state: &mut AppState) { if !found_any { ui.label(egui::RichText::new(tr!("No install found")).color(theme::TEXT_SECONDARY)); } - if state.discovery.is_running() { + if state.bg.discovery.is_running() { ui.horizontal(|ui| { ui.spinner(); ui.label( @@ -309,7 +309,7 @@ fn nothing_open_hint(state: &AppState) -> String { } fn draw_texture_resolution(ui: &mut egui::Ui, state: &AppState) { - let report = &state.texture_report; + let report = &state.textures.report; if report.is_empty() || report.document != state.active_document { return; } @@ -427,7 +427,7 @@ fn draw_right(ui: &mut egui::Ui, state: &mut AppState) { ui.label( egui::RichText::new(tr!( "Error: {error_dialog_title}", - error_dialog_title = state.error_dialog_title + error_dialog_title = state.error_dialog.title )) .small() .color(theme::ERROR), @@ -656,10 +656,10 @@ mod tests { let mut state = AppState::default(); state.documents.clear(); state.active_document = None; - state.frame_stats.tick(); + state.perf.frame_stats.tick(); std::thread::sleep(std::time::Duration::from_millis(2)); - state.frame_stats.tick(); - assert!(state.frame_stats.fps() > 0.0, "no frame was timed"); + state.perf.frame_stats.tick(); + assert!(state.perf.frame_stats.fps() > 0.0, "no frame was timed"); let ctx = egui::Context::default(); ctx.enable_accesskit(); let output = ctx.run_ui(egui::RawInput::default(), |ui| draw(ui, &mut state)); @@ -719,7 +719,8 @@ mod tests { click(&ctx, &mut state, Game::GtaVLegacy.label()); click(&ctx, &mut state, Game::GtaVEnhanced.label()); let pending = state - .pending_close + .prompts + .close .clone() .expect("the switch did not go through the close request"); assert_eq!(state.unsaved_documents(&pending.documents), [file]); diff --git a/src/ui/panels/texture_preview/mod.rs b/src/ui/panels/texture_preview/mod.rs index f50b14619..3b6b702e6 100644 --- a/src/ui/panels/texture_preview/mod.rs +++ b/src/ui/panels/texture_preview/mod.rs @@ -238,14 +238,14 @@ pub fn draw(ui: &mut egui::Ui, state: &mut AppState) { .min(levels - 1); let cached = if mip == 0 { - state.texture_cache.get_or_decode( + state.textures.cache.get_or_decode( ui.ctx(), (doc_id, shown_name.clone(), channel_view), &texture, ) } else { // Cached under the texture's name and the level, so forgetting the document forgets it too. - state.texture_cache.get_or_insert_image( + state.textures.cache.get_or_insert_image( ui.ctx(), (doc_id, format!("{shown_name}@mip{mip}"), channel_view), egui::TextureOptions::LINEAR, @@ -396,13 +396,13 @@ fn draw_document_image( .unwrap_or(ChannelView::Rgba); // The picture is built only on a miss: a height map is never edited in place. let key = (doc_id, label.to_string(), channel_view); - let cached = match state.texture_cache.get(&key).cloned() { + let cached = match state.textures.cache.get(&key).cloned() { Some(cached) => Some(cached), None => { let made = state .document(doc_id) .and_then(|d| textures::document_image(&d.payload)); - state.texture_cache.get_or_insert_image( + state.textures.cache.get_or_insert_image( ui.ctx(), key, egui::TextureOptions::NEAREST, diff --git a/src/ui/panels/timeline_ycd.rs b/src/ui/panels/timeline_ycd.rs index 5dd98bf78..b43c4c372 100644 --- a/src/ui/panels/timeline_ycd.rs +++ b/src/ui/panels/timeline_ycd.rs @@ -39,7 +39,7 @@ pub fn draw(ui: &mut egui::Ui, state: &mut crate::state::AppState) { } let source = { - let Some(binding) = state.anim.binding.as_ref() else { + let Some(binding) = state.animation.session.binding.as_ref() else { let message = match state.preview_scene.clip { None => format!( "Select a clip in {} to play it", @@ -92,14 +92,14 @@ pub fn draw(ui: &mut egui::Ui, state: &mut crate::state::AppState) { if let Some(selection) = clip_subject { tl.0.ensure_subject(selection); } - let mut transport = state.anim_transport; + let mut transport = state.animation.transport; let output = timeline::draw(ui, &source, &mut transport, &mut tl.0); state.panels.put(tl); - state.anim_transport = transport; + state.animation.transport = transport; if let Some(time) = output.seek_to { - state.anim_transport.time = state.anim_transport.range.clamp(time); - state.anim_transport.seek_pending = None; + state.animation.transport.time = state.animation.transport.range.clamp(time); + state.animation.transport.seek_pending = None; } draw_key_controls(ui, state, &source); @@ -111,10 +111,10 @@ fn insert_key( track: or_anim::EditTrack, time: f32, ) -> bool { - let Some(frame) = state.anim.frame_at(time) else { + let Some(frame) = state.animation.session.frame_at(time) else { return false; }; - let Some(local) = state.anim.pose.local(bone).copied() else { + let Some(local) = state.animation.session.pose.local(bone).copied() else { return false; }; let value = match track { @@ -123,7 +123,8 @@ fn insert_key( or_anim::EditTrack::Rotation => or_anim::EditValue::Rotation(local.rotation), }; state - .anim_edits + .animation + .edits .set(or_anim::EditKey { bone, track, frame }, value) } @@ -132,8 +133,8 @@ fn draw_key_controls( state: &mut crate::state::AppState, source: &YcdTimelineSource, ) { - let time = state.anim_transport.time; - let Some(frame) = state.anim.frame_at(time) else { + let time = state.animation.transport.time; + let Some(frame) = state.animation.session.frame_at(time) else { return; }; let selected: Vec<(u16, or_anim::EditTrack)> = state @@ -162,14 +163,14 @@ fn draw_key_controls( ) .clicked() { - let before = state.anim_edits.clone(); + let before = state.animation.edits.clone(); let mut applied = false; for (bone, track) in &selected { applied |= insert_key(state, *bone, *track, time); } if applied { state.push_anim_edit("insert key", before); - state.anim.invalidate(); + state.animation.session.invalidate(); } } if ui @@ -177,10 +178,10 @@ fn draw_key_controls( .on_hover_text("Remove the key at the playhead on the selected rows") .clicked() { - let before = state.anim_edits.clone(); + let before = state.animation.edits.clone(); let mut applied = false; for (bone, track) in &selected { - applied |= state.anim_edits.remove(&or_anim::EditKey { + applied |= state.animation.edits.remove(&or_anim::EditKey { bone: *bone, track: *track, frame, @@ -188,7 +189,7 @@ fn draw_key_controls( } if applied { state.push_anim_edit("clear key", before); - state.anim.invalidate(); + state.animation.session.invalidate(); } } }); diff --git a/src/ui/panels/viewport/mod.rs b/src/ui/panels/viewport/mod.rs index 5263c1303..2ecda7278 100644 --- a/src/ui/panels/viewport/mod.rs +++ b/src/ui/panels/viewport/mod.rs @@ -56,8 +56,8 @@ pub fn draw(ui: &mut egui::Ui, state: &mut AppState, bridge: Option<&mut RenderB bridge.refresh_meshes(state); bridge.refresh_game_scene(state); bridge.refresh_skinning(state); - if state.texture_report.epoch != bridge.texture_report().epoch { - state.texture_report = bridge.texture_report().clone(); + if state.textures.report.epoch != bridge.texture_report().epoch { + state.textures.report = bridge.texture_report().clone(); } // The project's copy, then the archive sibling — a dictionary // travelling with the file — and a configured path last. diff --git a/src/ui/panels/viewport/texture_badge.rs b/src/ui/panels/viewport/texture_badge.rs index 573ab3198..a55f57ad1 100644 --- a/src/ui/panels/viewport/texture_badge.rs +++ b/src/ui/panels/viewport/texture_badge.rs @@ -44,7 +44,7 @@ pub(super) fn draw_texture_badge( rect: egui::Rect, state: &AppState, ) -> Option { - let report = &state.texture_report; + let report = &state.textures.report; if report.is_empty() || report.document != state.active_document { return None; } diff --git a/src/ui/panels/wardrobe/garment.rs b/src/ui/panels/wardrobe/garment.rs index d35575b70..60757c0cd 100644 --- a/src/ui/panels/wardrobe/garment.rs +++ b/src/ui/panels/wardrobe/garment.rs @@ -78,7 +78,7 @@ pub fn draw(ui: &mut egui::Ui, state: &mut AppState) { let linked = state.wardrobe_is_linked(); let picked = state.picked_garments(); // F2 or a toast asked for a name; it is answered by the panel that has the field: the garment's, or the pack's while none is selected. - shown.focus_name |= std::mem::take(&mut state.workbench.wardrobe.rename_asked); + shown.focus_name |= state.workbench.wardrobe_mut().take_rename_request(); if shown.versions_open { state.load_versions(); } @@ -170,14 +170,13 @@ pub fn draw(ui: &mut egui::Ui, state: &mut AppState) { commands::run_action(state, ui.ctx(), action); } if let Some((medium, low, replace)) = asked.mesh.set { - let desk = &mut state.workbench.wardrobe.mesh; - (desk.medium, desk.low, desk.replace) = (medium, low, replace); + state + .workbench + .wardrobe_mut() + .set_mesh_levels(medium, low, replace); } - if let (Some(shown), Some(before)) = ( - asked.mesh.show_before, - state.workbench.wardrobe.mesh.before.as_mut(), - ) { - before.shown = shown; + if let Some(shown) = asked.mesh.show_before { + state.workbench.wardrobe_mut().set_mesh_show_before(shown); } if let Some((id, ask)) = asked.texture { match ask { @@ -302,7 +301,7 @@ fn garment( asked.run.push(action); } } - super::watched::draw(ui, state, g, &mut asked.watched); + super::watched::draw(ui, state.workbench.wardrobe(), g, &mut asked.watched); for i in 0..g.variations.len() { textures::row(ui, shown, g, i, asked); } diff --git a/src/ui/panels/wardrobe/header.rs b/src/ui/panels/wardrobe/header.rs index ca860ca84..ca638e962 100644 --- a/src/ui/panels/wardrobe/header.rs +++ b/src/ui/panels/wardrobe/header.rs @@ -8,14 +8,16 @@ use egui_phosphor::regular as icon; use or_wardrobe::Ped; use super::{action_button, WardrobeUi}; +use crate::state::workbench::WardrobeWork; use crate::state::AppState; use crate::ui::commands::{self, Action}; use crate::ui::theme; /// What a clothing content is called on screen: its pack, which is the name people gave it, and not the id the project file keeps. pub(crate) fn pack_name(state: &AppState, module: &str) -> String { - (state.workbench.packs().iter()) - .find(|p| p.module == module) + state + .workbench + .pack(module) .and_then(|p| p.read.as_ref().ok()) .map_or_else(|| module.to_string(), |read| read.wardrobe.pack.clone()) } @@ -154,7 +156,7 @@ fn pack_chooser(ui: &mut egui::Ui, state: &mut AppState, module: &str) { .clothing_modules() .iter() .map(|m| { - let name = match (state.workbench.packs().iter()).find(|p| p.module == m.id) { + let name = match state.workbench.pack(&m.id) { None => tr!("Reading…").to_string(), Some(pack) if pack.read.is_err() => tr!("Could not be read").to_string(), Some(_) => pack_name(state, &m.id), @@ -181,26 +183,25 @@ fn pack_chooser(ui: &mut egui::Ui, state: &mut AppState, module: &str) { egui::WidgetInfo::labeled(egui::WidgetType::ComboBox, true, tr!("Clothing pack shown")) }); if chosen != module { - state.workbench.wardrobe.module = Some(chosen); - state.workbench.wardrobe.selected = None; + state.workbench.wardrobe_mut().select_module(chosen); } } /// The words of an edit that runs and the button that stops it, above the build; nothing is drawn while no edit runs. -pub(super) fn progress(ui: &mut egui::Ui, state: &mut AppState) { - let Some(what) = state.workbench.wardrobe.progress_words() else { +pub(super) fn progress(ui: &mut egui::Ui, wardrobe: &WardrobeWork) { + let Some(what) = wardrobe.progress_words() else { return; }; ui.horizontal(|ui| { ui.spinner(); ui.add(egui::Label::new(egui::RichText::new(what).color(theme::TEXT_SECONDARY)).truncate()); - if state.workbench.wardrobe.stoppable() + if wardrobe.stoppable() && ui .small_button(tr!("Stop")) .on_hover_text(tr!("Stop: nothing is changed and the pack stays as it was")) .clicked() { - state.workbench.wardrobe.stop(); + wardrobe.stop(); } }); } @@ -284,7 +285,7 @@ fn fix_menu(ui: &mut egui::Ui, state: &mut AppState) { Err(_) => {} } if action == Action::FixAllSafe { - levels_checkbox(ui, state); + levels_checkbox(ui, state.workbench.wardrobe_mut()); } } } @@ -316,14 +317,14 @@ fn fix_caption(action: Action) -> &'static str { } /// Whether Fix all safe also gives the models that lack them a medium and a low level, in its one step of Undo. -fn levels_checkbox(ui: &mut egui::Ui, state: &mut AppState) { +fn levels_checkbox(ui: &mut egui::Ui, wardrobe: &mut WardrobeWork) { // Indented: it is an option of Fix all safe, which stands above it. ui.horizontal(|ui| { ui.add_space(14.0); // ⚠ A menu draws a tick box with no frame, so an unticked one reads as greyed out. super::kit::framed(ui); ui.checkbox( - &mut state.workbench.wardrobe.mesh.fix_levels, + wardrobe.fix_levels_mut(), tr!("Also add missing levels of detail"), ) .on_hover_text( @@ -334,11 +335,11 @@ fn levels_checkbox(ui: &mut egui::Ui, state: &mut AppState) { /// The button that takes the last change back: an icon of one width, named for the change it would take back and saying what it would take back. fn undo_button(ui: &mut egui::Ui, state: &mut AppState) { - let name = state.workbench.wardrobe.undo_words(); + let name = state.workbench.wardrobe().undo_words(); let Some(mut command) = commands::of(state, Action::UndoClothes) else { return; }; - if let Some(label) = state.workbench.wardrobe.undo_label() { + if let Some(label) = state.workbench.wardrobe().undo_label() { command.hover = Some(tr!("Takes back: {label}", label = label)); } let button = @@ -456,7 +457,7 @@ pub(super) fn build_chooser(ui: &mut egui::Ui, state: &mut AppState, module: &st ) }); if chosen != active { - state.workbench.selected_output = chosen; + state.workbench.select_output(chosen); } if let Some(output) = state.active_output_id() { let (words, colour) = super::strip::build_state(state, &output); diff --git a/src/ui/panels/wardrobe/keys.rs b/src/ui/panels/wardrobe/keys.rs index ea83e8e69..bd468393f 100644 --- a/src/ui/panels/wardrobe/keys.rs +++ b/src/ui/panels/wardrobe/keys.rs @@ -51,8 +51,11 @@ fn walk(state: &mut AppState, shown: &mut WardrobeUi, module: &str, down: bool, else { return; }; - let at = (state.workbench.wardrobe.selected.as_ref()) - .and_then(|(_, id)| order.iter().position(|o| o == id)); + let at = state + .workbench + .wardrobe() + .selected_garment_id() + .and_then(|id| order.iter().position(|o| o == id)); let to = match (at, down) { (None, _) => 0, (Some(at), true) => (at + 1).min(order.len() - 1), diff --git a/src/ui/panels/wardrobe/light.rs b/src/ui/panels/wardrobe/light.rs index 0c6251dae..c3b0ed54a 100644 --- a/src/ui/panels/wardrobe/light.rs +++ b/src/ui/panels/wardrobe/light.rs @@ -7,7 +7,7 @@ use egui_phosphor::regular as icon; use super::kit::{combo, framed, menu}; use crate::state::workbench::light::{Light, STRONGEST}; -use crate::state::workbench::ViewMode; +use crate::state::workbench::Dressed; use crate::state::AppState; use crate::ui::accessible_name::named; use crate::ui::theme; @@ -147,10 +147,10 @@ fn daylight( } /// The Light menu: the light the view drawn now is lit by. Shaded has the game's daylight and the plain views a studio light, and each is shown only while it lights something. -pub(super) fn light(ui: &mut egui::Ui, state: &mut AppState) { - let mut hour = state.drivers.time_of_day.hour; - let dressed = &mut state.workbench.wardrobe.dressed; - let shaded = dressed.view == ViewMode::Shaded; +/// +/// Returns `true` when the time of day `hour` was changed. +pub(super) fn light(ui: &mut egui::Ui, dressed: &mut Dressed, hour: &mut f32) -> bool { + let shaded = dressed.is_shaded(); let mut now = dressed.light; let (mut hour_moved, mut to_material) = (false, false); let opened = menu(ui, tr!("Light"), Some(icon::SUN), |ui| { @@ -159,12 +159,12 @@ pub(super) fn light(ui: &mut egui::Ui, state: &mut AppState) { match shaded { true => daylight( ui, - &mut hour, + hour, &mut dressed.shadows, &mut hour_moved, &mut to_material, ), - false => studio(ui, &mut now, &mut hour, &mut hour_moved), + false => studio(ui, &mut now, hour, &mut hour_moved), } }); crate::ui::guide_links::tip( @@ -174,11 +174,9 @@ pub(super) fn light(ui: &mut egui::Ui, state: &mut AppState) { ); dressed.light = now; if to_material { - dressed.view = ViewMode::Material; - } - if hour_moved { - state.drivers.time_of_day.set_hour(hour); + dressed.switch_to_material(); } + hour_moved } /// The garment selected and the files of its alternates, when it has any. @@ -190,16 +188,15 @@ pub(super) fn alternates_of_the_selected(state: &AppState) -> Option<(String, Ve } /// The model the garment selected is worn with, when it has alternates: its own, or one of the numbered ones. -pub(super) fn alternate_model(ui: &mut egui::Ui, state: &mut AppState) { - let Some((id, files)) = alternates_of_the_selected(state) else { - return; - }; - let dressed = &mut state.workbench.wardrobe.dressed; +pub(super) fn alternate_model( + ui: &mut egui::Ui, + dressed: &mut Dressed, + id: &str, + files: &[String], +) { // The set of alternate variations that makes this garment wear one of its alternates, and the number it says. - let driven = (dressed.driven.iter()) - .find(|d| d.target == or_wardrobe::alternate::Asset::garment(&id)) - .map(|d| (d.name.clone(), usize::from(d.alt), d.overridden)); - let chosen_by_hand = dressed.alternate.get(&id).copied(); + let driven = dressed.driven_for_garment(id); + let chosen_by_hand = dressed.chosen_alternate(id); let now = chosen_by_hand.unwrap_or(0).min(files.len()); let words = |n: usize| match n { 0 => tr!("Main model").to_string(), @@ -234,12 +231,8 @@ pub(super) fn alternate_model(ui: &mut egui::Ui, state: &mut AppState) { .on_hover_text(tr!("A set of alternate variations changes this garment's model while the garments that cause it are worn; a model chosen here is worn in place of the set's")); } if follow_the_set { - dressed.alternate.remove(&id); + dressed.clear_alternate(id); } else if chosen != shown { - match (chosen, &driven) { - // ⚠ The main model is a choice held against a set, and the plain absence of one where none drives the garment. - (0, None) => dressed.alternate.remove(&id), - (n, _) => dressed.alternate.insert(id, n), - }; + dressed.set_alternate(id.to_string(), chosen, driven.is_some()); } } diff --git a/src/ui/panels/wardrobe/list.rs b/src/ui/panels/wardrobe/list.rs index 2428996d5..2ce89b57b 100644 --- a/src/ui/panels/wardrobe/list.rs +++ b/src/ui/panels/wardrobe/list.rs @@ -186,13 +186,13 @@ pub fn draw(ui: &mut egui::Ui, state: &mut AppState) { egui::Panel::bottom(ui.id().with("wardrobe_strip")) .frame(egui::Frame::NONE.inner_margin(egui::Margin::symmetric(8, 3))) .show_inside(ui, |ui| { - header::progress(ui, state); + header::progress(ui, state.workbench.wardrobe()); if figures { strip::draw(ui, state, &module); } header::build_chooser(ui, state, &module); }); - if state.workbench.wardrobe.quick_look { + if state.workbench.wardrobe().is_quick_look_open() { egui::Panel::bottom(ui.id().with("wardrobe_quick_look")) .resizable(false) .show_inside(ui, |ui| quick::draw(ui, state, &mut shown)); @@ -208,7 +208,7 @@ fn body(ui: &mut egui::Ui, state: &mut AppState, shown: &mut WardrobeUi, module: // The garments picked and no longer listed, which are let go once the list is drawn. let mut unlisted: Option> = None; { - let Some(pack) = state.workbench.packs().iter().find(|p| p.module == module) else { + let Some(pack) = state.workbench.pack(module) else { ui.horizontal(|ui| { ui.spinner(); ui.label( @@ -228,7 +228,7 @@ fn body(ui: &mut egui::Ui, state: &mut AppState, shown: &mut WardrobeUi, module: let findings = state.workbench.findings(); refresh( shown, - state.workbench.wardrobe.generation, + state.workbench.wardrobe().generation(), module, read, findings, @@ -265,7 +265,7 @@ fn body(ui: &mut egui::Ui, state: &mut AppState, shown: &mut WardrobeUi, module: cached, picked: &picked, linked, - dressed: &state.workbench.wardrobe.dressed, + dressed: state.workbench.dressed(), filters: &filters, }; rows(ui, &frame, tiles, view, &mut asked); @@ -334,11 +334,7 @@ fn body(ui: &mut egui::Ui, state: &mut AppState, shown: &mut WardrobeUi, module: if let Some(id) = asked.open_model { state.open_garment_model(&id); } - state - .workbench - .wardrobe - .dressed - .ask_row_thumbs(asked.thumbs); + state.workbench.dressed_mut().ask_row_thumbs(asked.thumbs); } /// What the filters in force are, in words: the text typed, the ped chosen and the chip pressed; nothing while none is on. diff --git a/src/ui/panels/wardrobe/mesh.rs b/src/ui/panels/wardrobe/mesh.rs index 0d4d21200..22ba314ab 100644 --- a/src/ui/panels/wardrobe/mesh.rs +++ b/src/ui/panels/wardrobe/mesh.rs @@ -6,6 +6,7 @@ use or_wardrobe::Garment; use super::garment::command_button; +use crate::state::workbench::MeshDesk; use crate::state::AppState; use crate::ui::commands::Action; use crate::ui::theme; @@ -57,7 +58,7 @@ pub(super) fn draw(ui: &mut egui::Ui, state: &AppState, g: &Garment, asked: &mut } ui.add_space(theme::SPACING_DEFAULT); // Closed until asked for, since the doctor's buttons are for a garment a person means to change and a panel that opens on them is longer for every other; open, by its own state, while a look or a step before stands for the garment, which is what the person asked to see. - let desk = &state.workbench.wardrobe.mesh; + let desk = state.workbench.wardrobe().mesh(); let standing = desk.looked.as_ref().is_some_and(|l| l.garment == g.id) || desk .before @@ -66,7 +67,7 @@ pub(super) fn draw(ui: &mut egui::Ui, state: &AppState, g: &Garment, asked: &mut let folded = egui::CollapsingHeader::new(tr!("Mesh doctor")) .id_salt(("mesh doctor", standing)) .default_open(standing) - .show(ui, |ui| body(ui, state, g, asked)); + .show(ui, |ui| body(ui, state, desk, g, asked)); // ⚠ A fold that opens at the foot of a panel shows nothing of itself: bring it up, once, when it opens. let was = ui.id().with(tr!("mesh doctor was standing")); let before = ui.data_mut(|d| d.get_temp::(was)).unwrap_or(false); @@ -77,8 +78,7 @@ pub(super) fn draw(ui: &mut egui::Ui, state: &AppState, g: &Garment, asked: &mut } } -fn body(ui: &mut egui::Ui, state: &AppState, g: &Garment, asked: &mut Asked) { - let desk = &state.workbench.wardrobe.mesh; +fn body(ui: &mut egui::Ui, state: &AppState, desk: &MeshDesk, g: &Garment, asked: &mut Asked) { ui.horizontal_wrapped(|ui| { if command_button(ui, state, Action::CheckMesh) { asked.run.push(Action::CheckMesh); diff --git a/src/ui/panels/wardrobe/overlay.rs b/src/ui/panels/wardrobe/overlay.rs index 5f2f21c5a..056893262 100644 --- a/src/ui/panels/wardrobe/overlay.rs +++ b/src/ui/panels/wardrobe/overlay.rs @@ -4,10 +4,11 @@ //! ⚠ **Thin by design.** The skeleton, the grid, the first person view and the clip are the state's; this places the controls where the view they act on is. use egui_phosphor::regular as icon; +use or_wardrobe::Ped; use super::kit::{combo, tip}; use super::tools::{carry_out, small, Play}; -use crate::state::workbench::{NO_GAME, SPEEDS}; +use crate::state::workbench::{Dressed, NO_GAME, SPEEDS}; use crate::state::AppState; use crate::ui::accessible_name::named; use crate::ui::theme; @@ -18,17 +19,38 @@ const FIRST_PERSON: &str = tr_key!("The camera stands at the head bone with the /// The view helpers, in a row under the view: the skeleton, the grid, the view from the head and the camera placed on the ped. pub(super) fn helpers(ui: &mut egui::Ui, state: &mut AppState) { let ped = state.dressed_ped(); - let has_skeleton = state.workbench.wardrobe.dressed.skeleton(ped).is_some(); - let has_head = state.workbench.wardrobe.dressed.eyes(ped).is_some(); + let mut show_grid = state.prefs.viewport.show_grid; + let mut hour = state.drivers.time_of_day.hour; + let hour_moved = helpers_row( + ui, + ped, + state.workbench.dressed_mut(), + &mut show_grid, + &mut hour, + ); + state.prefs.viewport.show_grid = show_grid; + if hour_moved { + state.drivers.time_of_day.set_hour(hour); + } +} + +fn helpers_row( + ui: &mut egui::Ui, + ped: Ped, + dressed: &mut Dressed, + show_grid: &mut bool, + hour: &mut f32, +) -> bool { + let has_skeleton = dressed.has_skeleton(ped); + let has_head = dressed.has_head(ped); let mut frame = false; + let mut hour_moved = false; ui.horizontal(|ui| { - let dressed = &mut state.workbench.wardrobe.dressed; ui.add_enabled(has_skeleton, egui::Checkbox::new(&mut dressed.bones, tr!("Bones"))) .on_hover_text(tr!("The skeleton of the ped, posed by the clip while one plays")) .on_disabled_hover_text(tr!("The skeleton is read from the game install, which needs to be chosen in Settings")); - ui.checkbox(&mut state.prefs.viewport.show_grid, tr!("Grid")) + ui.checkbox(show_grid, tr!("Grid")) .on_hover_text(tr!("The floor grid of the 3D views")); - let dressed = &mut state.workbench.wardrobe.dressed; let response = ui .add_enabled( has_head, @@ -36,7 +58,7 @@ pub(super) fn helpers(ui: &mut egui::Ui, state: &mut AppState) { ) .on_disabled_hover_text(tr!("The head is placed from the ped's skeleton, which is read from the game install, which needs to be chosen in Settings")); tip(response, crate::i18n::tr(FIRST_PERSON)); - super::light::light(ui, state); + hour_moved = super::light::light(ui, dressed, hour); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { let button = ui.button(tr!("{icon} Frame", icon = icon::CROSSHAIR)); frame = named(button, tr!("Frame the ped")) @@ -45,8 +67,9 @@ pub(super) fn helpers(ui: &mut egui::Ui, state: &mut AppState) { }); }); if frame { - state.workbench.wardrobe.dressed.frame_again(); + dressed.frame_again(); } + hour_moved } /// A box over the view at `rect`, which its content sits in: at the top edge, or at the bottom edge where it is as tall as it was in the last frame. @@ -90,8 +113,8 @@ fn over( } /// The note of the view from the head: that it is on, how to look round and how to leave. -pub(super) fn first_person(ui: &mut egui::Ui, rect: egui::Rect, state: &mut AppState) { - if !state.workbench.wardrobe.dressed.first_person { +pub(super) fn first_person(ui: &mut egui::Ui, rect: egui::Rect, dressed: &mut Dressed) { + if !dressed.is_first_person() { return; } let leave = over(ui, rect, false, |ui| { @@ -104,7 +127,7 @@ pub(super) fn first_person(ui: &mut egui::Ui, rect: egui::Rect, state: &mut AppS .inner }); if leave { - state.workbench.wardrobe.dressed.first_person = false; + dressed.leave_first_person(); } } @@ -133,35 +156,33 @@ pub(super) fn no_game(ui: &mut egui::Ui, rect: egui::Rect, state: &mut AppState) } /// Escape leaves the view from the head while the pointer or the keyboard is on the view; true when it did. -pub(super) fn escape_leaves(ui: &egui::Ui, view: &egui::Response, state: &mut AppState) -> bool { - let dressed = &mut state.workbench.wardrobe.dressed; +pub(super) fn escape_leaves( + ui: &egui::Ui, + view: &egui::Response, + dressed: &mut Dressed, + asking: bool, +) -> bool { let here = view.hovered() || view.has_focus(); // ⚠ Not while a window or a menu is open: Escape closes that first. - let covered = state.workbench.asking.is_some() || egui::Popup::is_any_open(ui.ctx()); - if !dressed.first_person || !here || covered { + let covered = asking || egui::Popup::is_any_open(ui.ctx()); + if !dressed.is_first_person() || !here || covered { return false; } let pressed = ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Escape)); if pressed { - dressed.first_person = false; + dressed.leave_first_person(); } pressed } /// What the view draws, in its bottom left corner. -pub(super) fn bottom(ui: &mut egui::Ui, rect: egui::Rect, state: &mut AppState) { - let drawn = state - .workbench - .wardrobe - .dressed - .scene() - .map(|scene| scene.drawn()) - .filter(|d| d.triangles > 0); - let drives = (state.workbench.wardrobe.dressed.motion.as_ref()).map(|m| { +pub(super) fn bottom(ui: &mut egui::Ui, rect: egui::Rect, dressed: &Dressed) { + let drawn = dressed.drawn_counts(); + let drives = dressed.motion_drive_counts().map(|(resolved, clip_tags)| { tr!( "the clip drives {resolved} of {clip_tags} bones", - resolved = m.report.resolved, - clip_tags = m.report.clip_tags() + resolved = resolved, + clip_tags = clip_tags ) }); let figures = drawn.map(|d| { @@ -184,24 +205,22 @@ pub(super) fn bottom(ui: &mut egui::Ui, rect: egui::Rect, state: &mut AppState) } /// Whether a clip is chosen or being read, so that its controls stand under the view. -pub(super) fn is_playing(state: &AppState) -> bool { - let dressed = &state.workbench.wardrobe.dressed; - dressed.motion.is_some() || dressed.is_animating() +pub(super) fn is_playing(dressed: &Dressed) -> bool { + dressed.is_playing_clip() } /// The controls of the clip that plays, in a row under the view: over it they covered the legs and the shoes, which are what a garment is checked on. pub(super) fn transport_row(ui: &mut egui::Ui, state: &mut AppState) { - if !is_playing(state) { + if !is_playing(state.workbench.dressed()) { return; } let mut asked = None; - ui.horizontal_wrapped(|ui| transport(ui, state, &mut asked)); + ui.horizontal_wrapped(|ui| transport(ui, state.workbench.dressed_mut(), &mut asked)); carry_out(state, asked); } /// Play or pause, loop, speed and the choice among the clips of the dictionary. -fn transport(ui: &mut egui::Ui, state: &mut AppState, asked: &mut Option) { - let dressed = &mut state.workbench.wardrobe.dressed; +fn transport(ui: &mut egui::Ui, dressed: &mut Dressed, asked: &mut Option) { let Some(motion) = &mut dressed.motion else { small(ui, tr!("Reading the clip…")); return; diff --git a/src/ui/panels/wardrobe/parts.rs b/src/ui/panels/wardrobe/parts.rs index 0c2374678..7e2498b62 100644 --- a/src/ui/panels/wardrobe/parts.rs +++ b/src/ui/panels/wardrobe/parts.rs @@ -3,19 +3,23 @@ //! ⚠ **Thin by design.** What a slot wears is `Dressed::base_edits`, which the scene reads; this lays the choices out. use or_wardrobe::dress::BaseEdit; -use or_wardrobe::{Component, Slot}; +use or_wardrobe::{Component, Ped, Slot}; use super::kit::{framed, menu, tip}; use super::words::{slot_order, slot_words}; +use crate::state::workbench::Dressed; use crate::state::AppState; use crate::ui::theme; /// The one switch for a ped with no hair: the ped's own hair taken off, for this view only. pub(super) fn hide_hair(ui: &mut egui::Ui, state: &mut AppState) { let ped = state.dressed_ped(); - let dressed = &mut state.workbench.wardrobe.dressed; + hide_hair_control(ui, ped, state.workbench.dressed_mut()); +} + +fn hide_hair_control(ui: &mut egui::Ui, ped: Ped, dressed: &mut Dressed) { let has = dressed.base_slots(ped).contains(&Component::Hair); - let mut off = dressed.base_edits.get(&Component::Hair) == Some(&BaseEdit::Off); + let mut off = dressed.base_edit(Component::Hair) == Some(BaseEdit::Off); let response = ui .add_enabled(has, egui::Checkbox::new(&mut off, tr!("Ped without hair"))) .on_disabled_hover_text( @@ -26,10 +30,7 @@ pub(super) fn hide_hair(ui: &mut egui::Ui, state: &mut AppState) { tr!("Take the ped's own hair off, to see a hat or a head garment on a bare head; for this view only, nothing is written to the pack. What a hat does to the hair in the game is Hide hair under Behaviour in Details"), ); if response.changed() { - match off { - true => dressed.base_edits.insert(Component::Hair, BaseEdit::Off), - false => dressed.base_edits.remove(&Component::Hair), - }; + dressed.set_base_edit(Component::Hair, off.then_some(BaseEdit::Off)); } } @@ -45,7 +46,10 @@ fn choice(now: Option) -> String { /// The ped's own drawables, one slot at a time: left as the game dresses them, taken off, or another drawable of the ped. pub(super) fn own_parts(ui: &mut egui::Ui, state: &mut AppState) { let ped = state.dressed_ped(); - let dressed = &mut state.workbench.wardrobe.dressed; + own_parts_menu(ui, ped, state.workbench.dressed_mut()); +} + +fn own_parts_menu(ui: &mut egui::Ui, ped: Ped, dressed: &mut Dressed) { let mut slots = dressed.base_slots(ped); slots.sort_by_key(|slot| slot_order(Some(Slot::Component(*slot)))); let opened = menu(ui, tr!("Ped's own parts"), None, |ui| { @@ -59,7 +63,7 @@ pub(super) fn own_parts(ui: &mut egui::Ui, state: &mut AppState) { .show(ui, |ui| { for slot in slots { let count = dressed.base_drawables(ped, slot); - let now = dressed.base_edits.get(&slot).copied(); + let now = dressed.base_edit(slot); let words = slot_words(Slot::Component(slot)); ui.label(words); let colour = match now { @@ -77,7 +81,7 @@ pub(super) fn own_parts(ui: &mut egui::Ui, state: &mut AppState) { ui.end_row(); } }); - let edited = !dressed.base_edits.is_empty(); + let edited = dressed.has_base_edits(); if ui .add_enabled( edited, @@ -86,7 +90,7 @@ pub(super) fn own_parts(ui: &mut egui::Ui, state: &mut AppState) { .on_disabled_hover_text(tr!("Nothing is changed")) .clicked() { - dressed.base_edits.clear(); + dressed.reset_base_edits(); } }); tip( @@ -95,34 +99,27 @@ pub(super) fn own_parts(ui: &mut egui::Ui, state: &mut AppState) { ); } -fn own_choices( - ui: &mut egui::Ui, - dressed: &mut crate::state::workbench::Dressed, - slot: Component, - count: usize, -) { +fn own_choices(ui: &mut egui::Ui, dressed: &mut Dressed, slot: Component, count: usize) { + let current = dressed.base_edit(slot); if ui - .selectable_label(!dressed.base_edits.contains_key(&slot), tr!("As the game")) + .selectable_label(current.is_none(), tr!("As the game")) .clicked() { - dressed.base_edits.remove(&slot); + dressed.set_base_edit(slot, None); } if ui - .selectable_label( - dressed.base_edits.get(&slot) == Some(&BaseEdit::Off), - tr!("Off"), - ) + .selectable_label(current == Some(BaseEdit::Off), tr!("Off")) .clicked() { - dressed.base_edits.insert(slot, BaseEdit::Off); + dressed.set_base_edit(slot, Some(BaseEdit::Off)); } for n in 0..count.min(u32::MAX as usize) as u32 { - let now = dressed.base_edits.get(&slot) == Some(&BaseEdit::Drawable(n)); + let now = current == Some(BaseEdit::Drawable(n)); if ui .selectable_label(now, tr!("Drawable {n}", n = n)) .clicked() { - dressed.base_edits.insert(slot, BaseEdit::Drawable(n)); + dressed.set_base_edit(slot, Some(BaseEdit::Drawable(n))); } } } diff --git a/src/ui/panels/wardrobe/preview.rs b/src/ui/panels/wardrobe/preview.rs index b3cf9b118..16eb8be69 100644 --- a/src/ui/panels/wardrobe/preview.rs +++ b/src/ui/panels/wardrobe/preview.rs @@ -34,8 +34,8 @@ pub fn draw(ui: &mut egui::Ui, state: &mut AppState, bridge: Option<&mut RenderB } let mut shown = state.panels.take::(); shown.drop_preview = Some((ui.max_rect(), ui.ctx().cumulative_pass_nr())); - let dressed = &state.workbench.wardrobe.dressed; - if dressed.is_reading() || dressed.is_cataloguing() { + let dressed = state.workbench.dressed(); + if dressed.needs_poll_repaint() { ui.ctx() .request_repaint_after(std::time::Duration::from_millis(50)); } @@ -45,7 +45,7 @@ pub fn draw(ui: &mut egui::Ui, state: &mut AppState, bridge: Option<&mut RenderB wear::wear(ui, state); wear::show(ui, state); tools::draw(ui, state); - let playing = overlay::is_playing(state); + let playing = overlay::is_playing(state.workbench.dressed()); let strip = STRIP_FULL + if playing { TRANSPORT_ROW } else { 0.0 }; let compact = ui.available_height() < strip + VIEW_COMFORTABLE; egui::Panel::bottom(ui.id().with("dressed_strip")) @@ -53,7 +53,7 @@ pub fn draw(ui: &mut egui::Ui, state: &mut AppState, bridge: Option<&mut RenderB .show_inside(ui, |ui| { overlay::helpers(ui, state); overlay::transport_row(ui, state); - tiles::notes(ui, state); + tiles::notes(ui, state.workbench.dressed_mut()); tiles::variants(ui, state, &mut shown, compact); }); view(ui, state, bridge); @@ -78,10 +78,11 @@ fn view(ui: &mut egui::Ui, state: &mut AppState, bridge: Option<&mut RenderBridg ); } } - overlay::escape_leaves(ui, &response, state); - overlay::first_person(ui, rect, state); + let asking = state.workbench.is_asking(); + overlay::escape_leaves(ui, &response, state.workbench.dressed_mut(), asking); + overlay::first_person(ui, rect, state.workbench.dressed_mut()); overlay::no_game(ui, rect, state); - overlay::bottom(ui, rect, state); + overlay::bottom(ui, rect, state.workbench.dressed()); } fn draw_scene( @@ -92,22 +93,19 @@ fn draw_scene( response: &egui::Response, ) { // The textures are the point of a dressed ped, so it starts in Material; the view is the person's after that. - let (shading, channel) = { - let dressed = &state.workbench.wardrobe.dressed; - (dressed.view.shading(), dressed.view.channel()) - }; + let (shading, channel) = state.workbench.dressed().shading_and_channel(); bridge.set_mode(shading); let ppp = ui.ctx().pixels_per_point(); bridge.set_desired_size( (rect.width() * ppp).round() as u32, (rect.height() * ppp).round() as u32, ); - let dressed = &state.workbench.wardrobe.dressed; + let dressed = state.workbench.dressed(); + let pose = dressed.pose_skin(); bridge.refresh_dressed_as(dressed.scene(), channel); bridge.refresh_dressed_game(dressed.scene()); - bridge.pose_dressed_game(dressed.motion.as_ref().map(|m| (m.revision(), m.skin()))); + bridge.pose_dressed_game(pose); if let Some(scene) = dressed.scene() { - let pose = dressed.motion.as_ref().map(|m| (m.revision(), m.skin())); bridge.pose_dressed(scene, pose); } // ⚠ After the ped is posed: the wireframe is drawn from the vertices the pose wrote. @@ -156,7 +154,7 @@ fn draw_scene( egui::StrokeKind::Inside, ); if !state.dressed_is_ready() { - let words = if state.workbench.wardrobe.dressed.is_reading() { + let words = if state.workbench.dressed().is_reading() { tr!("Reading the files…") } else { tr!("Select a garment to see it worn") diff --git a/src/ui/panels/wardrobe/query_bar.rs b/src/ui/panels/wardrobe/query_bar.rs index 03a6b48e6..ff62fe6dd 100644 --- a/src/ui/panels/wardrobe/query_bar.rs +++ b/src/ui/panels/wardrobe/query_bar.rs @@ -47,12 +47,10 @@ fn count(read: &crate::state::workbench::PackRead) -> Vec { pub(super) fn draw(ui: &mut egui::Ui, state: &mut AppState, shown: &mut WardrobeUi, module: &str) { let parsed = Query::parse(&shown.filter); - let generation = state.workbench.wardrobe.generation; + let generation = state.workbench.wardrobe().generation(); let Some(read) = state .workbench - .packs() - .iter() - .find(|p| p.module == module) + .pack(module) .and_then(|p| p.read.as_ref().ok()) else { return; @@ -115,7 +113,7 @@ pub(super) fn draw(ui: &mut egui::Ui, state: &mut AppState, shown: &mut Wardrobe } Some(Asked::Forget(name)) => state.forget_query(module.to_string(), name), Some(Asked::Save) => { - state.workbench.asking = Some(Question::SaveQuery { + state.workbench.ask(Question::SaveQuery { module: module.to_string(), query: shown .filter diff --git a/src/ui/panels/wardrobe/quick.rs b/src/ui/panels/wardrobe/quick.rs index c64abf5e3..ebbc75554 100644 --- a/src/ui/panels/wardrobe/quick.rs +++ b/src/ui/panels/wardrobe/quick.rs @@ -67,12 +67,12 @@ fn about(state: &AppState) -> Option { pub(super) fn draw(ui: &mut egui::Ui, state: &mut AppState, shown: &mut WardrobeUi) { let Some(about) = about(state) else { - state.workbench.wardrobe.quick_look = false; + state.workbench.wardrobe_mut().close_quick_look(); return; }; let crypto = state.keys.provider(); let want = about.file.clone().and_then(Want::of_file); - let glance = &mut state.workbench.wardrobe.glance; + let glance = state.workbench.wardrobe_mut().glance_mut(); let picture: Option, String>> = match glance.look(want, &crypto) { Glimpse::Nothing => None, Glimpse::Reading => Some(Err(String::new())), @@ -115,7 +115,7 @@ pub(super) fn draw(ui: &mut egui::Ui, state: &mut AppState, shown: &mut Wardrobe }); }); if !open || ui.ctx().input(|i| i.key_pressed(egui::Key::Escape)) { - state.workbench.wardrobe.quick_look = false; + state.workbench.wardrobe_mut().close_quick_look(); } } diff --git a/src/ui/panels/wardrobe/recover.rs b/src/ui/panels/wardrobe/recover.rs index 5a7d258a4..62be5ce7f 100644 --- a/src/ui/panels/wardrobe/recover.rs +++ b/src/ui/panels/wardrobe/recover.rs @@ -77,7 +77,7 @@ pub(super) fn versions_menu(ui: &mut egui::Ui, state: &mut AppState) { .wardrobe_pack() .and_then(|p| p.read.as_ref().ok()) .map(|read| &read.wardrobe); - let Some(versions) = state.workbench.wardrobe.versions.as_ref() else { + let Some(versions) = state.workbench.wardrobe().versions() else { return; }; if versions.list.is_empty() { @@ -168,7 +168,7 @@ pub(super) fn garment_versions( return; } let (Some(versions), Some(now)) = ( - state.workbench.wardrobe.versions.as_ref(), + state.workbench.wardrobe().versions(), state .wardrobe_pack() .and_then(|p| p.read.as_ref().ok()) diff --git a/src/ui/panels/wardrobe/tiles.rs b/src/ui/panels/wardrobe/tiles.rs index d1fb8a1cf..a5324f7b0 100644 --- a/src/ui/panels/wardrobe/tiles.rs +++ b/src/ui/panels/wardrobe/tiles.rs @@ -4,7 +4,7 @@ //! there is not, so that the view above is never drawn over them. use super::WardrobeUi; -use crate::state::workbench::{Thumb, NO_GAME}; +use crate::state::workbench::{Dressed, Thumb}; use crate::state::AppState; use crate::ui::accessible_name::named; use crate::ui::theme; @@ -22,20 +22,10 @@ const CAPTION: usize = 15; const EMPTY: &str = tr_key!("empty texture"); /// What the preview could not do, and the way to mend it where there is one. -pub(super) fn notes(ui: &mut egui::Ui, state: &mut AppState) { - let dressed = &state.workbench.wardrobe.dressed; +pub(super) fn notes(ui: &mut egui::Ui, dressed: &mut Dressed) { let retry = dressed.base_missing().is_some(); // ⚠ The note that no game install is chosen stands over the view, with the button that chooses one. - let mut lines: Vec = (dressed.notes.iter()) - .filter(|note| note.as_str() != crate::i18n::tr(NO_GAME)) - .take(4) - .cloned() - .collect(); - let more = (dressed.notes.iter()) - .filter(|note| note.as_str() != crate::i18n::tr(NO_GAME)) - .count() - .saturating_sub(4); - lines.extend(dressed.clip_note.clone()); + let (lines, more) = dressed.visible_notes(4); let mut again = false; ui.horizontal_wrapped(|ui| { for line in &lines { @@ -57,7 +47,7 @@ pub(super) fn notes(ui: &mut egui::Ui, state: &mut AppState) { } }); if again { - state.workbench.wardrobe.dressed.retry_base(); + dressed.retry_base(); } } @@ -85,7 +75,8 @@ pub(super) fn variants( } let wearing = state.dressed_variation(&id); let linked = pack.linked; - let reading = state.workbench.wardrobe.dressed.is_reading(); + let dressed = state.workbench.dressed(); + let reading = dressed.is_reading(); let mut chosen = None; egui::ScrollArea::horizontal() .id_salt("dressed_variants") @@ -99,10 +90,7 @@ pub(super) fn variants( || crate::i18n::tr(EMPTY).to_string(), |n| n.to_string_lossy().into_owned(), ); - let thumb = file - .as_deref() - .and_then(|f| state.workbench.wardrobe.dressed.thumb(f)) - .cloned(); + let thumb = file.as_deref().and_then(|f| dressed.thumb(f)).cloned(); let absent = match (&file, reading) { (None, _) => crate::i18n::tr(EMPTY), (Some(_), true) => tr!("reading…"), @@ -145,7 +133,7 @@ pub(super) fn variants( }); }); if let Some(i) = chosen { - state.workbench.wardrobe.dressed.variation.insert(id, i); + state.workbench.dressed_mut().set_variation(id, i); } } diff --git a/src/ui/panels/wardrobe/tools.rs b/src/ui/panels/wardrobe/tools.rs index 99e0236a7..104cfbfdb 100644 --- a/src/ui/panels/wardrobe/tools.rs +++ b/src/ui/panels/wardrobe/tools.rs @@ -69,7 +69,7 @@ fn why_not_shaded(status: &GamePackStatus) -> String { fn view_mode(ui: &mut egui::Ui, state: &mut AppState) { // ⚠ Shaded draws as Material until the game's shaders are baked, so it is not offered before: a choice that changes nothing is worse than none. - let status = state.game_pack.status().clone(); + let status = state.install.game_pack.status().clone(); let baked = matches!(status, GamePackStatus::Ready { .. }); let dressed = &mut state.workbench.wardrobe.dressed; // Two lines a choice, eight choices: taller than a list of one-line words, which would scroll. diff --git a/src/ui/panels/wardrobe/views.rs b/src/ui/panels/wardrobe/views.rs index 30fdba70a..42c7318c4 100644 --- a/src/ui/panels/wardrobe/views.rs +++ b/src/ui/panels/wardrobe/views.rs @@ -5,6 +5,7 @@ use or_wardrobe::dress::Sets; use super::kit::combo; +use crate::state::workbench::Dressed; use crate::state::AppState; use crate::ui::guide_links::{self, CHECK_ON_THE_PED}; @@ -26,12 +27,10 @@ pub(super) fn sets_of_the_ped(state: &AppState) -> Vec<(String, String)> { /// Which sets of alternate variations the ped wears: those a garment worn causes, none, or one of the pack's sets as if its garment were worn. /// /// Not drawn where the pack has no set for the ped. -pub(super) fn alternate_sets(ui: &mut egui::Ui, state: &mut AppState) { - let sets = sets_of_the_ped(state); +pub(super) fn alternate_sets(ui: &mut egui::Ui, dressed: &mut Dressed, sets: &[(String, String)]) { if sets.is_empty() { return; } - let dressed = &mut state.workbench.wardrobe.dressed; let shown = match &dressed.sets { Sets::Worn => tr!("As worn").to_string(), Sets::Off => tr!("None").to_string(), @@ -44,7 +43,7 @@ pub(super) fn alternate_sets(ui: &mut egui::Ui, state: &mut AppState) { .on_hover_text(tr!("The sets a garment worn causes, as the game applies them: a hat that changes the hair changes it here")); ui.selectable_value(&mut dressed.sets, Sets::Off, tr!("None")) .on_hover_text(tr!("No set: every garment is worn with its own model")); - for (id, name) in &sets { + for (id, name) in sets { ui.selectable_value(&mut dressed.sets, Sets::Only(id.clone()), name) .on_hover_text(tr!( "Only this set, as if a garment that causes it were worn" diff --git a/src/ui/panels/wardrobe/watched.rs b/src/ui/panels/wardrobe/watched.rs index 93053dd9f..2eb8761c3 100644 --- a/src/ui/panels/wardrobe/watched.rs +++ b/src/ui/panels/wardrobe/watched.rs @@ -5,7 +5,7 @@ use or_wardrobe::slots::{Binding, MapSlot}; use or_wardrobe::Garment; -use crate::state::AppState; +use crate::state::workbench::WardrobeWork; use crate::ui::theme; /// What the controls asked for, carried out once the panel is drawn. @@ -23,19 +23,11 @@ fn letter(i: usize) -> char { } /// The watched-folders section for garment `g`. -pub(super) fn draw(ui: &mut egui::Ui, state: &AppState, g: &Garment, asked: &mut Asked) { +pub(super) fn draw(ui: &mut egui::Ui, wardrobe: &WardrobeWork, g: &Garment, asked: &mut Asked) { if g.variations.is_empty() { return; } - let mine: Vec<&Binding> = state - .workbench - .wardrobe - .textures - .bindings() - .iter() - .map(|(_, _, b)| b) - .filter(|b| b.garment == g.id) - .collect(); + let mine = wardrobe.bindings_for_garment(&g.id); egui::CollapsingHeader::new(tr!("Watched folders")) .id_salt(("watched folders", &g.id, mine.is_empty())) .default_open(!mine.is_empty()) diff --git a/src/ui/panels/wardrobe/wear.rs b/src/ui/panels/wardrobe/wear.rs index 098b80ffa..c23b0b8ab 100644 --- a/src/ui/panels/wardrobe/wear.rs +++ b/src/ui/panels/wardrobe/wear.rs @@ -8,6 +8,7 @@ use or_wardrobe::Ped; use super::kit::{combo_with, framed, menu, segments, tip, Part}; use super::words::ped_words; +use crate::state::workbench::Dressed; use crate::state::AppState; /// Why a control of the ped itself is greyed while no game install is chosen. @@ -18,11 +19,32 @@ pub(super) fn wear(ui: &mut egui::Ui, state: &mut AppState) { let ped = state.dressed_ped(); let selected = state .workbench - .wardrobe - .selected - .as_ref() - .map(|(_, id)| id.clone()); + .wardrobe() + .selected_garment_id() + .map(str::to_string); let has_game = state.prefs.active_game_root().is_some(); + let alternates = super::light::alternates_of_the_selected(state); + let sets = super::views::sets_of_the_ped(state); + wear_controls( + ui, + state.workbench.dressed_mut(), + ped, + selected.as_deref(), + has_game, + alternates.as_ref(), + &sets, + ); +} + +fn wear_controls( + ui: &mut egui::Ui, + dressed: &mut Dressed, + ped: Ped, + selected: Option<&str>, + has_game: bool, + alternates: Option<&(String, Vec)>, + sets: &[(String, String)], +) { let mut asked_ped = None; ui.horizontal_wrapped(|ui| { let parts = Ped::ALL.map(|candidate| Part { @@ -34,7 +56,6 @@ pub(super) fn wear(ui: &mut egui::Ui, state: &mut AppState) { if let Some(at) = segments(ui, &parts) { asked_ped = Some(Ped::ALL[at]); } - let dressed = &mut state.workbench.wardrobe.dressed; let skin = combo_with(ui, tr!("Skin"), dressed.tone.name(), has_game, None, |ui| { for tone in Tone::ALL { ui.selectable_value(&mut dressed.tone, tone, tone.name()); @@ -42,8 +63,7 @@ pub(super) fn wear(ui: &mut egui::Ui, state: &mut AppState) { }); let skin = skin.on_disabled_hover_text(crate::i18n::tr(NEEDS_THE_GAME)); tip(skin, tr!("The skin tone of the ped's own head")); - outfit(ui, state, selected.as_ref()); - let dressed = &mut state.workbench.wardrobe.dressed; + outfit(ui, dressed, selected); let heels = if dressed.lift != 0.0 { tr!("Heels ({lift} mm)", lift = format!("{:+.0}", dressed.lift * 1000.0)) } else { @@ -55,30 +75,27 @@ pub(super) fn wear(ui: &mut egui::Ui, state: &mut AppState) { ); }); // ⚠ A row of their own, whole or not at all: the first row has no room for two more drop-downs at the smallest window. - let has_choices = super::light::alternates_of_the_selected(state).is_some() - || !super::views::sets_of_the_ped(state).is_empty(); - if has_choices { + if alternates.is_some() || !sets.is_empty() { ui.horizontal_wrapped(|ui| { - super::light::alternate_model(ui, state); - super::views::alternate_sets(ui, state); + if let Some((id, files)) = alternates { + super::light::alternate_model(ui, dressed, id, files); + } + super::views::alternate_sets(ui, dressed, sets); }); } if let Some(ped) = asked_ped { - let dressed = &mut state.workbench.wardrobe.dressed; - dressed.ped = Some(ped); - dressed.frame_again(); + dressed.select_ped(ped); } } /// The outfit: the garments worn together, the garment selected put in or taken out, and the way to take everything off. -fn outfit(ui: &mut egui::Ui, state: &mut AppState, selected: Option<&String>) { - let dressed = &mut state.workbench.wardrobe.dressed; +fn outfit(ui: &mut egui::Ui, dressed: &mut Dressed, selected: Option<&str>) { let worn = dressed.outfit.len(); let name = match worn { 0 => tr!("Outfit").to_string(), n => tr!("Outfit ({n})", n = n), }; - let in_outfit = selected.is_some_and(|id| dressed.outfit.contains(id)); + let in_outfit = selected.is_some_and(|id| dressed.is_in_outfit(id)); let (mut toggle, mut clear) = (false, false); let opened = menu(ui, &name, None, |ui| { framed(ui); @@ -113,8 +130,7 @@ fn outfit(ui: &mut egui::Ui, state: &mut AppState, selected: Option<&String>) { ); if toggle { if let Some(id) = selected { - dressed.toggle_in_outfit(id); - dressed.outfit_on = true; + dressed.toggle_and_wear_outfit(id); } } if clear { @@ -124,7 +140,7 @@ fn outfit(ui: &mut egui::Ui, state: &mut AppState, selected: Option<&String>) { /// Which version of the pack the view shows: the ped without it, with it, or with it as it was before its last change. pub(super) fn show(ui: &mut egui::Ui, state: &mut AppState) { - let dressed = &state.workbench.wardrobe.dressed; + let dressed = state.workbench.dressed(); let (original, previous) = (dressed.original, dressed.previous); let has_game = state.prefs.active_game_root().is_some(); let mut asked = None; @@ -153,14 +169,8 @@ pub(super) fn show(ui: &mut egui::Ui, state: &mut AppState) { asked = segments(ui, &parts); }); match asked { - Some(0) => { - let dressed = &mut state.workbench.wardrobe.dressed; - (dressed.original, dressed.previous) = (true, false); - } - Some(1) => { - let dressed = &mut state.workbench.wardrobe.dressed; - (dressed.original, dressed.previous) = (false, false); - } + Some(0) => state.workbench.dressed_mut().show_original(), + Some(1) => state.workbench.dressed_mut().show_current_pack(), Some(_) => state.show_previous_version(), None => {} } diff --git a/src/ui/panels/weapons/list.rs b/src/ui/panels/weapons/list.rs index b9fcdcda2..068280c54 100644 --- a/src/ui/panels/weapons/list.rs +++ b/src/ui/panels/weapons/list.rs @@ -64,7 +64,7 @@ pub fn draw(ui: &mut egui::Ui, state: &mut AppState) { let mut shown = state.panels.take::(); shown.drop = Some((ui.max_rect(), ui.ctx().cumulative_pass_nr())); header(ui, state); - let filter = state.workbench.weapons.filter.clone(); + let filter = state.workbench.weapons().filter().to_string(); match rows(state, &filter) { None => { ui.label(egui::RichText::new(tr!("Reading the weapons…")).color(theme::TEXT_SECONDARY)); @@ -104,7 +104,7 @@ fn header(ui: &mut egui::Ui, state: &mut AppState) { ui.horizontal(|ui| { // ⚠ The filter leaves room for the two buttons beside it, so that neither wraps to a line of its own in a narrow panel. let room = 2.0 * (STEP_BUTTON + ui.spacing().item_spacing.x); - let filter = &mut state.workbench.weapons.filter; + let filter = state.workbench.weapons_mut().filter_mut(); let field = ui.add( egui::TextEdit::singleline(filter) .hint_text(tr!("Filter weapons by name")) @@ -132,7 +132,7 @@ fn body(ui: &mut egui::Ui, state: &mut AppState, rows: &[Row]) { for row in rows { groups.entry(row.group.as_str()).or_default().push(row); } - let selected = state.workbench.weapons.selected.clone(); + let selected = state.workbench.weapons().selected_id().map(str::to_string); let module = state .weapons_pack() .map(|p| p.module.clone()) diff --git a/src/ui/panels/weapons/preview.rs b/src/ui/panels/weapons/preview.rs index 26b5b33e5..dc0a02132 100644 --- a/src/ui/panels/weapons/preview.rs +++ b/src/ui/panels/weapons/preview.rs @@ -9,7 +9,7 @@ use or_weapons::assemble::assemble; use super::WeaponsUi; use crate::render::viewport::CameraInputs; use crate::render::RenderBridge; -use crate::state::workbench::ViewMode; +use crate::state::workbench::{ViewMode, WeaponsWork}; use crate::state::AppState; use crate::ui::accessible_name::named; use crate::ui::theme; @@ -35,7 +35,7 @@ fn places(state: &AppState) -> Vec { return Vec::new(); }; let assembly = assemble(weapon, &read.facts); - let choice = &state.workbench.weapons.choice; + let choice = state.workbench.weapons().choice(); let worn = or_weapons::assemble::worn(&assembly, choice); let mut places: Vec = Vec::new(); for part in &assembly.parts { @@ -61,15 +61,9 @@ pub fn draw(ui: &mut egui::Ui, state: &mut AppState, bridge: Option<&mut RenderB } let mut shown = state.panels.take::(); shown.drop_preview = Some((ui.max_rect(), ui.ctx().cumulative_pass_nr())); - match state.weapon_scene_request() { - Some(request) => { - let crypto = state.keys.provider(); - state.workbench.weapons.scene.want(request, crypto); - } - None => state.workbench.weapons.scene.clear(), - } - state.workbench.weapons.scene.poll(); - if state.workbench.weapons.scene.is_reading() { + let request = state.weapon_scene_request(); + let crypto = state.keys.provider(); + if state.workbench.weapons_mut().sync_preview(request, crypto) { ui.ctx() .request_repaint_after(std::time::Duration::from_millis(50)); } @@ -82,24 +76,25 @@ pub fn draw(ui: &mut egui::Ui, state: &mut AppState, bridge: Option<&mut RenderB state.panels.put(shown); return; } - tools(ui, state); + let bone_places = places(state); + tools(ui, state.workbench.weapons_mut(), &bone_places); view(ui, state, bridge); state.panels.put(shown); } /// How the weapon is drawn, and the part worn at each bone. -fn tools(ui: &mut egui::Ui, state: &mut AppState) { +fn tools(ui: &mut egui::Ui, weapons: &mut WeaponsWork, bone_places: &[Place]) { ui.horizontal(|ui| { ui.label(egui::RichText::new(tr!("Shown as")).color(theme::TEXT_SECONDARY)); for mode in VIEWS { - let on = state.workbench.weapons.view == mode; + let on = weapons.view_mode() == mode; let response = ui.selectable_label(on, mode.name()); if named(response, mode.name()).clicked() { - state.workbench.weapons.view = mode; + weapons.set_view_mode(mode); } } }); - for place in places(state) { + for place in bone_places { ui.horizontal_wrapped(|ui| { ui.label( egui::RichText::new(tr!("Part at {bone}", bone = place.bone.as_str())) @@ -113,20 +108,12 @@ fn tools(ui: &mut egui::Ui, state: &mut AppState) { ) .clicked() { - state - .workbench - .weapons - .choice - .insert(place.bone.clone(), None); + weapons.choose_part(place.bone.clone(), None); } for option in &place.options { let on = place.worn.as_deref() == Some(option.as_str()); if ui.selectable_label(on, option).clicked() { - state - .workbench - .weapons - .choice - .insert(place.bone.clone(), Some(option.clone())); + weapons.choose_part(place.bone.clone(), Some(option.clone())); } } }); @@ -149,14 +136,14 @@ fn view(ui: &mut egui::Ui, state: &mut AppState, bridge: Option<&mut RenderBridg ); return; }; - let mode = state.workbench.weapons.view; + let mode = state.workbench.weapons().view_mode(); bridge.set_mode(mode.shading()); let ppp = ui.ctx().pixels_per_point(); bridge.set_desired_size( (rect.width() * ppp).round() as u32, (rect.height() * ppp).round() as u32, ); - bridge.refresh_dressed_as(state.workbench.weapons.scene.scene.as_ref(), mode.channel()); + bridge.refresh_dressed_as(state.workbench.weapons().preview_scene(), mode.channel()); bridge.refresh_lines(state); let mut inputs = CameraInputs::default(); @@ -201,18 +188,7 @@ fn view(ui: &mut egui::Ui, state: &mut AppState, bridge: Option<&mut RenderBridg egui::Stroke::new(1.0_f32, theme::BORDER), egui::StrokeKind::Inside, ); - let said = match ( - &state.workbench.weapons.scene.error, - state.workbench.weapons.scene.is_reading(), - ) { - (Some(why), _) => Some(why.clone()), - (None, true) => Some(tr!("Reading the files…").to_string()), - (None, false) if state.workbench.weapons.scene.scene.is_none() => { - Some(tr!("The weapon has no model in the pack to draw").to_string()) - } - _ => None, - }; - if let Some(said) = said { + if let Some(said) = state.workbench.weapons().preview_status() { ui.painter().text( rect.center_bottom() - egui::vec2(0.0, 12.0), egui::Align2::CENTER_BOTTOM, diff --git a/src/ui/panels/weapons/weapon.rs b/src/ui/panels/weapons/weapon.rs index 5afcf28e8..81f899f87 100644 --- a/src/ui/panels/weapons/weapon.rs +++ b/src/ui/panels/weapons/weapon.rs @@ -112,11 +112,8 @@ pub fn draw(ui: &mut egui::Ui, state: &mut AppState) { ui.add_space(theme::SPACING_HAIR); ui.horizontal(|ui| { ui.label(egui::RichText::new(tr!("Name")).color(theme::TEXT_SECONDARY)); - let work = &mut state.workbench.weapons; - let typed = match &mut work.renaming { - Some((held, typed)) if *held == id => typed, - slot => &mut slot.insert((id.clone(), name.clone())).1, - }; + let weapons = state.workbench.weapons_mut(); + let typed = weapons.rename_draft(&id, &name); let field = ui.add_enabled( editable, egui::TextEdit::singleline(typed).desired_width(f32::INFINITY), @@ -124,7 +121,7 @@ pub fn draw(ui: &mut egui::Ui, state: &mut AppState) { let field = named(field, tr!("Weapon name")); if field.lost_focus() { let new = typed.clone(); - work.renaming = None; + weapons.clear_rename(); state.rename_selected_weapon(&new); } }); diff --git a/src/ui/panels/world_viewer/plain.rs b/src/ui/panels/world_viewer/plain.rs index 36a85a803..b74c9b7ba 100644 --- a/src/ui/panels/world_viewer/plain.rs +++ b/src/ui/panels/world_viewer/plain.rs @@ -388,7 +388,7 @@ pub(super) fn selection( /// The view: the world through the fly camera. pub fn draw_view(ui: &mut egui::Ui, state: &mut AppState, bridge: Option<&mut RenderBridge>) { state.world_follows_the_project(); - let pack_status = state.game_pack.status().short_label(); + let pack_status = state.install.game_pack.status().short_label(); let keyed = view_keys::edit_key(ui, &state.prefs); let held = state.panels.get_or_default_mut::(); let was_clean = held.clean; @@ -583,7 +583,7 @@ pub fn draw_view(ui: &mut egui::Ui, state: &mut AppState, bridge: Option<&mut Re /// The panel beside the view. pub fn draw_side(ui: &mut egui::Ui, state: &mut AppState, bridge: Option<&mut RenderBridge>) { let drawn = bridge.as_deref().map(|bridge| bridge.world_drawn()); - let pack_status = state.game_pack.status().short_label(); + let pack_status = state.install.game_pack.status().short_label(); let Some(session) = state.world_session() else { return; }; diff --git a/src/ui/panels/ycd_clips.rs b/src/ui/panels/ycd_clips.rs index 9d14689cf..eaaaabf0b 100644 --- a/src/ui/panels/ycd_clips.rs +++ b/src/ui/panels/ycd_clips.rs @@ -53,10 +53,13 @@ pub fn draw(ui: &mut egui::Ui, state: &mut AppState) { let buckets = dict.clips.hash.len(); let dict = dict.clone(); for name in embedded { - state.name_index.add(NameIndexCategory::ClipSet, name); + state + .install + .name_index + .add(NameIndexCategory::ClipSet, name); } - let rows = build_rows(&dict, &state.name_index); + let rows = build_rows(&dict, &state.install.name_index); let total = rows.len(); ui.horizontal(|ui| { diff --git a/src/ui/tests/every_context_menu_draws_from_the_registry.rs b/src/ui/tests/every_context_menu_draws_from_the_registry.rs index c8d758180..b4044fe7a 100644 --- a/src/ui/tests/every_context_menu_draws_from_the_registry.rs +++ b/src/ui/tests/every_context_menu_draws_from_the_registry.rs @@ -550,8 +550,8 @@ fn every_context_menu_offers_its_app_commands_with_the_registrys_label_binding_a .game_paths .set(game, Some(dir.path().to_path_buf())); state.prefs.active_game = Some(game); - state.search.root = Some(dir.path().to_path_buf()); - state.search.hits = vec![or_title::install::content::ContentHit { + state.find.session.root = Some(dir.path().to_path_buf()); + state.find.session.hits = vec![or_title::install::content::ContentHit { path: "notes.txt".into(), container: or_title::install::LOOSE.into(), offsets: vec![0], diff --git a/src/ui/tests/the_counts_of_only_one_type_read_nothing_until_clicked.rs b/src/ui/tests/the_counts_of_only_one_type_read_nothing_until_clicked.rs index e4632cec6..15653c7e4 100644 --- a/src/ui/tests/the_counts_of_only_one_type_read_nothing_until_clicked.rs +++ b/src/ui/tests/the_counts_of_only_one_type_read_nothing_until_clicked.rs @@ -60,7 +60,7 @@ fn drawn_now(ctx: &egui::Context, state: &mut AppState) -> Vec { fn settle(state: &mut AppState, doc: DocumentId) { let until = Instant::now() + Duration::from_secs(30); - while state.expander.is_listing(doc) { + while state.bg.expander.is_listing(doc) { assert!(Instant::now() < until, "the tree's scan never finished"); state.poll_expansions(); std::thread::sleep(Duration::from_millis(2)); @@ -128,7 +128,7 @@ fn the_submenu_of_only_one_type_reads_no_archive_until_count_types_is_clicked() std::thread::sleep(Duration::from_millis(5)); } assert!( - !state.expander.is_listing(doc), + !state.bg.expander.is_listing(doc), "drawing the submenu asked for a read" ); assert_eq!( diff --git a/src/ui/tests/the_error_and_close_questions_say_what_they_act_on_on_screen.rs b/src/ui/tests/the_error_and_close_questions_say_what_they_act_on_on_screen.rs index 9ac2e99bf..d0886ebcf 100644 --- a/src/ui/tests/the_error_and_close_questions_say_what_they_act_on_on_screen.rs +++ b/src/ui/tests/the_error_and_close_questions_say_what_they_act_on_on_screen.rs @@ -20,7 +20,7 @@ fn a_file_that_will_not_open(dir: &std::path::Path) -> Shell { let mut shell = a_first_launch(); shell.state.load_file(bad); let until = Instant::now() + Duration::from_secs(30); - while !shell.state.show_error_dialog { + while !shell.state.error_dialog.show { assert!(Instant::now() < until, "the file never failed to open"); shell.state.poll_load_result(); shell.draw_sized(SMALLEST, Vec::new()); @@ -64,12 +64,12 @@ fn a_file_that_will_not_open_is_named_said_in_plain_words_and_keeps_the_library_ "the details do not keep the file and the library's own words: {copied}" ); assert!( - shell.state.show_error_dialog, + shell.state.error_dialog.show, "Copy details closed the window" ); shell.draw_sized(SMALLEST, vec![key(egui::Key::Escape)]); assert!( - !shell.state.show_error_dialog, + !shell.state.error_dialog.show, "Escape does not close the error window" ); } @@ -130,7 +130,7 @@ fn closing_a_project_lists_what_is_dropped_names_the_file_once_and_escape_is_can shell.draw_sized(SMALLEST, vec![key(egui::Key::Escape)]); shell.settled_sized(SMALLEST); assert!( - shell.state.pending_close.is_none(), + shell.state.prompts.close.is_none(), "Escape does not answer Cancel" ); assert!( diff --git a/src/ui/tests/the_maps_screen_on_screen.rs b/src/ui/tests/the_maps_screen_on_screen.rs index 78bb41038..c41520b6c 100644 --- a/src/ui/tests/the_maps_screen_on_screen.rs +++ b/src/ui/tests/the_maps_screen_on_screen.rs @@ -66,6 +66,7 @@ pub(super) fn a_maps_shell(dir: &Path) -> Shell { for name in ["prop_crate_a", "prop_crate_b"] { shell .state + .install .name_index .add(crate::state::name_index::NameIndexCategory::Model, name); } diff --git a/src/ui/tests/the_top_flows_end_to_end/installs.rs b/src/ui/tests/the_top_flows_end_to_end/installs.rs index c78da07c3..ea935d8b5 100644 --- a/src/ui/tests/the_top_flows_end_to_end/installs.rs +++ b/src/ui/tests/the_top_flows_end_to_end/installs.rs @@ -18,10 +18,10 @@ fn open_from_install(at: &mut Flow, path: &str) -> Step { at.double_click_row(&name)?; let wanted = name.clone(); at.wait(&format!("{name} open"), move |flow| { - flow.shell.state.show_error_dialog || flow.active_name() == wanted + flow.shell.state.error_dialog.show || flow.active_name() == wanted })?; - if at.shell.state.show_error_dialog { - let said = at.shell.state.error_dialog_message.clone(); + if at.shell.state.error_dialog.show { + let said = at.shell.state.error_dialog.message.clone(); return Err(format!("{name} did not open: {said}")); } Ok(()) diff --git a/src/ui/tests/the_top_flows_end_to_end/mod.rs b/src/ui/tests/the_top_flows_end_to_end/mod.rs index 5c19c4647..0cb8adbe2 100644 --- a/src/ui/tests/the_top_flows_end_to_end/mod.rs +++ b/src/ui/tests/the_top_flows_end_to_end/mod.rs @@ -342,11 +342,11 @@ impl Flow { let wanted = path.to_path_buf(); self.wait(&format!("{} open", path.display()), move |flow| { let state = &flow.shell.state; - state.show_error_dialog + state.error_dialog.show || (state.active_document()).is_some_and(|d| d.path.as_ref() == Some(&wanted)) })?; - if self.shell.state.show_error_dialog { - let said = self.shell.state.error_dialog_message.clone(); + if self.shell.state.error_dialog.show { + let said = self.shell.state.error_dialog.message.clone(); return Err(format!("{} did not open: {said}", path.display())); } Ok(()) @@ -359,7 +359,7 @@ impl Flow { /// The search of this machine for installs over: a launch starts it and it ends within a few seconds. pub(super) fn wait_for_the_installs(&mut self) { let _ = self.wait_within(Duration::from_secs(20), "the search for installs", |flow| { - !flow.shell.state.discovery.is_running() + !flow.shell.state.bg.discovery.is_running() }); } @@ -377,7 +377,7 @@ impl Flow { self.click_beside("Open", game)?; self.wait("the install's rows", |flow| { let state = &flow.shell.state; - (state.active_document()).is_some_and(|doc| !state.expander.is_listing(doc.id)) + (state.active_document()).is_some_and(|doc| !state.bg.expander.is_listing(doc.id)) }) } @@ -407,7 +407,7 @@ impl Flow { let (file, before) = (to.to_path_buf(), self.toasts.len()); self.wait(&format!("{} written", to.display()), move |flow| { std::fs::metadata(&file).is_ok_and(|m| m.len() > 0) - || flow.shell.state.show_error_dialog + || flow.shell.state.error_dialog.show || flow.toasts.len() > before })?; if !to.exists() { diff --git a/src/video/mod.rs b/src/video/mod.rs index e56a42be7..0ed1b7c4b 100644 --- a/src/video/mod.rs +++ b/src/video/mod.rs @@ -9,8 +9,6 @@ use or_media::{Decoders, Frame, MediaError, VideoStream}; pub mod bink; -use crate::state::{AppState, DocPayload, DocumentId}; - pub const PREVIEW_WIDTH: u32 = 640; pub const PREVIEW_HEIGHT: u32 = 360; /// Frames per second a movie that states no rate plays at. @@ -33,36 +31,12 @@ impl BikDocument { preview: Arc::default(), } } -} -impl AppState { - /// The document's preview, started on first use. - pub fn video_preview(&self, doc: DocumentId) -> Option> { - let DocPayload::Bik(bik) = &self.document(doc)?.payload else { - return None; - }; - let mut preview = bik.preview.lock().unwrap_or_else(PoisonError::into_inner); - preview.prepare(&bik.bytes); - Some(preview) - } - - /// Gives the speaker what `doc`'s preview owes it: the movie's sound started where the picture - /// stands, or stopped. - pub fn sound_the_movie(&mut self, doc: DocumentId) { - let owed = self - .video_preview(doc) - .map(|mut preview| (preview.take_cue(), preview.position)); - match owed { - Some((Some(SoundCue::Play(sound)), position)) => { - if let Err(why) = self.audio.play_movie(doc, &sound, position) { - if let Some(mut preview) = self.video_preview(doc) { - preview.set_sound_problem(why); - } - } - } - Some((Some(SoundCue::Stop), _)) => self.audio.stop_movie(doc), - _ => {} - } + /// Locks this movie's preview, starting decode on first use. + pub(crate) fn lock_prepared(&self) -> MutexGuard<'_, Preview> { + let mut preview = self.preview.lock().unwrap_or_else(PoisonError::into_inner); + preview.prepare(&self.bytes); + preview } }