Build production-ready editor authoring workflows
CI / Format, lint, test, build (push) Waiting to run

This commit is contained in:
Rbanh committed 2026-07-11 12:41:04 -04:00
1 parent cc1fa6ea3b
commit 0553a85220
163 files changed
+34547 -1565

No files matched your search

@@ -0,0 +1,278 @@
//! Privacy-bounded support bundle export for editor troubleshooting.
use std::path::PathBuf;
use std::time::{SystemTime, UNIX_EPOCH};
use bevy::prelude::*;
use bevy::render::renderer::RenderAdapterInfo;
use serde::{Deserialize, Serialize};
use shared::{brush_math::validate_brush, BrushDesc, LevelObject};
use crate::project_io::ProjectWorkspace;
use crate::scene::recovery::{atomic_write, default_state_root};
use crate::scene_io::{SceneIo, SceneIoEventSeverity};
use crate::session::EditorSessionRuntime;
const DIAGNOSTICS_SCHEMA_VERSION: u32 = 1;
const DIAGNOSTICS_DIR: &str = "diagnostics";
const MAX_EVENT_MESSAGE_CHARS: usize = 512;
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct DiagnosticBuildInfo {
pub editor_version: String,
pub bevy_version: String,
pub target_os: String,
pub target_arch: String,
pub build_profile: String,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct DiagnosticRendererInfo {
pub adapter_name: String,
pub device_type: String,
pub backend: String,
pub driver: String,
pub driver_info: String,
pub vendor_id: u32,
pub device_id: u32,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct DiagnosticProjectInfo {
pub project_root: String,
pub settings_path: String,
pub active_scene: Option<String>,
pub scene_dirty: bool,
pub project_settings_dirty: bool,
pub layout_dirty: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct DiagnosticValidationSummary {
pub level_object_count: usize,
pub brush_actor_count: usize,
pub invalid_brush_count: usize,
pub brush_error_count: usize,
pub brush_warning_count: usize,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct DiagnosticSceneIoEvent {
pub id: u64,
pub severity: String,
pub message: String,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct DiagnosticBundleDocument {
pub schema_version: u32,
pub created_unix_seconds: u64,
pub build: DiagnosticBuildInfo,
pub renderer: Option<DiagnosticRendererInfo>,
pub project: DiagnosticProjectInfo,
pub validation: DiagnosticValidationSummary,
pub prior_abnormal_shutdown: bool,
pub scene_io_events: Vec<DiagnosticSceneIoEvent>,
}
/// Writes an allowlisted support report without scene data, environment values, or credentials.
pub fn export_diagnostic_bundle(world: &mut World) -> Result<PathBuf, String> {
let document = capture_diagnostic_bundle(world);
let directory = default_state_root()
.ok_or_else(|| "XDG_STATE_HOME and HOME are both unavailable".to_string())?
.join(DIAGNOSTICS_DIR);
let timestamp = document.created_unix_seconds;
let path = directory.join(format!(
"blacksite-diagnostics-{timestamp:020}-{}.ron",
std::process::id()
));
let text = serialize_diagnostic_bundle(&document)?;
atomic_write(&path, text.as_bytes())?;
Ok(path)
}
fn capture_diagnostic_bundle(world: &mut World) -> DiagnosticBundleDocument {
let validation = validation_summary(world);
let renderer =
world
.get_resource::<RenderAdapterInfo>()
.map(|adapter| DiagnosticRendererInfo {
adapter_name: adapter.name.clone(),
device_type: format!("{:?}", adapter.device_type),
backend: format!("{:?}", adapter.backend),
driver: adapter.driver.clone(),
driver_info: adapter.driver_info.clone(),
vendor_id: adapter.vendor,
device_id: adapter.device,
});
let scene_io = world.resource::<SceneIo>();
let workspace = world.resource::<ProjectWorkspace>();
let project = DiagnosticProjectInfo {
project_root: workspace.root.clone(),
settings_path: workspace.settings_path.clone(),
active_scene: scene_io
.active_path
.as_ref()
.map(|path| path.display().to_string()),
scene_dirty: scene_io.has_unsaved_tabs(),
project_settings_dirty: workspace.settings_dirty,
layout_dirty: workspace.layout_dirty,
};
let scene_io_events = scene_io
.events
.iter()
.map(|event| DiagnosticSceneIoEvent {
id: event.id,
severity: match event.severity {
SceneIoEventSeverity::Info => "info",
SceneIoEventSeverity::Error => "error",
}
.to_string(),
message: bounded_message(&event.message),
})
.collect();
DiagnosticBundleDocument {
schema_version: DIAGNOSTICS_SCHEMA_VERSION,
created_unix_seconds: SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs(),
build: build_info(),
renderer,
project,
validation,
prior_abnormal_shutdown: world
.get_resource::<EditorSessionRuntime>()
.is_some_and(|runtime| runtime.prior_abnormal_shutdown),
scene_io_events,
}
}
fn validation_summary(world: &mut World) -> DiagnosticValidationSummary {
let mut level_query = world.query_filtered::<Entity, With<LevelObject>>();
let level_object_count = level_query.iter(world).count();
let mut brush_query = world.query_filtered::<&BrushDesc, With<LevelObject>>();
let mut summary = DiagnosticValidationSummary {
level_object_count,
brush_actor_count: 0,
invalid_brush_count: 0,
brush_error_count: 0,
brush_warning_count: 0,
};
for brush in brush_query.iter(world) {
summary.brush_actor_count += 1;
let report = validate_brush(brush);
let errors = report
.diagnostics
.iter()
.filter(|diagnostic| {
diagnostic.severity == shared::brush_math::BrushDiagnosticSeverity::Error
})
.count();
let warnings = report.diagnostics.len().saturating_sub(errors);
summary.brush_error_count += errors;
summary.brush_warning_count += warnings;
summary.invalid_brush_count += usize::from(errors > 0);
}
summary
}
fn build_info() -> DiagnosticBuildInfo {
DiagnosticBuildInfo {
editor_version: env!("CARGO_PKG_VERSION").to_string(),
bevy_version: "0.19".to_string(),
target_os: std::env::consts::OS.to_string(),
target_arch: std::env::consts::ARCH.to_string(),
build_profile: if cfg!(debug_assertions) {
"debug"
} else {
"release"
}
.to_string(),
}
}
fn bounded_message(message: &str) -> String {
message
.chars()
.filter(|character| !character.is_control() || *character == ' ')
.take(MAX_EVENT_MESSAGE_CHARS)
.collect()
}
fn serialize_diagnostic_bundle(document: &DiagnosticBundleDocument) -> Result<String, String> {
ron::ser::to_string_pretty(document, ron::ser::PrettyConfig::default())
.map_err(|error| format!("could not serialize diagnostics: {error}"))
}
#[cfg(test)]
mod tests {
use super::*;
fn fixture() -> DiagnosticBundleDocument {
DiagnosticBundleDocument {
schema_version: DIAGNOSTICS_SCHEMA_VERSION,
created_unix_seconds: 42,
build: build_info(),
renderer: None,
project: DiagnosticProjectInfo {
project_root: "/project".to_string(),
settings_path: "assets/project.ron".to_string(),
active_scene: Some("assets/levels/test.scn.ron".to_string()),
scene_dirty: true,
project_settings_dirty: false,
layout_dirty: false,
},
validation: DiagnosticValidationSummary {
level_object_count: 12,
brush_actor_count: 2,
invalid_brush_count: 1,
brush_error_count: 1,
brush_warning_count: 0,
},
prior_abnormal_shutdown: true,
scene_io_events: vec![DiagnosticSceneIoEvent {
id: 1,
severity: "error".to_string(),
message: "Save failed: disk full".to_string(),
}],
}
}
#[test]
fn serialized_bundle_contains_only_allowlisted_sections() {
let text = serialize_diagnostic_bundle(&fixture()).unwrap();
for allowed in [
"build",
"renderer",
"project",
"validation",
"scene_io_events",
] {
assert!(text.contains(allowed));
}
for forbidden in [
"scene_contents",
"asset_contents",
"environment",
"credential",
"access_token",
"hostname",
"username",
"modal_operator",
] {
assert!(!text.to_ascii_lowercase().contains(forbidden));
}
}
#[test]
fn event_messages_are_control_free_and_bounded() {
let message = format!("failure\n{}", "x".repeat(MAX_EVENT_MESSAGE_CHARS + 20));
let bounded = bounded_message(&message);
assert!(bounded.chars().count() <= MAX_EVENT_MESSAGE_CHARS);
assert!(!bounded.contains('\n'));
}
}
+847
View File
@@ -0,0 +1,847 @@
//! Pre-engine project validation, recent-project discovery, and sandbox scaffolding.
use std::collections::HashSet;
use std::path::{Component, Path, PathBuf};
use std::process::Command;
use bevy::app::AppExit;
use bevy::prelude::*;
use bevy::window::{CompositeAlphaMode, PresentMode, WindowPlugin};
use bevy_egui::{egui, EguiContext, EguiPlugin, EguiPrimaryContextPass, PrimaryEguiContext};
use settings::{
save_project_settings_to_string, ProjectKind, ProjectSettings, DEFAULT_PROJECT_PATH,
PROJECT_TEMPLATE_VERSION,
};
use crate::project_io::UserPreferences;
use crate::scene::recovery::atomic_write;
use crate::ui::theme::{
apply_editor_theme, ACCENT, BORDER, CANVAS_BG, PANEL_BG, PANEL_BG_DARK, SELECTION, TEXT,
TEXT_DIM, TEXT_MUTED,
};
const SANDBOX_DIRECTORIES: &[&str] = &[
"assets/.index",
"assets/.trash",
"assets/audio",
"assets/build_profiles",
"assets/levels",
"assets/materials",
"assets/meshes/generated",
"assets/models",
"assets/post_fx",
"assets/rendering_profiles",
"assets/shaders",
"assets/textures",
];
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProjectSummary {
pub root: PathBuf,
pub project_id: String,
pub name: String,
pub project_kind: ProjectKind,
pub template_version: u32,
pub capabilities: Vec<String>,
pub default_level: PathBuf,
pub last_scene: Option<PathBuf>,
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct StartupArguments {
pub project: Option<PathBuf>,
pub help: bool,
}
#[derive(Resource)]
struct ProjectLauncherUi {
recents: Vec<ProjectSummary>,
sandbox_name: String,
sandbox_destination: Option<PathBuf>,
status: Option<String>,
}
impl Default for ProjectLauncherUi {
fn default() -> Self {
let mut preferences = crate::project_io::read_user_preferences();
if let Ok(root) = std::env::current_dir().and_then(|root| root.canonicalize()) {
crate::project_io::remember_project_root(&mut preferences, &root);
}
Self {
recents: recent_project_summaries(&preferences),
sandbox_name: "New Sandbox".to_string(),
sandbox_destination: None,
status: None,
}
}
}
pub fn run_project_launcher() {
let mut app = App::new();
app.add_plugins(DefaultPlugins.set(WindowPlugin {
primary_window: Some(Window {
title: "Blacksite Project Browser".to_string(),
name: Some("blacksite-project-launcher".to_string()),
resolution: (960, 620).into(),
present_mode: PresentMode::AutoVsync,
transparent: false,
composite_alpha_mode: CompositeAlphaMode::Opaque,
..default()
}),
..default()
}))
.add_plugins(EguiPlugin::default())
.init_resource::<ProjectLauncherUi>()
.add_systems(Startup, spawn_project_launcher_camera)
.add_systems(EguiPrimaryContextPass, project_launcher_ui_system);
app.run();
}
fn spawn_project_launcher_camera(mut commands: Commands) {
commands.spawn((Camera2d, PrimaryEguiContext));
}
pub fn spawn_project_launcher_process() -> Result<(), String> {
let executable = sibling_executable("project_launcher")?;
let root = std::env::current_dir()
.map_err(|error| format!("could not resolve active project root: {error}"))?;
spawn_detached(&executable, &[], &root)
}
pub fn reveal_project_root(root: &Path) -> Result<(), String> {
Command::new("xdg-open")
.arg(root)
.spawn()
.map_err(|error| format!("could not reveal {}: {error}", root.display()))?;
Ok(())
}
fn project_launcher_ui_system(world: &mut World) {
let Ok(context) = world
.query_filtered::<&mut EguiContext, With<PrimaryEguiContext>>()
.single(world)
else {
return;
};
let mut context = context.clone();
world.resource_scope(|world, mut state: Mut<ProjectLauncherUi>| {
project_launcher_ui(world, context.get_mut(), &mut state);
});
}
#[expect(
deprecated,
reason = "bevy_egui exposes a Context during EguiPrimaryContextPass, requiring one top-level context-based panel"
)]
fn project_launcher_ui(world: &mut World, context: &egui::Context, state: &mut ProjectLauncherUi) {
apply_editor_theme(context);
egui::CentralPanel::default()
.frame(
egui::Frame::new()
.fill(CANVAS_BG)
.inner_margin(egui::Margin::same(24)),
)
.show(context, |ui| {
let content_width = ui.available_width().min(1240.0);
let side_space = ((ui.available_width() - content_width) * 0.5).max(0.0);
ui.horizontal(|ui| {
ui.add_space(side_space);
ui.vertical(|ui| {
ui.set_width(content_width);
ui.horizontal(|ui| {
ui.vertical(|ui| {
ui.label(
egui::RichText::new("BLACKSITE")
.size(22.0)
.strong()
.color(ACCENT),
);
ui.label(
egui::RichText::new("PROJECT BROWSER")
.size(11.0)
.color(TEXT_DIM),
);
});
ui.add_space(18.0);
ui.separator();
ui.add_space(10.0);
ui.label(
egui::RichText::new(
"Choose a validated workspace before the engine starts",
)
.color(TEXT_DIM),
);
});
ui.add_space(22.0);
ui.horizontal(|ui| {
ui.vertical(|ui| {
ui.set_width(340.0);
launcher_actions(world, ui, state);
});
ui.add_space(18.0);
ui.vertical(|ui| {
ui.set_width((content_width - 358.0).max(360.0));
recent_projects(world, ui, state);
});
});
if let Some(status) = state.status.as_deref() {
ui.add_space(12.0);
ui.separator();
ui.label(egui::RichText::new(status).color(TEXT_DIM));
}
});
});
});
}
fn launcher_actions(world: &mut World, ui: &mut egui::Ui, state: &mut ProjectLauncherUi) {
egui::Frame::new()
.fill(PANEL_BG_DARK)
.stroke(egui::Stroke::new(1.0, BORDER))
.inner_margin(egui::Margin::same(16))
.show(ui, |ui| {
ui.set_min_height(455.0);
ui.heading("Open Project");
ui.label(
egui::RichText::new("Select a root containing assets/project.ron").color(TEXT_DIM),
);
ui.add_space(8.0);
if ui.button("Browse Existing...").clicked() {
if let Some(root) = rfd::FileDialog::new().pick_folder() {
open_project_from_launcher(world, state, root);
}
}
ui.add_space(24.0);
ui.separator();
ui.add_space(14.0);
ui.heading("New Sandbox");
ui.label(
egui::RichText::new("Creates a clean content workspace with a valid empty level")
.color(TEXT_DIM),
);
ui.add_space(8.0);
ui.label(egui::RichText::new("Project name").color(TEXT_DIM));
ui.text_edit_singleline(&mut state.sandbox_name);
ui.add_space(6.0);
let destination = state
.sandbox_destination
.as_ref()
.map(|path| path.display().to_string())
.unwrap_or_else(|| "No destination selected".to_string());
ui.add(
egui::Label::new(
egui::RichText::new(destination)
.monospace()
.color(TEXT_MUTED),
)
.truncate(),
);
if ui.button("Choose Empty Folder...").clicked() {
state.sandbox_destination = rfd::FileDialog::new().pick_folder();
}
let can_create =
state.sandbox_destination.is_some() && !state.sandbox_name.trim().is_empty();
if ui
.add_enabled(can_create, egui::Button::new("Create And Open Sandbox"))
.clicked()
{
let destination = state.sandbox_destination.clone().unwrap();
match scaffold_sandbox_project(&destination, &state.sandbox_name) {
Ok(summary) => launch_editor_and_close(world, state, &summary),
Err(error) => state.status = Some(error),
}
}
});
}
fn recent_projects(world: &mut World, ui: &mut egui::Ui, state: &mut ProjectLauncherUi) {
ui.horizontal(|ui| {
ui.heading("Recent Projects");
ui.add_space(8.0);
ui.label(egui::RichText::new(state.recents.len().to_string()).color(TEXT_MUTED));
});
ui.label(
egui::RichText::new("Missing and invalid projects are filtered automatically")
.color(TEXT_DIM),
);
ui.add_space(10.0);
if state.recents.is_empty() {
egui::Frame::new()
.fill(PANEL_BG)
.stroke(egui::Stroke::new(1.0, BORDER))
.inner_margin(egui::Margin::same(16))
.show(ui, |ui| {
ui.label(egui::RichText::new("No valid recent projects").color(TEXT));
ui.label(
egui::RichText::new("Browse an existing project or create a sandbox.")
.color(TEXT_DIM),
);
});
return;
}
let recents = state.recents.clone();
egui::ScrollArea::vertical()
.id_salt("project_launcher_recents")
.show(ui, |ui| {
for summary in recents {
let response = egui::Frame::new()
.fill(PANEL_BG)
.stroke(egui::Stroke::new(1.0, BORDER))
.inner_margin(egui::Margin::same(14))
.show(ui, |ui| {
ui.horizontal(|ui| {
ui.vertical(|ui| {
ui.label(egui::RichText::new(&summary.name).strong().color(TEXT));
ui.label(
egui::RichText::new(summary.root.display().to_string())
.monospace()
.size(11.0)
.color(TEXT_MUTED),
);
let detail = summary.last_scene.as_ref().map_or_else(
|| format!("{:?} | default scene", summary.project_kind),
|scene| {
format!(
"{:?} | {}",
summary.project_kind,
scene
.strip_prefix(&summary.root)
.unwrap_or(scene)
.display()
)
},
);
ui.label(egui::RichText::new(detail).size(11.0).color(TEXT_DIM));
});
ui.with_layout(
egui::Layout::right_to_left(egui::Align::Center),
|ui| {
if ui.button("Open").clicked() {
launch_editor_and_close(world, state, &summary);
}
},
);
});
});
if response.response.hovered() {
ui.painter().rect_stroke(
response.response.rect,
0.0,
egui::Stroke::new(1.0, SELECTION),
egui::StrokeKind::Inside,
);
}
ui.add_space(8.0);
}
});
}
fn open_project_from_launcher(world: &mut World, state: &mut ProjectLauncherUi, root: PathBuf) {
match inspect_project(&root, None) {
Ok(summary) => launch_editor_and_close(world, state, &summary),
Err(error) => state.status = Some(error),
}
}
fn launch_editor_and_close(
world: &mut World,
state: &mut ProjectLauncherUi,
summary: &ProjectSummary,
) {
match spawn_editor_process(&summary.root) {
Ok(()) => {
state.status = Some(format!("Opening {}", summary.name));
world.write_message(AppExit::Success);
}
Err(error) => state.status = Some(error),
}
}
fn spawn_editor_process(root: &Path) -> Result<(), String> {
let executable = sibling_executable("editor")?;
spawn_detached(
&executable,
&[std::ffi::OsStr::new("--project"), root.as_os_str()],
root,
)
}
#[cfg(target_os = "linux")]
fn spawn_detached(
executable: &Path,
arguments: &[&std::ffi::OsStr],
cwd: &Path,
) -> Result<(), String> {
let mut command = Command::new("systemd-run");
command
.args(["--user", "--collect", "--quiet", "--service-type=exec"])
.arg(format!("--working-directory={}", cwd.display()));
for variable in [
"PATH",
"WAYLAND_DISPLAY",
"DISPLAY",
"XAUTHORITY",
"XDG_RUNTIME_DIR",
"HYPRLAND_INSTANCE_SIGNATURE",
"DBUS_SESSION_BUS_ADDRESS",
"XDG_CURRENT_DESKTOP",
"XDG_SESSION_DESKTOP",
"XDG_SESSION_TYPE",
"XDG_DATA_HOME",
"XDG_CONFIG_HOME",
"XDG_STATE_HOME",
"GDK_BACKEND",
"LD_LIBRARY_PATH",
"WGPU_VALIDATION",
"BEVY_FPS_HDR",
] {
if let Some(value) = std::env::var_os(variable) {
command.arg(format!("--setenv={variable}={}", value.to_string_lossy()));
}
}
let status = command
.arg(executable)
.args(arguments)
.status()
.map_err(|error| format!("could not invoke systemd-run: {error}"))?;
status.success().then_some(()).ok_or_else(|| {
format!(
"systemd-run could not start {} (status {status})",
executable.display()
)
})
}
#[cfg(not(target_os = "linux"))]
fn spawn_detached(
executable: &Path,
arguments: &[&std::ffi::OsStr],
cwd: &Path,
) -> Result<(), String> {
Command::new(executable)
.args(arguments)
.current_dir(cwd)
.spawn()
.map_err(|error| format!("could not start {}: {error}", executable.display()))?;
Ok(())
}
fn sibling_executable(name: &str) -> Result<PathBuf, String> {
let current = std::env::current_exe()
.map_err(|error| format!("could not locate current executable: {error}"))?;
let extension = current
.extension()
.map(|extension| extension.to_os_string());
let mut executable = current.with_file_name(name);
if let Some(extension) = extension {
executable.set_extension(extension);
}
executable
.is_file()
.then_some(executable.clone())
.ok_or_else(|| format!("required executable is not built: {}", executable.display()))
}
pub fn parse_startup_arguments(
arguments: impl IntoIterator<Item = String>,
) -> Result<StartupArguments, String> {
let mut parsed = StartupArguments::default();
let mut arguments = arguments.into_iter();
while let Some(argument) = arguments.next() {
match argument.as_str() {
"--project" => {
if parsed.project.is_some() {
return Err("--project may only be provided once".to_string());
}
let path = arguments
.next()
.ok_or_else(|| "--project requires a project root path".to_string())?;
parsed.project = Some(PathBuf::from(path));
}
"--help" | "-h" => parsed.help = true,
unknown => return Err(format!("unknown editor argument `{unknown}`")),
}
}
Ok(parsed)
}
pub fn command_line_help() -> &'static str {
"Blacksite Editor\n\nUSAGE:\n editor [--project <root>]\n\nOPTIONS:\n --project <root> Open a validated Blacksite project before engine startup\n -h, --help Print this help"
}
pub fn activate_project_root(root: &Path) -> Result<ProjectSummary, String> {
let summary = inspect_project(root, None)?;
std::env::set_current_dir(&summary.root).map_err(|error| {
format!(
"could not activate project root {}: {error}",
summary.root.display()
)
})?;
Ok(summary)
}
pub fn inspect_project(root: &Path, last_scene: Option<&Path>) -> Result<ProjectSummary, String> {
let root = root
.canonicalize()
.map_err(|error| format!("could not open project root {}: {error}", root.display()))?;
if !root.is_dir() {
return Err(format!(
"project root is not a directory: {}",
root.display()
));
}
let manifest_path = root.join(DEFAULT_PROJECT_PATH);
let text = std::fs::read_to_string(&manifest_path)
.map_err(|error| format!("could not read {}: {error}", manifest_path.display()))?;
let manifest: ProjectSettings = ron::from_str(&text).map_err(|error| {
format!(
"invalid project manifest {}: {error}",
manifest_path.display()
)
})?;
if manifest.name.trim().is_empty() {
return Err(format!(
"project name is empty in {}",
manifest_path.display()
));
}
manifest.audio.validate().map_err(|error| {
format!(
"invalid audio settings in {}: {error}",
manifest_path.display()
)
})?;
let default_reference = Path::new(&manifest.default_level);
if !default_reference.starts_with("assets/levels")
|| !manifest.default_level.ends_with(".scn.ron")
{
return Err("default_level must be a .scn.ron scene under assets/levels/".into());
}
let default_level = safe_project_path(&root, default_reference, "default_level")?;
let default_metadata = std::fs::symlink_metadata(&default_level).ok();
if !default_metadata
.as_ref()
.is_some_and(std::fs::Metadata::is_file)
|| default_metadata.is_some_and(|metadata| metadata.file_type().is_symlink())
{
return Err(format!(
"default level is missing or is not a regular file: {}",
default_level.display()
));
}
let default_level_text = std::fs::read_to_string(&default_level).map_err(|error| {
format!(
"could not read default level {}: {error}",
default_level.display()
)
})?;
scene::validate_level_text(&default_level_text).map_err(|error| {
format!(
"default level failed validation {}: {error}",
default_level.display()
)
})?;
scene::validate_composition_graph(&default_level, &root).map_err(|error| {
format!(
"default level composition failed validation {}: {error}",
default_level.display()
)
})?;
let last_scene = last_scene
.and_then(|path| safe_project_path(&root, path, "last_scene").ok())
.filter(|path| path.is_file());
let project_id = if manifest.project_id.trim().is_empty() {
format!("legacy:{}", root.display())
} else {
manifest.project_id
};
Ok(ProjectSummary {
root,
project_id,
name: manifest.name,
project_kind: manifest.project_kind,
template_version: manifest.template_version,
capabilities: manifest.capabilities,
default_level,
last_scene,
})
}
pub fn recent_project_summaries(preferences: &UserPreferences) -> Vec<ProjectSummary> {
let mut seen = HashSet::new();
preferences
.recent_projects
.iter()
.filter_map(|root| {
let root = PathBuf::from(root);
let last_scene = preferences
.recent_levels
.iter()
.map(PathBuf::from)
.find(|scene| root.join(scene).is_file());
inspect_project(&root, last_scene.as_deref()).ok()
})
.filter(|summary| seen.insert(summary.root.clone()))
.collect()
}
pub fn scaffold_sandbox_project(destination: &Path, name: &str) -> Result<ProjectSummary, String> {
let name = name.trim();
if name.is_empty() {
return Err("sandbox project name cannot be empty".to_string());
}
if destination.exists() {
let mut entries = std::fs::read_dir(destination)
.map_err(|error| format!("could not inspect {}: {error}", destination.display()))?;
if entries.next().is_some() {
return Err(format!(
"sandbox destination must be empty: {}",
destination.display()
));
}
}
for directory in SANDBOX_DIRECTORIES {
std::fs::create_dir_all(destination.join(directory)).map_err(|error| {
format!(
"could not create sandbox directory {}: {error}",
destination.join(directory).display()
)
})?;
}
let default_level = "assets/levels/main.scn.ron";
let empty_scene = format!(
"(schema_version: {},\n resources: {{}},\n entities: {{}},\n)\n",
scene::CURRENT_SCENE_SCHEMA_VERSION
);
scene::validate_level_text(&empty_scene)?;
atomic_write(&destination.join(default_level), empty_scene.as_bytes())?;
let manifest = ProjectSettings {
project_id: uuid::Uuid::new_v4().to_string(),
name: name.to_string(),
project_kind: ProjectKind::Sandbox,
template_version: PROJECT_TEMPLATE_VERSION,
capabilities: vec![
"editor".into(),
"gameplay".into(),
"rendering".into(),
"audio".into(),
],
default_level: default_level.to_string(),
asset_roots: vec![
"assets/audio".into(),
"assets/levels".into(),
"assets/materials".into(),
"assets/meshes".into(),
"assets/models".into(),
"assets/textures".into(),
],
..ProjectSettings::default()
};
let manifest_text = save_project_settings_to_string(&manifest)
.map_err(|error| format!("could not serialize sandbox manifest: {error}"))?;
atomic_write(
&destination.join(DEFAULT_PROJECT_PATH),
manifest_text.as_bytes(),
)?;
for (name, profile) in sandbox_build_profiles(default_level) {
atomic_write(
&destination.join("assets/build_profiles").join(name),
profile.as_bytes(),
)?;
}
inspect_project(destination, None)
}
fn sandbox_build_profiles(default_level: &str) -> [(&'static str, String); 3] {
[
(
"development.ron",
format!(
"(version:1,name:\"Development\",cargo_profile:Development,target:None,features:[],rendering_tier:\"development\",default_scene:Some(\"{default_level}\"),output_dir:\"dist/development\")\n"
),
),
(
"qa.ron",
format!(
"(version:1,name:\"QA\",cargo_profile:Qa,target:None,features:[],rendering_tier:\"representative\",default_scene:Some(\"{default_level}\"),output_dir:\"dist/qa\")\n"
),
),
(
"release.ron",
format!(
"(version:1,name:\"Release\",cargo_profile:Release,target:None,features:[],rendering_tier:\"shipping\",default_scene:Some(\"{default_level}\"),output_dir:\"dist/release\")\n"
),
),
]
}
fn safe_project_path(root: &Path, path: impl AsRef<Path>, field: &str) -> Result<PathBuf, String> {
let path = path.as_ref();
if path.as_os_str().is_empty() || path.is_absolute() {
return Err(format!("{field} must be a non-empty project-relative path"));
}
if path.components().any(|component| {
matches!(
component,
Component::ParentDir | Component::RootDir | Component::Prefix(_)
)
}) {
return Err(format!("{field} cannot escape the project root"));
}
Ok(root.join(path))
}
#[cfg(test)]
mod tests {
use super::*;
fn temp_root(label: &str) -> PathBuf {
std::env::temp_dir().join(format!("blacksite-{label}-{}", uuid::Uuid::new_v4()))
}
#[test]
fn startup_arguments_parse_project_and_reject_unknown_flags() {
let parsed =
parse_startup_arguments(["--project".to_string(), "/tmp/project".to_string()]).unwrap();
assert_eq!(parsed.project, Some(PathBuf::from("/tmp/project")));
assert!(parse_startup_arguments(["--mystery".to_string()]).is_err());
assert!(parse_startup_arguments(["--project".to_string()]).is_err());
}
#[test]
fn sandbox_scaffold_can_be_inspected_and_reloaded() {
let root = temp_root("sandbox");
let created = scaffold_sandbox_project(&root, "Prototype").unwrap();
let reopened =
inspect_project(&root, Some(Path::new("assets/levels/main.scn.ron"))).unwrap();
assert_eq!(created.project_id, reopened.project_id);
assert_eq!(reopened.name, "Prototype");
assert_eq!(reopened.project_kind, ProjectKind::Sandbox);
assert_eq!(reopened.template_version, PROJECT_TEMPLATE_VERSION);
assert!(reopened.capabilities.iter().any(|item| item == "audio"));
let manifest = settings::load_project_settings_from_path(
root.join(DEFAULT_PROJECT_PATH).to_string_lossy().as_ref(),
);
assert!(manifest.audio.validate().is_ok());
assert!(manifest.audio.bus(settings::AUDIO_BUS_SFX_ID).is_some());
assert_eq!(
reopened.last_scene,
Some(root.join("assets/levels/main.scn.ron"))
);
for directory in SANDBOX_DIRECTORIES {
assert!(root.join(directory).is_dir(), "missing {directory}");
}
for profile in ["development.ron", "qa.ron", "release.ron"] {
let text =
std::fs::read_to_string(root.join("assets/build_profiles").join(profile)).unwrap();
assert!(text.contains("assets/levels/main.scn.ron"), "{profile}");
assert!(text.contains("output_dir"), "{profile}");
}
std::fs::remove_dir_all(root).unwrap();
}
#[test]
fn recent_projects_filter_missing_invalid_and_duplicate_roots() {
let valid = temp_root("recent-valid");
let invalid = temp_root("recent-invalid");
scaffold_sandbox_project(&valid, "Valid").unwrap();
std::fs::create_dir_all(&invalid).unwrap();
let preferences = UserPreferences {
recent_projects: vec![
valid.display().to_string(),
"/definitely/missing/blacksite-project".to_string(),
invalid.display().to_string(),
valid.display().to_string(),
],
recent_levels: vec!["assets/levels/main.scn.ron".to_string()],
..Default::default()
};
let summaries = recent_project_summaries(&preferences);
assert_eq!(summaries.len(), 1);
assert_eq!(summaries[0].name, "Valid");
assert!(summaries[0].last_scene.is_some());
std::fs::remove_dir_all(valid).unwrap();
std::fs::remove_dir_all(invalid).unwrap();
}
#[test]
fn project_inspection_rejects_invalid_audio_bus_graphs() {
let root = temp_root("invalid-audio-buses");
scaffold_sandbox_project(&root, "Invalid Audio").unwrap();
let manifest_path = root.join(DEFAULT_PROJECT_PATH);
let mut manifest =
settings::load_project_settings_from_path(manifest_path.to_string_lossy().as_ref());
manifest
.audio
.bus_mut(settings::AUDIO_BUS_SFX_ID)
.unwrap()
.parent = Some("missing".into());
std::fs::write(
&manifest_path,
save_project_settings_to_string(&manifest).unwrap(),
)
.unwrap();
let error = inspect_project(&root, None).unwrap_err();
assert!(error.contains("invalid audio settings"), "{error}");
std::fs::remove_dir_all(root).unwrap();
}
#[test]
fn sandbox_scaffold_refuses_nonempty_destination_and_path_escape() {
let root = temp_root("sandbox-nonempty");
std::fs::create_dir_all(&root).unwrap();
std::fs::write(root.join("keep.txt"), "user data").unwrap();
assert!(scaffold_sandbox_project(&root, "Unsafe").is_err());
assert!(safe_project_path(&root, "../outside", "test").is_err());
assert_eq!(
std::fs::read_to_string(root.join("keep.txt")).unwrap(),
"user data"
);
std::fs::remove_dir_all(root).unwrap();
}
#[test]
fn project_default_level_must_use_the_audited_levels_tree() {
let root = temp_root("default-level-contract");
scaffold_sandbox_project(&root, "Contract").unwrap();
std::fs::create_dir_all(root.join("assets/custom")).unwrap();
std::fs::write(
root.join("assets/custom/start.scn.ron"),
format!(
"(schema_version:{},resources:{{}},entities:{{}})",
scene::CURRENT_SCENE_SCHEMA_VERSION
),
)
.unwrap();
let mut manifest = settings::load_project_settings_from_path(
root.join(DEFAULT_PROJECT_PATH).to_string_lossy().as_ref(),
);
manifest.default_level = "assets/custom/start.scn.ron".into();
std::fs::write(
root.join(DEFAULT_PROJECT_PATH),
save_project_settings_to_string(&manifest).unwrap(),
)
.unwrap();
let error = inspect_project(&root, None).unwrap_err();
assert!(error.contains("assets/levels"), "{error}");
std::fs::remove_dir_all(root).unwrap();
}
}
+3
View File
@@ -1,4 +1,7 @@
//! Project workspace I/O, settings UI, and recent-level sync.
pub mod diagnostics_bundle;
pub mod launcher;
pub mod project_io;
pub mod session;
pub mod settings_ui;
+83 -6
View File
@@ -2,7 +2,7 @@
use bevy::prelude::*;
use serde::{Deserialize, Serialize};
use settings::{ProjectSettings, ProjectSettingsIo, DEFAULT_PROJECT_PATH};
use settings::{ProjectKind, ProjectSettings, ProjectSettingsIo, DEFAULT_PROJECT_PATH};
use crate::scene_io::SceneIo;
@@ -10,7 +10,7 @@ const USER_CONFIG_DIR: &str = ".config/bevy-fps";
const USER_PREFS_FILE: &str = "editor_prefs.ron";
/// User-local editor preferences (not checked into the repo).
#[derive(Debug, Clone, Default, Serialize, Deserialize, Resource)]
#[derive(Debug, Clone, Serialize, Deserialize, Resource)]
pub struct UserPreferences {
pub recent_projects: Vec<String>,
pub recent_levels: Vec<String>,
@@ -31,16 +31,53 @@ pub struct UserPreferences {
pub hierarchy_show_runtime: bool,
#[serde(default)]
pub hierarchy_sort_mode: crate::ui::hierarchy_state::HierarchySort,
#[serde(default = "default_true")]
pub scene_autosave_enabled: bool,
#[serde(default = "default_autosave_interval_secs")]
pub scene_autosave_interval_secs: u64,
#[serde(default = "default_recovery_generations")]
pub scene_recovery_generations: usize,
}
fn default_true() -> bool {
true
}
const fn default_autosave_interval_secs() -> u64 {
120
}
const fn default_recovery_generations() -> usize {
5
}
impl Default for UserPreferences {
fn default() -> Self {
Self {
recent_projects: Vec::new(),
recent_levels: Vec::new(),
last_project_root: None,
dock_layout: None,
save_before_play: false,
hierarchy_filter: String::new(),
hierarchy_expanded_paths: Vec::new(),
hierarchy_show_generated: true,
hierarchy_show_runtime: false,
hierarchy_sort_mode: crate::ui::hierarchy_state::HierarchySort::default(),
scene_autosave_enabled: true,
scene_autosave_interval_secs: default_autosave_interval_secs(),
scene_recovery_generations: default_recovery_generations(),
}
}
}
/// Active project workspace metadata (mirrors manifest fields in `ProjectSettings`).
#[derive(Resource, Debug, Clone)]
pub struct ProjectWorkspace {
pub root: String,
pub project_id: String,
pub project_kind: ProjectKind,
pub last_opened_scene: Option<String>,
pub settings_path: String,
pub settings_dirty: bool,
pub layout_dirty: bool,
@@ -54,6 +91,9 @@ impl Default for ProjectWorkspace {
.unwrap_or_else(|| ".".into());
Self {
root,
project_id: String::new(),
project_kind: ProjectKind::default(),
last_opened_scene: None,
settings_path: DEFAULT_PROJECT_PATH.into(),
settings_dirty: false,
layout_dirty: false,
@@ -73,7 +113,13 @@ impl Plugin for ProjectIoPlugin {
}
fn load_user_preferences(mut commands: Commands) {
let prefs = read_user_preferences();
let mut prefs = read_user_preferences();
if let Ok(root) = std::env::current_dir().and_then(|root| root.canonicalize()) {
remember_project_root(&mut prefs, &root);
if let Err(error) = write_user_preferences(&prefs) {
warn!("Failed to remember active project: {error}");
}
}
commands.insert_resource(prefs);
}
@@ -85,12 +131,13 @@ pub(crate) fn load_user_preferences_on_startup(commands: Commands) {
fn sync_workspace_from_settings_system(
settings: Res<ProjectSettings>,
settings_io: Res<ProjectSettingsIo>,
scene_io: Res<SceneIo>,
mut workspace: ResMut<ProjectWorkspace>,
) {
if !settings_io.is_changed() && !settings.is_changed() {
if !settings_io.is_changed() && !settings.is_changed() && !scene_io.is_changed() {
return;
}
sync_workspace_from_settings(&mut workspace, &settings, &settings_io);
sync_workspace_from_settings(&mut workspace, &settings, &settings_io, &scene_io);
}
fn user_prefs_path() -> Option<std::path::PathBuf> {
@@ -127,14 +174,26 @@ pub fn push_recent(list: &mut Vec<String>, entry: String, max: usize) {
list.truncate(max);
}
pub fn remember_project_root(preferences: &mut UserPreferences, root: &std::path::Path) {
let root = root.display().to_string();
push_recent(&mut preferences.recent_projects, root.clone(), 12);
preferences.last_project_root = Some(root);
}
pub fn sync_workspace_from_settings(
workspace: &mut ProjectWorkspace,
settings: &ProjectSettings,
settings_io: &ProjectSettingsIo,
scene_io: &SceneIo,
) {
workspace.project_id.clone_from(&settings.project_id);
workspace.project_kind = settings.project_kind;
workspace.last_opened_scene = scene_io
.active_path
.as_ref()
.map(|path| path.display().to_string());
workspace.settings_path = settings_io.path.clone();
workspace.settings_dirty = settings_io.dirty;
let _ = settings;
}
pub fn window_title(
@@ -160,3 +219,21 @@ pub fn window_title(
}
parts.join(" — ")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn remembering_project_deduplicates_and_updates_last_root() {
let mut preferences = UserPreferences {
recent_projects: vec!["/old".into(), "/project".into()],
..Default::default()
};
remember_project_root(&mut preferences, std::path::Path::new("/project"));
assert_eq!(preferences.last_project_root.as_deref(), Some("/project"));
assert_eq!(preferences.recent_projects, vec!["/project", "/old"]);
}
}
+419
View File
@@ -0,0 +1,419 @@
//! Versioned machine-local editor session persistence and crash boundary.
use std::path::{Path, PathBuf};
use bevy::app::AppExit;
use bevy::prelude::*;
use bevy_egui::egui;
use serde::{Deserialize, Serialize};
use crate::project_io::{ProjectWorkspace, UserPreferences};
use crate::scene::recovery::{atomic_write, default_state_root};
use crate::scene_io::{SceneIo, SceneIoRequest};
use crate::settings_ui::ProjectSettingsPanel;
use crate::ui::{BrushDiagnosticsPanel, DiagnosticsPanel};
use crate::viewport::rendering_diagnostics::RenderingDiagnosticsPanel;
use crate::viewport::CameraBookmarks;
const SESSION_FILE: &str = "session.ron";
const SESSION_SCHEMA_VERSION: u32 = 1;
const SESSION_WRITE_INTERVAL_SECS: f32 = 2.0;
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct SessionPanelState {
#[serde(default)]
pub diagnostics: bool,
#[serde(default)]
pub brush_diagnostics: bool,
#[serde(default)]
pub rendering: bool,
#[serde(default)]
pub project_settings: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct CameraBookmarkRecord {
pub scene: String,
pub translation: [f32; 3],
pub rotation: [f32; 4],
pub scale: [f32; 3],
}
impl CameraBookmarkRecord {
fn from_transform(scene: String, transform: Transform) -> Self {
Self {
scene,
translation: transform.translation.to_array(),
rotation: transform.rotation.to_array(),
scale: transform.scale.to_array(),
}
}
fn to_transform(&self) -> Transform {
Transform {
translation: Vec3::from_array(self.translation),
rotation: Quat::from_array(self.rotation).normalize(),
scale: Vec3::from_array(self.scale),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct EditorSessionDocument {
#[serde(default)]
pub schema_version: u32,
#[serde(default)]
pub clean_shutdown: bool,
#[serde(default)]
pub project_root: String,
#[serde(default)]
pub active_scene: Option<String>,
#[serde(default)]
pub dock_layout: Option<String>,
#[serde(default)]
pub hierarchy_expanded_paths: Vec<String>,
#[serde(default)]
pub panels: SessionPanelState,
#[serde(default)]
pub camera_bookmarks: Vec<CameraBookmarkRecord>,
}
impl Default for EditorSessionDocument {
fn default() -> Self {
Self {
schema_version: SESSION_SCHEMA_VERSION,
clean_shutdown: true,
project_root: String::new(),
active_scene: None,
dock_layout: None,
hierarchy_expanded_paths: Vec::new(),
panels: SessionPanelState::default(),
camera_bookmarks: Vec::new(),
}
}
}
#[derive(Resource, Debug, Default)]
pub struct EditorSessionRuntime {
pub prior_abnormal_shutdown: bool,
pub resume_scene: Option<PathBuf>,
pub resume_prompt_open: bool,
save_elapsed_secs: f32,
}
pub struct EditorSessionPlugin;
impl Plugin for EditorSessionPlugin {
fn build(&self, app: &mut App) {
app.init_resource::<EditorSessionRuntime>()
.add_systems(Startup, initialize_session)
.add_systems(Update, persist_running_session)
.add_systems(
Last,
persist_clean_session_on_exit.after(bevy::window::ExitSystems),
);
}
}
pub fn session_resume_window(world: &mut World, ctx: &egui::Context) {
let (open, scene) = {
let runtime = world.resource::<EditorSessionRuntime>();
(runtime.resume_prompt_open, runtime.resume_scene.clone())
};
if !open {
return;
}
let Some(scene) = scene else {
world
.resource_mut::<EditorSessionRuntime>()
.resume_prompt_open = false;
return;
};
egui::Window::new("Recover Editor Session")
.collapsible(false)
.resizable(false)
.anchor(egui::Align2::CENTER_CENTER, egui::Vec2::ZERO)
.show(ctx, |ui| {
ui.label("The previous editor session did not close cleanly.");
ui.small("The safe startup scene is active. Resume only the last authored scene; modal tools and dirty preview state are never restored.");
ui.monospace(scene.display().to_string());
ui.separator();
ui.horizontal(|ui| {
if ui.button("Resume Last Scene").clicked() {
world.resource_mut::<SceneIo>().request =
Some(SceneIoRequest::OpenPath(scene.clone()));
world
.resource_mut::<EditorSessionRuntime>()
.resume_prompt_open = false;
}
if ui.button("Continue Safe").clicked() {
world
.resource_mut::<EditorSessionRuntime>()
.resume_prompt_open = false;
world
.resource_mut::<SceneIo>()
.set_status("Continued with safe startup after abnormal shutdown");
}
});
});
}
fn session_path() -> Option<PathBuf> {
default_state_root().map(|root| root.join(SESSION_FILE))
}
fn read_session(path: &Path) -> Result<EditorSessionDocument, String> {
let text = std::fs::read_to_string(path)
.map_err(|error| format!("could not read {}: {error}", path.display()))?;
let document: EditorSessionDocument =
ron::from_str(&text).map_err(|error| format!("invalid session document: {error}"))?;
normalize_session(document)
}
fn normalize_session(mut document: EditorSessionDocument) -> Result<EditorSessionDocument, String> {
match document.schema_version {
0 => document.schema_version = SESSION_SCHEMA_VERSION,
SESSION_SCHEMA_VERSION => {}
version => {
return Err(format!(
"session schema {version} is newer than supported {SESSION_SCHEMA_VERSION}"
));
}
}
document.camera_bookmarks.retain(valid_bookmark);
Ok(document)
}
fn valid_bookmark(bookmark: &CameraBookmarkRecord) -> bool {
bookmark
.translation
.iter()
.chain(bookmark.rotation.iter())
.chain(bookmark.scale.iter())
.all(|value| value.is_finite())
}
fn write_session(path: &Path, document: &EditorSessionDocument) -> Result<(), String> {
let text = ron::ser::to_string_pretty(document, ron::ser::PrettyConfig::default())
.map_err(|error| format!("could not serialize session: {error}"))?;
atomic_write(path, text.as_bytes())
}
fn initialize_session(world: &mut World) {
let previous = session_path().and_then(|path| read_session(&path).ok());
let prior_abnormal = previous
.as_ref()
.is_some_and(|document| !document.clean_shutdown);
if let Some(document) = previous.as_ref() {
restore_non_destructive_session_state(world, document);
if !prior_abnormal {
restore_active_scene(world, document);
}
}
let resume_scene = previous
.as_ref()
.and_then(|document| document.active_scene.as_deref())
.map(PathBuf::from)
.filter(|path| path.exists());
world.insert_resource(EditorSessionRuntime {
prior_abnormal_shutdown: prior_abnormal,
resume_prompt_open: prior_abnormal && resume_scene.is_some(),
resume_scene,
save_elapsed_secs: 0.0,
});
if let Some(path) = session_path() {
let document = capture_session(world, false);
if let Err(error) = write_session(&path, &document) {
warn!("Failed to write running session marker: {error}");
}
}
}
fn restore_active_scene(world: &mut World, document: &EditorSessionDocument) {
let Some(path) = document.active_scene.as_deref().map(PathBuf::from) else {
return;
};
if path.exists() {
world.resource_mut::<SceneIo>().active_path = Some(path);
}
}
fn restore_non_destructive_session_state(world: &mut World, document: &EditorSessionDocument) {
let poses = document
.camera_bookmarks
.iter()
.map(|bookmark| (bookmark.scene.clone(), bookmark.to_transform()))
.collect();
world.resource_mut::<CameraBookmarks>().poses = poses;
world.resource_mut::<DiagnosticsPanel>().open = document.panels.diagnostics;
world.resource_mut::<BrushDiagnosticsPanel>().open = document.panels.brush_diagnostics;
world.resource_mut::<RenderingDiagnosticsPanel>().open = document.panels.rendering;
world.resource_mut::<ProjectSettingsPanel>().open = document.panels.project_settings;
}
fn capture_session(world: &World, clean_shutdown: bool) -> EditorSessionDocument {
let prefs = world.resource::<UserPreferences>();
EditorSessionDocument {
schema_version: SESSION_SCHEMA_VERSION,
clean_shutdown,
project_root: world.resource::<ProjectWorkspace>().root.clone(),
active_scene: world
.resource::<SceneIo>()
.active_path
.as_ref()
.map(|path| path.display().to_string()),
dock_layout: prefs.dock_layout.clone(),
hierarchy_expanded_paths: prefs.hierarchy_expanded_paths.clone(),
panels: SessionPanelState {
diagnostics: world.resource::<DiagnosticsPanel>().open,
brush_diagnostics: world.resource::<BrushDiagnosticsPanel>().open,
rendering: world.resource::<RenderingDiagnosticsPanel>().open,
project_settings: world.resource::<ProjectSettingsPanel>().open,
},
camera_bookmarks: world
.resource::<CameraBookmarks>()
.poses
.iter()
.map(|(scene, transform)| {
CameraBookmarkRecord::from_transform(scene.clone(), *transform)
})
.collect(),
}
}
fn persist_running_session(world: &mut World) {
let delta = world.resource::<Time>().delta_secs();
let should_write = {
let mut runtime = world.resource_mut::<EditorSessionRuntime>();
runtime.save_elapsed_secs += delta;
if runtime.save_elapsed_secs < SESSION_WRITE_INTERVAL_SECS {
false
} else {
runtime.save_elapsed_secs = 0.0;
true
}
};
if !should_write {
return;
}
let Some(path) = session_path() else {
return;
};
if let Err(error) = write_session(&path, &capture_session(world, false)) {
warn!("Failed to persist running editor session: {error}");
}
}
#[allow(clippy::too_many_arguments)]
fn persist_clean_session_on_exit(
mut exits: MessageReader<AppExit>,
scene_io: Res<SceneIo>,
workspace: Res<ProjectWorkspace>,
prefs: Res<UserPreferences>,
bookmarks: Res<CameraBookmarks>,
diagnostics: Res<DiagnosticsPanel>,
brush_diagnostics: Res<BrushDiagnosticsPanel>,
rendering: Res<RenderingDiagnosticsPanel>,
project_settings: Res<ProjectSettingsPanel>,
) {
if exits.read().next().is_none() {
return;
}
let Some(path) = session_path() else {
return;
};
let document = EditorSessionDocument {
schema_version: SESSION_SCHEMA_VERSION,
clean_shutdown: true,
project_root: workspace.root.clone(),
active_scene: scene_io
.active_path
.as_ref()
.map(|path| path.display().to_string()),
dock_layout: prefs.dock_layout.clone(),
hierarchy_expanded_paths: prefs.hierarchy_expanded_paths.clone(),
panels: SessionPanelState {
diagnostics: diagnostics.open,
brush_diagnostics: brush_diagnostics.open,
rendering: rendering.open,
project_settings: project_settings.open,
},
camera_bookmarks: bookmarks
.poses
.iter()
.map(|(scene, transform)| {
CameraBookmarkRecord::from_transform(scene.clone(), *transform)
})
.collect(),
};
if let Err(error) = write_session(&path, &document) {
warn!("Failed to persist clean editor shutdown: {error}");
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn legacy_unversioned_session_migrates_to_v1() {
let legacy = r#"(
clean_shutdown: true,
project_root: "/project",
active_scene: Some("assets/levels/test.scn.ron"),
)"#;
let document: EditorSessionDocument = ron::from_str(legacy).unwrap();
let migrated = normalize_session(document).unwrap();
assert_eq!(migrated.schema_version, SESSION_SCHEMA_VERSION);
assert_eq!(migrated.project_root, "/project");
}
#[test]
fn newer_session_schema_is_rejected() {
let document = EditorSessionDocument {
schema_version: SESSION_SCHEMA_VERSION + 1,
..default()
};
assert!(normalize_session(document)
.unwrap_err()
.contains("newer than supported"));
}
#[test]
fn invalid_camera_pose_is_removed_during_migration() {
let mut document = EditorSessionDocument::default();
document.camera_bookmarks.push(CameraBookmarkRecord {
scene: "scene".to_string(),
translation: [f32::NAN, 0.0, 0.0],
rotation: [0.0, 0.0, 0.0, 1.0],
scale: [1.0; 3],
});
assert!(normalize_session(document)
.unwrap()
.camera_bookmarks
.is_empty());
}
#[test]
fn serialized_session_contains_only_allowlisted_metadata() {
let document = EditorSessionDocument {
project_root: "/project".to_string(),
active_scene: Some("assets/levels/test.scn.ron".to_string()),
..default()
};
let text = ron::ser::to_string(&document).unwrap();
assert!(text.contains("active_scene"));
for forbidden in ["scene_contents", "credential", "token", "environment"] {
assert!(!text.to_ascii_lowercase().contains(forbidden));
}
}
}
+100 -2
View File
@@ -210,6 +210,97 @@ fn draw_project_settings_form(
);
});
ui.collapsing("Audio Buses", |ui| {
let bus_ids: Vec<String> = draft.audio.buses.iter().map(|bus| bus.id.clone()).collect();
let mut remove_bus = None;
for (index, bus) in draft.audio.buses.iter_mut().enumerate() {
egui::Frame::new()
.fill(egui::Color32::from_rgb(24, 26, 29))
.stroke(egui::Stroke::new(1.0, egui::Color32::from_rgb(53, 57, 63)))
.corner_radius(4.0)
.inner_margin(8.0)
.show(ui, |ui| {
ui.horizontal(|ui| {
ui.strong(&bus.label);
ui.small(
egui::RichText::new(format!("[{}]", bus.id))
.color(egui::Color32::from_rgb(139, 146, 156)),
);
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
let required = matches!(
bus.id.as_str(),
settings::AUDIO_BUS_MASTER_ID
| settings::AUDIO_BUS_MUSIC_ID
| settings::AUDIO_BUS_SFX_ID
);
if ui
.add_enabled(!required, egui::Button::new("Remove"))
.clicked()
{
remove_bus = Some(index);
}
});
});
ui.horizontal_wrapped(|ui| {
ui.label("Name");
ui.add_sized([140.0, 20.0], egui::TextEdit::singleline(&mut bus.label));
ui.checkbox(&mut bus.muted, "Mute");
});
ui.add(
egui::Slider::new(
&mut bus.gain_db,
settings::AUDIO_GAIN_DB_MIN..=settings::AUDIO_GAIN_DB_MAX,
)
.text("Gain")
.suffix(" dB"),
);
if bus.id != settings::AUDIO_BUS_MASTER_ID {
let parent_label = bus
.parent
.as_deref()
.and_then(|parent| bus_ids.iter().find(|id| id.as_str() == parent))
.map(String::as_str)
.unwrap_or("None");
egui::ComboBox::from_id_salt(("audio_bus_parent", index))
.selected_text(parent_label)
.show_ui(ui, |ui| {
for candidate in &bus_ids {
if candidate != &bus.id {
ui.selectable_value(
&mut bus.parent,
Some(candidate.clone()),
candidate,
);
}
}
});
}
});
ui.add_space(4.0);
}
if let Some(index) = remove_bus {
draft.audio.buses.remove(index);
}
if ui.button("Add Bus").clicked() {
let mut suffix = 1usize;
let id = loop {
let candidate = format!("bus_{suffix}");
if draft.audio.bus(&candidate).is_none() {
break candidate;
}
suffix += 1;
};
draft.audio.buses.push(settings::AudioBusSettings::new(
id,
"New Bus",
Some(settings::AUDIO_BUS_MASTER_ID),
));
}
if let Err(error) = draft.audio.validate() {
ui.colored_label(egui::Color32::from_rgb(235, 105, 105), error.to_string());
}
});
ui.separator();
ui.heading("Physics");
ui.add(egui::Slider::new(&mut draft.physics.walk_speed, 1.0..=15.0).text("Walk speed"));
@@ -231,11 +322,18 @@ fn draw_project_settings_form(
);
ui.separator();
if ui.button("Apply").clicked() {
let settings_valid = draft.audio.validate().is_ok();
if ui
.add_enabled(settings_valid, egui::Button::new("Apply"))
.clicked()
{
commit_project_settings(world, draft);
*io_dirty = true;
}
if ui.button("Save to disk").clicked() {
if ui
.add_enabled(settings_valid, egui::Button::new("Save to disk"))
.clicked()
{
commit_project_settings(world, draft);
let settings = world.resource::<ProjectSettings>().clone();
let mut io = world.resource_mut::<ProjectSettingsIo>();