Add collaborative authored-file safety
This commit is contained in:
1 parent
b4aa61e394
commit
5a82a9ee29
23 files changed
+2857
-89
No files matched your search
@@ -1248,6 +1248,10 @@ fn apply_prefab_scope_to_source(
|
||||
return;
|
||||
}
|
||||
};
|
||||
let before_snapshot = crate::collaboration::FileSnapshot::from_loaded_bytes(
|
||||
&source_path,
|
||||
before_source.as_bytes(),
|
||||
);
|
||||
let mut document = match SceneDocument::from_ron_text(&before_source) {
|
||||
Ok(document) => document,
|
||||
Err(error) => {
|
||||
@@ -1361,7 +1365,13 @@ fn apply_prefab_scope_to_source(
|
||||
}
|
||||
let after_source = document.to_ron_text()?;
|
||||
scene::validate_prefab_graph_text(&after_source, &source_path, &project_root)?;
|
||||
crate::scene::recovery::atomic_write(&source_path, after_source.as_bytes())?;
|
||||
crate::collaboration::publish_authored_file(
|
||||
world,
|
||||
&source_path,
|
||||
after_source.as_bytes(),
|
||||
&before_snapshot,
|
||||
crate::collaboration::FileWriteIntent::PrefabSource { instance_root },
|
||||
)?;
|
||||
Ok::<_, String>(after_source)
|
||||
})();
|
||||
let after_source = match apply_result {
|
||||
@@ -2607,6 +2617,22 @@ fn retry_prefab_source(world: &mut World, entity: Entity) {
|
||||
"Prefab source queued for reload".into();
|
||||
}
|
||||
|
||||
pub(crate) fn reload_prefab_source_after_file_conflict(
|
||||
world: &mut World,
|
||||
instance_root: Entity,
|
||||
) -> Result<String, String> {
|
||||
if world.get::<PrefabInstance>(instance_root).is_none() {
|
||||
return Err("the prefab instance no longer exists".into());
|
||||
}
|
||||
retry_prefab_source(world, instance_root);
|
||||
let status = world.resource::<crate::scene_io::SceneIo>().status.clone();
|
||||
if status.starts_with("Prefab retry failed") {
|
||||
Err(status)
|
||||
} else {
|
||||
Ok(status)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn prefab_member_inspector_ui(world: &mut World, ui: &mut egui::Ui, entity: Entity) {
|
||||
let Some((instance_root, target)) = prefab_member_override_target(world, entity) else {
|
||||
ui.label(egui::RichText::new("Prefab target unavailable").color(ERROR));
|
||||
@@ -3258,6 +3284,38 @@ mod tests {
|
||||
assert_eq!(read_overrides(&instance), PrefabOverrides::default());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn collaboration_reload_restarts_prefab_hydration_without_dropping_overrides() {
|
||||
let root = std::env::temp_dir().join(format!(
|
||||
"blacksite-prefab-collaboration-reload-{}",
|
||||
uuid::Uuid::new_v4()
|
||||
));
|
||||
let source_path = root.join("assets/prefabs/base.scn.ron");
|
||||
std::fs::create_dir_all(source_path.parent().unwrap()).unwrap();
|
||||
std::fs::write(&source_path, prefab_source("mesh", None)).unwrap();
|
||||
let mut world = prefab_test_world(&root);
|
||||
let mut instance = PrefabInstance::new("base", "assets/prefabs/base.scn.ron");
|
||||
instance.overrides_ron = encode_prefab_overrides(&PrefabOverrides {
|
||||
source_revision: Some("previous".into()),
|
||||
..Default::default()
|
||||
})
|
||||
.unwrap();
|
||||
let instance_root = world.spawn((instance.clone(), HydratedPrefabReady)).id();
|
||||
|
||||
let status = reload_prefab_source_after_file_conflict(&mut world, instance_root).unwrap();
|
||||
|
||||
assert_eq!(status, "Prefab source queued for reload");
|
||||
assert_eq!(
|
||||
world
|
||||
.get::<PrefabInstance>(instance_root)
|
||||
.map(|current| ¤t.overrides_ron),
|
||||
Some(&instance.overrides_ron)
|
||||
);
|
||||
assert!(world.get::<HydratedPrefabReady>(instance_root).is_none());
|
||||
assert!(world.get::<PrefabRef>(instance_root).is_some());
|
||||
std::fs::remove_dir_all(root).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nested_unpack_fold_is_transactional_when_a_later_link_is_invalid() {
|
||||
let mut world = World::new();
|
||||
|
||||
@@ -1570,7 +1570,7 @@ pub fn set_scene_composition_with_history(world: &mut World, new: SceneCompositi
|
||||
pub fn apply_command_undo(world: &mut World) {
|
||||
let candidate = world.resource::<EditorHistory>().undo_stack.last().cloned();
|
||||
if let Some(candidate) = candidate {
|
||||
if let Err(error) = prepare_prefab_source_history(&candidate, true) {
|
||||
if let Err(error) = prepare_prefab_source_history(world, &candidate, true) {
|
||||
world.resource_mut::<EditorHistory>().status = format!("Undo blocked: {error}");
|
||||
world
|
||||
.resource_mut::<SceneIo>()
|
||||
@@ -1591,7 +1591,7 @@ pub fn apply_command_undo(world: &mut World) {
|
||||
pub fn apply_command_redo(world: &mut World) {
|
||||
let candidate = world.resource::<EditorHistory>().redo_stack.last().cloned();
|
||||
if let Some(candidate) = candidate {
|
||||
if let Err(error) = prepare_prefab_source_history(&candidate, false) {
|
||||
if let Err(error) = prepare_prefab_source_history(world, &candidate, false) {
|
||||
world.resource_mut::<EditorHistory>().status = format!("Redo blocked: {error}");
|
||||
world
|
||||
.resource_mut::<SceneIo>()
|
||||
@@ -1609,8 +1609,13 @@ pub fn apply_command_redo(world: &mut World) {
|
||||
mark_dirty(world);
|
||||
}
|
||||
|
||||
fn prepare_prefab_source_history(command: &EditorCommand, undo: bool) -> Result<(), String> {
|
||||
fn prepare_prefab_source_history(
|
||||
world: &mut World,
|
||||
command: &EditorCommand,
|
||||
undo: bool,
|
||||
) -> Result<(), String> {
|
||||
let EditorCommand::ApplyPrefabToSource {
|
||||
entity,
|
||||
source_path,
|
||||
before_source,
|
||||
after_source,
|
||||
@@ -1624,15 +1629,18 @@ fn prepare_prefab_source_history(command: &EditorCommand, undo: bool) -> Result<
|
||||
} else {
|
||||
(before_source, after_source)
|
||||
};
|
||||
let current = std::fs::read_to_string(source_path)
|
||||
.map_err(|error| format!("could not read {}: {error}", source_path.display()))?;
|
||||
if ¤t != expected {
|
||||
return Err(format!(
|
||||
"{} changed outside this history command",
|
||||
source_path.display()
|
||||
));
|
||||
}
|
||||
crate::scene::recovery::atomic_write(source_path, replacement.as_bytes())
|
||||
let expected =
|
||||
crate::collaboration::FileSnapshot::from_loaded_bytes(source_path, expected.as_bytes());
|
||||
crate::collaboration::publish_authored_file(
|
||||
world,
|
||||
source_path,
|
||||
replacement.as_bytes(),
|
||||
&expected,
|
||||
crate::collaboration::FileWriteIntent::PrefabSourceHistory {
|
||||
instance_root: *entity,
|
||||
},
|
||||
)
|
||||
.map(|_| ())
|
||||
}
|
||||
|
||||
fn undo_command(world: &mut World, command: &mut EditorCommand) {
|
||||
|
||||
@@ -22,6 +22,7 @@ pub use ext::extensibility;
|
||||
pub use ext::hot_reload;
|
||||
pub use play::net_editor;
|
||||
pub use play::state;
|
||||
pub use project::collaboration;
|
||||
pub use project::diagnostics_bundle;
|
||||
pub use project::launcher;
|
||||
pub use project::project_io;
|
||||
@@ -64,6 +65,7 @@ use infra::EditorInfraPlugin;
|
||||
use operators::OperatorPlugin;
|
||||
use play::audio_preview::AudioPreviewPlugin;
|
||||
use play::PlaySessionPlugin;
|
||||
use project::collaboration::CollaborationPlugin;
|
||||
use project_io::ProjectIoPlugin;
|
||||
use render_view::RenderViewPlugin;
|
||||
use scene_io::SceneIoPlugin;
|
||||
@@ -111,6 +113,7 @@ impl PluginGroup for EditorPluginGroup {
|
||||
.add(EditorVisualizersPlugin)
|
||||
.add(EditorHistoryPlugin)
|
||||
.add(SceneIoPlugin)
|
||||
.add(CollaborationPlugin)
|
||||
.add(EditorUiPlugin)
|
||||
.add(EditorSessionPlugin)
|
||||
.add(brp::BrpPlugin);
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,5 +1,6 @@
|
||||
//! Project workspace I/O, settings UI, and recent-level sync.
|
||||
|
||||
pub mod collaboration;
|
||||
pub mod diagnostics_bundle;
|
||||
pub mod launcher;
|
||||
pub mod project_io;
|
||||
|
||||
@@ -1,18 +1,28 @@
|
||||
//! Editor-only Project Settings panel (egui). Data lives in the `settings` crate.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use bevy::prelude::*;
|
||||
use bevy_egui::egui;
|
||||
use game_hot::sync_project_sun_from_settings;
|
||||
use settings::{
|
||||
load_project_settings_from_path, save_project_settings, sync_sim_tuning, ExposureMode,
|
||||
ProjectSettings, ProjectSettingsChanged, ProjectSettingsIo,
|
||||
save_project_settings_to_string, sync_sim_tuning, ExposureMode, ProjectSettings,
|
||||
ProjectSettingsChanged, ProjectSettingsIo,
|
||||
};
|
||||
|
||||
use crate::project::collaboration::{
|
||||
file_status_indicator_ui, publish_authored_file, CollaborationState, FileSnapshot,
|
||||
FileWriteIntent,
|
||||
};
|
||||
use crate::scene_io::SceneIo;
|
||||
|
||||
/// Whether the Project Settings window is visible (editor UI state only).
|
||||
#[derive(Resource, Debug, Default)]
|
||||
pub struct ProjectSettingsPanel {
|
||||
pub open: bool,
|
||||
pub draft: Option<ProjectSettings>,
|
||||
disk_snapshot: Option<FileSnapshot>,
|
||||
save_error: Option<String>,
|
||||
}
|
||||
|
||||
pub struct SettingsUiPlugin;
|
||||
@@ -39,11 +49,23 @@ pub fn project_settings_window(
|
||||
) {
|
||||
if !panel.open {
|
||||
panel.draft = None;
|
||||
panel.disk_snapshot = None;
|
||||
panel.save_error = None;
|
||||
return;
|
||||
}
|
||||
|
||||
if panel.draft.is_none() {
|
||||
panel.draft = Some(world.resource::<ProjectSettings>().clone());
|
||||
let io = world.resource::<ProjectSettingsIo>();
|
||||
panel.disk_snapshot = Some(
|
||||
io.loaded_source
|
||||
.as_deref()
|
||||
.map(|source| {
|
||||
FileSnapshot::from_loaded_bytes(Path::new(&io.path), source.as_bytes())
|
||||
})
|
||||
.unwrap_or_else(FileSnapshot::missing),
|
||||
);
|
||||
panel.save_error = None;
|
||||
}
|
||||
|
||||
let mut open = panel.open;
|
||||
@@ -51,17 +73,33 @@ pub fn project_settings_window(
|
||||
.open(&mut open)
|
||||
.default_width(420.0)
|
||||
.show(ctx, |ui| {
|
||||
let Some(draft) = panel.draft.as_mut() else {
|
||||
let ProjectSettingsPanel {
|
||||
draft: Some(draft),
|
||||
disk_snapshot,
|
||||
save_error,
|
||||
..
|
||||
} = panel
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let io_path = world.resource::<ProjectSettingsIo>().path.clone();
|
||||
let mut io_dirty = world.resource::<ProjectSettingsIo>().dirty;
|
||||
draw_project_settings_form(world, ui, draft, &io_path, &mut io_dirty);
|
||||
draw_project_settings_form(
|
||||
world,
|
||||
ui,
|
||||
draft,
|
||||
&io_path,
|
||||
&mut io_dirty,
|
||||
disk_snapshot,
|
||||
save_error,
|
||||
);
|
||||
world.resource_mut::<ProjectSettingsIo>().dirty = io_dirty;
|
||||
});
|
||||
panel.open = open;
|
||||
if !open {
|
||||
panel.draft = None;
|
||||
panel.disk_snapshot = None;
|
||||
panel.save_error = None;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -71,12 +109,26 @@ fn draw_project_settings_form(
|
||||
draft: &mut ProjectSettings,
|
||||
io_path: &str,
|
||||
io_dirty: &mut bool,
|
||||
disk_snapshot: &mut Option<FileSnapshot>,
|
||||
save_error: &mut Option<String>,
|
||||
) {
|
||||
let caps = world
|
||||
.get_resource::<settings::RenderingCapabilities>()
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.small(egui::RichText::new(io_path).monospace());
|
||||
if let Some(state) = world.get_resource::<CollaborationState>() {
|
||||
let status = state.file_status(Path::new(io_path));
|
||||
let _ = file_status_indicator_ui(ui, &status, Path::new(io_path));
|
||||
}
|
||||
});
|
||||
if let Some(error) = save_error.as_deref() {
|
||||
ui.colored_label(crate::ui::theme::ERROR, error);
|
||||
}
|
||||
ui.separator();
|
||||
|
||||
ui.collapsing("Global Illumination", |ui| {
|
||||
egui::ComboBox::from_label("GiMode")
|
||||
.selected_text(format!("{:?}", draft.rendering.gi_mode))
|
||||
@@ -335,25 +387,116 @@ fn draw_project_settings_form(
|
||||
.clicked()
|
||||
{
|
||||
commit_project_settings(world, draft);
|
||||
*io_dirty = true;
|
||||
let settings = world.resource::<ProjectSettings>().clone();
|
||||
let mut io = world.resource_mut::<ProjectSettingsIo>();
|
||||
if let Err(error) = save_project_settings(&settings, &mut io) {
|
||||
warn!("Save project settings failed: {error}");
|
||||
} else {
|
||||
*io_dirty = false;
|
||||
let Some(expected) = disk_snapshot.clone() else {
|
||||
let error = "Project settings disk baseline is unavailable; reload before saving";
|
||||
*save_error = Some(error.into());
|
||||
world.resource_mut::<SceneIo>().set_status(error);
|
||||
return;
|
||||
};
|
||||
match persist_project_settings(world, &settings, &expected) {
|
||||
Ok((snapshot, source)) => {
|
||||
let mut io = world.resource_mut::<ProjectSettingsIo>();
|
||||
io.dirty = false;
|
||||
io.loaded_source = Some(source);
|
||||
*disk_snapshot = Some(snapshot);
|
||||
*save_error = None;
|
||||
*io_dirty = false;
|
||||
world
|
||||
.resource_mut::<SceneIo>()
|
||||
.set_status(format!("Saved project settings to {io_path}"));
|
||||
}
|
||||
Err(error) => {
|
||||
warn!("Save project settings failed: {error}");
|
||||
*save_error = Some(error.clone());
|
||||
world
|
||||
.resource_mut::<SceneIo>()
|
||||
.set_status(format!("Save project settings failed: {error}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
if ui.button("Revert from disk").clicked() {
|
||||
*draft = load_project_settings_from_path(io_path);
|
||||
commit_project_settings(world, draft);
|
||||
world.resource_mut::<ProjectSettingsIo>().dirty = false;
|
||||
*io_dirty = false;
|
||||
match read_project_settings_document(Path::new(io_path)) {
|
||||
Ok((settings, source, snapshot)) => {
|
||||
*draft = settings;
|
||||
commit_project_settings(world, draft);
|
||||
let mut io = world.resource_mut::<ProjectSettingsIo>();
|
||||
io.dirty = false;
|
||||
io.loaded_source = Some(source);
|
||||
*disk_snapshot = Some(snapshot);
|
||||
*save_error = None;
|
||||
*io_dirty = false;
|
||||
}
|
||||
Err(error) => {
|
||||
*save_error = Some(error.clone());
|
||||
world
|
||||
.resource_mut::<SceneIo>()
|
||||
.set_status(format!("Revert project settings failed: {error}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
if *io_dirty {
|
||||
ui.label(egui::RichText::new("Unsaved changes").color(egui::Color32::YELLOW));
|
||||
}
|
||||
}
|
||||
|
||||
fn persist_project_settings(
|
||||
world: &mut World,
|
||||
settings: &ProjectSettings,
|
||||
expected: &FileSnapshot,
|
||||
) -> Result<(FileSnapshot, String), String> {
|
||||
let path = world.resource::<ProjectSettingsIo>().path.clone();
|
||||
let source = save_project_settings_to_string(settings).map_err(|error| error.to_string())?;
|
||||
let snapshot = publish_authored_file(
|
||||
world,
|
||||
Path::new(&path),
|
||||
source.as_bytes(),
|
||||
expected,
|
||||
FileWriteIntent::ProjectSettings,
|
||||
)?;
|
||||
Ok((snapshot, source))
|
||||
}
|
||||
|
||||
fn read_project_settings_document(
|
||||
path: &Path,
|
||||
) -> Result<(ProjectSettings, String, FileSnapshot), String> {
|
||||
let source = std::fs::read_to_string(path)
|
||||
.map_err(|error| format!("could not read {}: {error}", path.display()))?;
|
||||
let settings: ProjectSettings = ron::from_str(&source)
|
||||
.map_err(|error| format!("invalid project settings in {}: {error}", path.display()))?;
|
||||
let snapshot = FileSnapshot::from_loaded_bytes(path, source.as_bytes());
|
||||
Ok((settings, source, snapshot))
|
||||
}
|
||||
|
||||
pub(crate) fn reload_project_settings_after_file_conflict(
|
||||
world: &mut World,
|
||||
path: &Path,
|
||||
) -> Result<String, String> {
|
||||
let active_path = world.resource::<ProjectSettingsIo>().path.clone();
|
||||
if Path::new(&active_path) != path {
|
||||
return Err("the project settings conflict no longer matches the active manifest".into());
|
||||
}
|
||||
let (settings, source, snapshot) = read_project_settings_document(path)?;
|
||||
commit_project_settings(world, &settings);
|
||||
{
|
||||
let mut io = world.resource_mut::<ProjectSettingsIo>();
|
||||
io.dirty = false;
|
||||
io.loaded_source = Some(source);
|
||||
}
|
||||
{
|
||||
let mut panel = world.resource_mut::<ProjectSettingsPanel>();
|
||||
panel.draft = Some(settings);
|
||||
panel.disk_snapshot = Some(snapshot);
|
||||
panel.save_error = None;
|
||||
}
|
||||
Ok(format!("Reloaded project settings from {}", path.display()))
|
||||
}
|
||||
|
||||
pub(crate) fn project_settings_conflict_copy_saved(world: &mut World) {
|
||||
world.resource_mut::<ProjectSettingsPanel>().save_error = None;
|
||||
}
|
||||
|
||||
fn commit_project_settings(world: &mut World, draft: &ProjectSettings) {
|
||||
let previous = world.resource::<ProjectSettings>().rendering.gi_mode;
|
||||
*world.resource_mut::<ProjectSettings>() = draft.clone();
|
||||
@@ -406,3 +549,35 @@ fn apply_project_settings_changes(
|
||||
// Full stack refresh runs next frame via `render_view::sync_project_render_view`
|
||||
// when `ProjectSettings` changes.
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn project_settings_save_refuses_an_external_revision() {
|
||||
let root = std::env::temp_dir().join(format!(
|
||||
"blacksite-project-settings-external-write-{}",
|
||||
uuid::Uuid::new_v4()
|
||||
));
|
||||
let path = root.join("assets/project.ron");
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
let loaded = save_project_settings_to_string(&ProjectSettings::default()).unwrap();
|
||||
std::fs::write(&path, &loaded).unwrap();
|
||||
let expected = FileSnapshot::from_loaded_bytes(&path, loaded.as_bytes());
|
||||
let mut world = World::new();
|
||||
world.insert_resource(ProjectSettingsIo {
|
||||
path: path.to_string_lossy().into_owned(),
|
||||
loaded_source: Some(loaded),
|
||||
..Default::default()
|
||||
});
|
||||
world.insert_resource(SceneIo::default());
|
||||
std::fs::write(&path, b"external").unwrap();
|
||||
|
||||
let result = persist_project_settings(&mut world, &ProjectSettings::default(), &expected);
|
||||
|
||||
assert!(result.unwrap_err().contains("changed outside Blacksite"));
|
||||
assert_eq!(std::fs::read(&path).unwrap(), b"external");
|
||||
std::fs::remove_dir_all(root).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -13,17 +13,20 @@ pub(crate) fn atomic_write(path: &Path, bytes: &[u8]) -> Result<(), String> {
|
||||
atomic_write_with_pre_rename(path, bytes, || Ok(()))
|
||||
}
|
||||
|
||||
fn atomic_write_with_pre_rename(
|
||||
pub(crate) fn atomic_write_with_pre_rename<E>(
|
||||
path: &Path,
|
||||
bytes: &[u8],
|
||||
before_rename: impl FnOnce() -> Result<(), String>,
|
||||
) -> Result<(), String> {
|
||||
before_rename: impl FnOnce() -> Result<(), E>,
|
||||
) -> Result<(), E>
|
||||
where
|
||||
E: From<String>,
|
||||
{
|
||||
let parent = path
|
||||
.parent()
|
||||
.filter(|parent| !parent.as_os_str().is_empty())
|
||||
.unwrap_or_else(|| Path::new("."));
|
||||
fs::create_dir_all(parent)
|
||||
.map_err(|error| format!("could not create {}: {error}", parent.display()))?;
|
||||
.map_err(|error| E::from(format!("could not create {}: {error}", parent.display())))?;
|
||||
|
||||
let file_name = path
|
||||
.file_name()
|
||||
@@ -40,18 +43,21 @@ fn atomic_write_with_pre_rename(
|
||||
.create_new(true)
|
||||
.write(true)
|
||||
.open(&temporary)
|
||||
.map_err(|error| format!("could not create {}: {error}", temporary.display()))?;
|
||||
file.write_all(bytes)
|
||||
.map_err(|error| format!("could not write {}: {error}", temporary.display()))?;
|
||||
.map_err(|error| {
|
||||
E::from(format!("could not create {}: {error}", temporary.display()))
|
||||
})?;
|
||||
file.write_all(bytes).map_err(|error| {
|
||||
E::from(format!("could not write {}: {error}", temporary.display()))
|
||||
})?;
|
||||
file.sync_all()
|
||||
.map_err(|error| format!("could not sync {}: {error}", temporary.display()))?;
|
||||
.map_err(|error| E::from(format!("could not sync {}: {error}", temporary.display())))?;
|
||||
before_rename()?;
|
||||
fs::rename(&temporary, path).map_err(|error| {
|
||||
format!(
|
||||
E::from(format!(
|
||||
"could not replace {} with {}: {error}",
|
||||
path.display(),
|
||||
temporary.display()
|
||||
)
|
||||
))
|
||||
})?;
|
||||
sync_parent_directory(parent);
|
||||
Ok(())
|
||||
|
||||
@@ -23,8 +23,9 @@ use shared::{
|
||||
|
||||
use crate::assets::{import_external_assets, EditorAssets, IMPORTABLE_ASSET_EXTENSIONS};
|
||||
use crate::history::{clear_level_objects, snapshot_entity, EditorHistory};
|
||||
use crate::project::collaboration::{publish_authored_file, FileSnapshot, FileWriteIntent};
|
||||
use crate::scene::recovery::{
|
||||
atomic_write, default_state_root, discard_recovery_snapshots, latest_recovery_snapshot,
|
||||
default_state_root, discard_recovery_snapshots, latest_recovery_snapshot,
|
||||
write_recovery_snapshot,
|
||||
};
|
||||
use crate::selection::SelectedEntity;
|
||||
@@ -60,6 +61,7 @@ pub struct SceneTab {
|
||||
pub dirty: bool,
|
||||
snapshot: String,
|
||||
recovery_snapshot: Option<PathBuf>,
|
||||
disk_snapshot: Option<FileSnapshot>,
|
||||
}
|
||||
|
||||
impl SceneTab {
|
||||
@@ -126,6 +128,7 @@ impl Default for SceneIo {
|
||||
dirty: false,
|
||||
snapshot: String::new(),
|
||||
recovery_snapshot: None,
|
||||
disk_snapshot: None,
|
||||
}],
|
||||
active_tab: 0,
|
||||
change_revision: 0,
|
||||
@@ -252,9 +255,14 @@ fn load_startup_scene(world: &mut World) {
|
||||
let path = active_path.unwrap_or(default_path);
|
||||
|
||||
match load_level(world, &path) {
|
||||
Ok(()) => {
|
||||
world.resource_mut::<SceneIo>().active_path = Some(path.clone());
|
||||
world.resource_mut::<SceneIo>().mark_clean();
|
||||
Ok(disk_snapshot) => {
|
||||
{
|
||||
let mut io = world.resource_mut::<SceneIo>();
|
||||
io.active_path = Some(path.clone());
|
||||
let active_tab = io.active_tab;
|
||||
io.tabs[active_tab].disk_snapshot = Some(disk_snapshot);
|
||||
io.mark_clean();
|
||||
}
|
||||
remember_path(world, path.clone());
|
||||
world.resource_mut::<EditorHistory>().clear();
|
||||
refresh_recovery_notice(world, &path);
|
||||
@@ -396,7 +404,7 @@ fn open_path(world: &mut World, path: PathBuf) -> String {
|
||||
return format!("Open failed: could not preserve active scene: {error}");
|
||||
}
|
||||
match load_level(world, &path) {
|
||||
Ok(()) => {
|
||||
Ok(disk_snapshot) => {
|
||||
let id = world.resource_mut::<SceneIo>().allocate_tab_id();
|
||||
{
|
||||
let mut io = world.resource_mut::<SceneIo>();
|
||||
@@ -406,6 +414,7 @@ fn open_path(world: &mut World, path: PathBuf) -> String {
|
||||
dirty: false,
|
||||
snapshot: String::new(),
|
||||
recovery_snapshot: None,
|
||||
disk_snapshot: Some(disk_snapshot),
|
||||
});
|
||||
io.active_tab = io.tabs.len() - 1;
|
||||
io.active_path = Some(path.clone());
|
||||
@@ -442,6 +451,7 @@ fn new_scene_tab(world: &mut World) -> String {
|
||||
dirty: false,
|
||||
snapshot: String::new(),
|
||||
recovery_snapshot: None,
|
||||
disk_snapshot: None,
|
||||
});
|
||||
io.active_tab = io.tabs.len() - 1;
|
||||
io.active_path = None;
|
||||
@@ -550,6 +560,7 @@ fn close_scene_tab(world: &mut World, index: usize) -> String {
|
||||
dirty: false,
|
||||
snapshot: String::new(),
|
||||
recovery_snapshot: None,
|
||||
disk_snapshot: None,
|
||||
}];
|
||||
io.active_tab = 0;
|
||||
io.active_path = None;
|
||||
@@ -691,12 +702,24 @@ fn save_selection_as_prefab(world: &mut World) -> String {
|
||||
else {
|
||||
return "Save prefab cancelled".to_string();
|
||||
};
|
||||
let expected = match FileSnapshot::capture(&path) {
|
||||
Ok(expected) => expected,
|
||||
Err(error) => return format!("Save prefab failed: {error}"),
|
||||
};
|
||||
|
||||
if ensure_unique_actor_ids(world, &selection) > 0 {
|
||||
world.resource_mut::<SceneIo>().mark_dirty();
|
||||
}
|
||||
|
||||
match save_prefab_entities(world, &path, selection) {
|
||||
match save_prefab_entities(
|
||||
world,
|
||||
&path,
|
||||
selection,
|
||||
SceneWriteContext::Standalone {
|
||||
expected,
|
||||
description: "prefab copy",
|
||||
},
|
||||
) {
|
||||
Ok(count) => {
|
||||
world.resource_mut::<EditorAssets>().refresh();
|
||||
format!(
|
||||
@@ -775,6 +798,7 @@ fn save_prefab_entities(
|
||||
world: &mut World,
|
||||
path: &Path,
|
||||
entities: Vec<Entity>,
|
||||
write_context: SceneWriteContext,
|
||||
) -> Result<usize, String> {
|
||||
let count = entities.len();
|
||||
let original_actor_ids: Vec<_> = entities
|
||||
@@ -791,7 +815,7 @@ fn save_prefab_entities(
|
||||
.clone(),
|
||||
);
|
||||
scene::validate_prefab_graph_text(&text, path, &project_root)?;
|
||||
atomic_write(path, text.as_bytes())?;
|
||||
publish_scene_text(world, path, text.as_bytes(), count, write_context)?;
|
||||
Ok(count)
|
||||
})();
|
||||
if result.is_err() {
|
||||
@@ -821,7 +845,7 @@ pub fn save_active_or_prompt_world(world: &mut World) -> String {
|
||||
fn save_active_or_prompt(world: &mut World) -> String {
|
||||
let path = world.resource::<SceneIo>().active_path.clone();
|
||||
match path {
|
||||
Some(path) => match save_level(world, &path) {
|
||||
Some(path) => match save_level(world, &path, SceneWriteContext::Active) {
|
||||
Ok(count) => {
|
||||
world.resource_mut::<SceneIo>().mark_clean();
|
||||
remember_path(world, path.clone());
|
||||
@@ -843,8 +867,12 @@ fn save_with_dialog(world: &mut World) -> String {
|
||||
else {
|
||||
return "Save cancelled".to_string();
|
||||
};
|
||||
let expected = match FileSnapshot::capture(&path) {
|
||||
Ok(expected) => expected,
|
||||
Err(error) => return format!("Save failed: {error}"),
|
||||
};
|
||||
|
||||
match save_level(world, &path) {
|
||||
match save_level(world, &path, SceneWriteContext::ActiveSaveAs { expected }) {
|
||||
Ok(count) => {
|
||||
world.resource_mut::<SceneIo>().active_path = Some(path.clone());
|
||||
world.resource_mut::<SceneIo>().mark_clean();
|
||||
@@ -901,8 +929,20 @@ fn export_selection_with_dialog(world: &mut World) -> String {
|
||||
else {
|
||||
return "Export cancelled".to_string();
|
||||
};
|
||||
let expected = match FileSnapshot::capture(&path) {
|
||||
Ok(expected) => expected,
|
||||
Err(error) => return format!("Export failed: {error}"),
|
||||
};
|
||||
|
||||
match save_standalone_entities(world, &path, vec![entity]) {
|
||||
match save_standalone_entities(
|
||||
world,
|
||||
&path,
|
||||
vec![entity],
|
||||
SceneWriteContext::Standalone {
|
||||
expected,
|
||||
description: "selection export",
|
||||
},
|
||||
) {
|
||||
Ok(count) => format!("Exported {count} selected entity to {}", path.display()),
|
||||
Err(err) => format!("Export failed: {err}"),
|
||||
}
|
||||
@@ -934,12 +974,16 @@ fn clear_scene_world(world: &mut World) {
|
||||
}
|
||||
}
|
||||
|
||||
fn save_level(world: &mut World, path: &Path) -> Result<usize, String> {
|
||||
fn save_level(
|
||||
world: &mut World,
|
||||
path: &Path,
|
||||
write_context: SceneWriteContext,
|
||||
) -> Result<usize, String> {
|
||||
let entities = authored_scene_entities(world);
|
||||
if is_prefab_document(path) {
|
||||
save_prefab_entities(world, path, entities)
|
||||
save_prefab_entities(world, path, entities, write_context)
|
||||
} else {
|
||||
save_entities(world, path, entities)
|
||||
save_entities(world, path, entities, write_context)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1131,10 +1175,15 @@ fn format_actor_validation(err: ActorValidationError) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
fn save_entities(world: &mut World, path: &Path, entities: Vec<Entity>) -> Result<usize, String> {
|
||||
fn save_entities(
|
||||
world: &mut World,
|
||||
path: &Path,
|
||||
entities: Vec<Entity>,
|
||||
write_context: SceneWriteContext,
|
||||
) -> Result<usize, String> {
|
||||
let count = entities.len();
|
||||
let text = serialize_entities(world, entities)?;
|
||||
atomic_write(path, text.as_bytes())?;
|
||||
publish_scene_text(world, path, text.as_bytes(), count, write_context)?;
|
||||
Ok(count)
|
||||
}
|
||||
|
||||
@@ -1142,13 +1191,108 @@ fn save_standalone_entities(
|
||||
world: &mut World,
|
||||
path: &Path,
|
||||
entities: Vec<Entity>,
|
||||
write_context: SceneWriteContext,
|
||||
) -> Result<usize, String> {
|
||||
let count = entities.len();
|
||||
let text = serialize_standalone_entities(world, entities)?;
|
||||
atomic_write(path, text.as_bytes())?;
|
||||
publish_scene_text(world, path, text.as_bytes(), count, write_context)?;
|
||||
Ok(count)
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
enum SceneWriteContext {
|
||||
Active,
|
||||
ActiveSaveAs {
|
||||
expected: FileSnapshot,
|
||||
},
|
||||
Standalone {
|
||||
expected: FileSnapshot,
|
||||
description: &'static str,
|
||||
},
|
||||
}
|
||||
|
||||
fn publish_scene_text(
|
||||
world: &mut World,
|
||||
path: &Path,
|
||||
bytes: &[u8],
|
||||
entity_count: usize,
|
||||
context: SceneWriteContext,
|
||||
) -> Result<(), String> {
|
||||
match context {
|
||||
SceneWriteContext::Active | SceneWriteContext::ActiveSaveAs { .. } => {
|
||||
let (tab_id, expected) = match context {
|
||||
SceneWriteContext::Active => active_scene_write_baseline(world, path)?,
|
||||
SceneWriteContext::ActiveSaveAs { expected } => {
|
||||
(active_scene_tab_id(world)?, expected)
|
||||
}
|
||||
SceneWriteContext::Standalone { .. } => unreachable!(),
|
||||
};
|
||||
let snapshot = publish_authored_file(
|
||||
world,
|
||||
path,
|
||||
bytes,
|
||||
&expected,
|
||||
FileWriteIntent::Scene {
|
||||
tab_id,
|
||||
entity_count,
|
||||
},
|
||||
)?;
|
||||
let mut io = world.resource_mut::<SceneIo>();
|
||||
let Some(tab) = io.tabs.iter_mut().find(|tab| tab.id == tab_id) else {
|
||||
return Err("saved scene tab no longer exists".into());
|
||||
};
|
||||
tab.disk_snapshot = Some(snapshot);
|
||||
}
|
||||
SceneWriteContext::Standalone {
|
||||
expected,
|
||||
description,
|
||||
} => {
|
||||
publish_authored_file(
|
||||
world,
|
||||
path,
|
||||
bytes,
|
||||
&expected,
|
||||
FileWriteIntent::Standalone {
|
||||
description: description.into(),
|
||||
},
|
||||
)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn active_scene_write_baseline(
|
||||
world: &World,
|
||||
destination: &Path,
|
||||
) -> Result<(u64, FileSnapshot), String> {
|
||||
let io = world.resource::<SceneIo>();
|
||||
let tab = io
|
||||
.tabs
|
||||
.get(io.active_tab)
|
||||
.ok_or_else(|| "active scene tab is missing".to_string())?;
|
||||
if io.active_path.as_deref() != Some(destination) || tab.path.as_deref() != Some(destination) {
|
||||
return Err(format!(
|
||||
"{} is not the active scene destination; use Save As",
|
||||
destination.display()
|
||||
));
|
||||
}
|
||||
let expected = tab.disk_snapshot.clone().ok_or_else(|| {
|
||||
format!(
|
||||
"scene disk baseline is unavailable for {}; reload it or use Save As",
|
||||
destination.display()
|
||||
)
|
||||
})?;
|
||||
Ok((tab.id, expected))
|
||||
}
|
||||
|
||||
fn active_scene_tab_id(world: &World) -> Result<u64, String> {
|
||||
let io = world.resource::<SceneIo>();
|
||||
io.tabs
|
||||
.get(io.active_tab)
|
||||
.map(|tab| tab.id)
|
||||
.ok_or_else(|| "active scene tab is missing".to_string())
|
||||
}
|
||||
|
||||
fn serialize_entities(world: &mut World, entities: Vec<Entity>) -> Result<String, String> {
|
||||
serialize_entities_inner_with_resources(world, entities, true)
|
||||
}
|
||||
@@ -1430,7 +1574,7 @@ fn restore_recovery(world: &mut World) -> String {
|
||||
return "No scene recovery snapshot is available".to_string();
|
||||
};
|
||||
match load_level(world, &snapshot) {
|
||||
Ok(()) => {
|
||||
Ok(_) => {
|
||||
mark_recovery_restored(&mut world.resource_mut::<SceneIo>(), active_path);
|
||||
world.resource_mut::<EditorHistory>().clear();
|
||||
format!(
|
||||
@@ -1471,8 +1615,12 @@ fn save_recovery_copy_with_dialog(world: &mut World) -> String {
|
||||
else {
|
||||
return "Save recovery copy cancelled".to_string();
|
||||
};
|
||||
let expected = match FileSnapshot::capture(&destination) {
|
||||
Ok(expected) => expected,
|
||||
Err(error) => return format!("Save recovery copy failed: {error}"),
|
||||
};
|
||||
|
||||
match write_recovery_copy(&snapshot, &destination) {
|
||||
match write_recovery_copy(world, &snapshot, &destination, &expected) {
|
||||
Ok(()) => format!(
|
||||
"Saved recovery copy {} from {}",
|
||||
destination.display(),
|
||||
@@ -1482,10 +1630,24 @@ fn save_recovery_copy_with_dialog(world: &mut World) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
fn write_recovery_copy(snapshot: &Path, destination: &Path) -> Result<(), String> {
|
||||
fn write_recovery_copy(
|
||||
world: &mut World,
|
||||
snapshot: &Path,
|
||||
destination: &Path,
|
||||
expected: &FileSnapshot,
|
||||
) -> Result<(), String> {
|
||||
let bytes = std::fs::read(snapshot)
|
||||
.map_err(|error| format!("could not read {}: {error}", snapshot.display()))?;
|
||||
atomic_write(destination, &bytes)
|
||||
publish_authored_file(
|
||||
world,
|
||||
destination,
|
||||
&bytes,
|
||||
expected,
|
||||
FileWriteIntent::Standalone {
|
||||
description: "recovery scene copy".into(),
|
||||
},
|
||||
)
|
||||
.map(|_| ())
|
||||
}
|
||||
|
||||
fn mark_recovery_restored(io: &mut SceneIo, active_path: Option<PathBuf>) {
|
||||
@@ -1522,14 +1684,79 @@ fn discard_recovery(world: &mut World) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
fn load_level(world: &mut World, path: &Path) -> Result<(), String> {
|
||||
fn load_level(world: &mut World, path: &Path) -> Result<FileSnapshot, String> {
|
||||
if !path.exists() {
|
||||
return Err(format!("{} does not exist yet", path.display()));
|
||||
}
|
||||
|
||||
let text = std::fs::read_to_string(path)
|
||||
.map_err(|err| format!("could not read {}: {err}", path.display()))?;
|
||||
load_level_text(world, Some(path), &text)
|
||||
let disk_snapshot = FileSnapshot::from_loaded_bytes(path, text.as_bytes());
|
||||
load_level_text(world, Some(path), &text)?;
|
||||
Ok(disk_snapshot)
|
||||
}
|
||||
|
||||
pub(crate) fn reload_scene_after_file_conflict(
|
||||
world: &mut World,
|
||||
tab_id: u64,
|
||||
path: &Path,
|
||||
) -> Result<String, String> {
|
||||
let active_matches = {
|
||||
let io = world.resource::<SceneIo>();
|
||||
io.tabs
|
||||
.get(io.active_tab)
|
||||
.is_some_and(|tab| tab.id == tab_id)
|
||||
};
|
||||
if !active_matches {
|
||||
return Err("the scene conflict no longer belongs to the active tab".into());
|
||||
}
|
||||
|
||||
let disk_snapshot = load_level(world, path)?;
|
||||
{
|
||||
let mut io = world.resource_mut::<SceneIo>();
|
||||
io.active_path = Some(path.to_path_buf());
|
||||
io.recovery_snapshot = None;
|
||||
let active_tab = io.active_tab;
|
||||
io.tabs[active_tab].disk_snapshot = Some(disk_snapshot);
|
||||
io.mark_clean();
|
||||
}
|
||||
world.resource_mut::<EditorHistory>().clear();
|
||||
remember_path(world, path.to_path_buf());
|
||||
refresh_recovery_notice(world, path);
|
||||
capture_active_tab(world)?;
|
||||
Ok(format!("Reloaded {} from disk", path.display()))
|
||||
}
|
||||
|
||||
pub(crate) fn adopt_scene_conflict_save_as(
|
||||
world: &mut World,
|
||||
tab_id: u64,
|
||||
path: PathBuf,
|
||||
disk_snapshot: FileSnapshot,
|
||||
entity_count: usize,
|
||||
) -> Result<String, String> {
|
||||
let active_matches = {
|
||||
let io = world.resource::<SceneIo>();
|
||||
io.tabs
|
||||
.get(io.active_tab)
|
||||
.is_some_and(|tab| tab.id == tab_id)
|
||||
};
|
||||
if !active_matches {
|
||||
return Err("the scene conflict no longer belongs to the active tab".into());
|
||||
}
|
||||
|
||||
{
|
||||
let mut io = world.resource_mut::<SceneIo>();
|
||||
io.active_path = Some(path.clone());
|
||||
let active_tab = io.active_tab;
|
||||
io.tabs[active_tab].disk_snapshot = Some(disk_snapshot);
|
||||
io.mark_clean();
|
||||
}
|
||||
remember_path(world, path.clone());
|
||||
retire_scene_recovery(world, &path);
|
||||
Ok(format!(
|
||||
"Saved {entity_count} level entities to {}",
|
||||
path.display()
|
||||
))
|
||||
}
|
||||
|
||||
fn load_level_text(world: &mut World, path: Option<&Path>, text: &str) -> Result<(), String> {
|
||||
@@ -1979,6 +2206,7 @@ mod tests {
|
||||
dirty: true,
|
||||
snapshot: "dirty inactive tab".to_string(),
|
||||
recovery_snapshot: None,
|
||||
disk_snapshot: None,
|
||||
});
|
||||
assert!(
|
||||
io.has_unsaved_tabs(),
|
||||
@@ -1993,6 +2221,61 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn active_scene_write_refuses_an_external_revision() {
|
||||
let root = std::env::temp_dir().join(format!(
|
||||
"blacksite-scene-external-write-{}",
|
||||
uuid::Uuid::new_v4()
|
||||
));
|
||||
let path = root.join("assets/levels/main.scn.ron");
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
std::fs::write(&path, b"loaded").unwrap();
|
||||
let disk_snapshot = FileSnapshot::capture(&path).unwrap();
|
||||
let mut io = SceneIo {
|
||||
active_path: Some(path.clone()),
|
||||
..Default::default()
|
||||
};
|
||||
io.tabs[0].path = Some(path.clone());
|
||||
io.tabs[0].disk_snapshot = Some(disk_snapshot);
|
||||
let mut world = World::new();
|
||||
world.insert_resource(io);
|
||||
std::fs::write(&path, b"external").unwrap();
|
||||
|
||||
let result = publish_scene_text(&mut world, &path, b"editor", 1, SceneWriteContext::Active);
|
||||
|
||||
assert!(result.unwrap_err().contains("changed outside Blacksite"));
|
||||
assert_eq!(std::fs::read(&path).unwrap(), b"external");
|
||||
assert!(world.resource::<SceneIo>().dirty);
|
||||
std::fs::remove_dir_all(root).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scene_save_as_refuses_a_file_created_after_destination_selection() {
|
||||
let root = std::env::temp_dir().join(format!(
|
||||
"blacksite-scene-save-as-race-{}",
|
||||
uuid::Uuid::new_v4()
|
||||
));
|
||||
let path = root.join("assets/levels/new.scn.ron");
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
let expected = FileSnapshot::missing();
|
||||
let mut world = World::new();
|
||||
world.init_resource::<SceneIo>();
|
||||
std::fs::write(&path, b"external").unwrap();
|
||||
|
||||
let result = publish_scene_text(
|
||||
&mut world,
|
||||
&path,
|
||||
b"editor",
|
||||
1,
|
||||
SceneWriteContext::ActiveSaveAs { expected },
|
||||
);
|
||||
|
||||
assert!(result.unwrap_err().contains("changed outside Blacksite"));
|
||||
assert_eq!(std::fs::read(&path).unwrap(), b"external");
|
||||
assert!(world.resource::<SceneIo>().dirty);
|
||||
std::fs::remove_dir_all(root).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn composition_edits_participate_in_undo_and_redo() {
|
||||
let mut app = App::new();
|
||||
@@ -2770,8 +3053,13 @@ mod tests {
|
||||
.insert_resource(crate::ui::hierarchy_state::HierarchyPanelState::default());
|
||||
app.world_mut().init_resource::<SceneIo>();
|
||||
|
||||
load_level(app.world_mut(), &prefab_path).unwrap();
|
||||
save_level(app.world_mut(), &prefab_path).unwrap();
|
||||
let expected = load_level(app.world_mut(), &prefab_path).unwrap();
|
||||
save_level(
|
||||
app.world_mut(),
|
||||
&prefab_path,
|
||||
SceneWriteContext::ActiveSaveAs { expected },
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
scene::validate_prefab_graph(&prefab_path, &root).unwrap();
|
||||
let document =
|
||||
@@ -2813,8 +3101,11 @@ mod tests {
|
||||
let destination = root.join("kept.scn.ron");
|
||||
std::fs::create_dir_all(&root).unwrap();
|
||||
std::fs::write(&snapshot, b"recovered scene bytes").unwrap();
|
||||
let expected = FileSnapshot::missing();
|
||||
let mut world = World::new();
|
||||
world.init_resource::<SceneIo>();
|
||||
|
||||
write_recovery_copy(&snapshot, &destination).unwrap();
|
||||
write_recovery_copy(&mut world, &snapshot, &destination, &expected).unwrap();
|
||||
|
||||
assert_eq!(
|
||||
std::fs::read(&destination).unwrap(),
|
||||
|
||||
@@ -20,6 +20,10 @@ use crate::assets::{
|
||||
AssetSelection, AssetSubAssetKind, EditorAsset, EditorAssetKind, EditorAssets, ASSETS_ROOT,
|
||||
BUILTINS_FOLDER,
|
||||
};
|
||||
use crate::project::collaboration::{
|
||||
file_status_indicator_ui, publish_authored_file, CollaborationState, FileSnapshot,
|
||||
FileWriteIntent,
|
||||
};
|
||||
use crate::scene_io::{SceneIo, SceneIoRequest};
|
||||
|
||||
use super::state::{
|
||||
@@ -1857,7 +1861,7 @@ fn top_level_asset_details_panel(
|
||||
selected_entities: &SelectedEntities,
|
||||
asset: &EditorAsset,
|
||||
) {
|
||||
asset_details_header(ui, asset);
|
||||
asset_details_header(world, ui, asset);
|
||||
ui.add_space(8.0);
|
||||
detail_row(ui, "Path", asset.path.as_deref().unwrap_or("Built-in"));
|
||||
detail_row(ui, "Folder", asset.folder_path.as_str());
|
||||
@@ -1946,7 +1950,7 @@ fn top_level_asset_details_panel(
|
||||
asset_action_buttons(world, ui, selected_entities, asset);
|
||||
}
|
||||
|
||||
fn asset_details_header(ui: &mut egui::Ui, asset: &EditorAsset) {
|
||||
fn asset_details_header(world: &World, ui: &mut egui::Ui, asset: &EditorAsset) {
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.label(
|
||||
egui::RichText::new(kind_icon(&asset.kind).as_str())
|
||||
@@ -1959,6 +1963,13 @@ fn asset_details_header(ui: &mut egui::Ui, asset: &EditorAsset) {
|
||||
ui.vertical(|ui| {
|
||||
ui.strong(asset.label.as_str());
|
||||
ui.small(egui::RichText::new(kind_label(&asset.kind)).color(TEXT_DIM));
|
||||
if let (Some(state), Some(path)) = (
|
||||
world.get_resource::<CollaborationState>(),
|
||||
asset.path.as_deref(),
|
||||
) {
|
||||
let status = state.file_status(Path::new(path));
|
||||
let _ = file_status_indicator_ui(ui, &status, Path::new(path));
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -2434,10 +2445,19 @@ fn ensure_material_draft(world: &mut World, path: &str, fallback_label: &str) {
|
||||
if !needs_load {
|
||||
return;
|
||||
}
|
||||
let draft = match MaterialAsset::load_from_path(path) {
|
||||
Ok(asset) => MaterialAssetDraft {
|
||||
let loaded = fs::read_to_string(path)
|
||||
.map_err(|error| format!("could not read {path}: {error}"))
|
||||
.and_then(|text| {
|
||||
let snapshot = FileSnapshot::from_loaded_bytes(Path::new(path), text.as_bytes());
|
||||
ron::from_str::<MaterialAsset>(&text)
|
||||
.map(|asset| (asset, snapshot))
|
||||
.map_err(|error| format!("invalid material RON in {path}: {error}"))
|
||||
});
|
||||
let draft = match loaded {
|
||||
Ok((asset, disk_snapshot)) => MaterialAssetDraft {
|
||||
path: path.to_string(),
|
||||
asset,
|
||||
disk_snapshot,
|
||||
error: None,
|
||||
},
|
||||
Err(error) => MaterialAssetDraft {
|
||||
@@ -2450,6 +2470,8 @@ fn ensure_material_draft(world: &mut World, path: &str, fallback_label: &str) {
|
||||
render_state: shared::MaterialRenderState::default(),
|
||||
material: MaterialDesc::default(),
|
||||
},
|
||||
disk_snapshot: FileSnapshot::capture(Path::new(path))
|
||||
.unwrap_or_else(|_| FileSnapshot::missing()),
|
||||
error: Some(error),
|
||||
},
|
||||
};
|
||||
@@ -2467,17 +2489,23 @@ fn save_material_draft(world: &mut World) {
|
||||
let result = ron::ser::to_string_pretty(&draft.asset, ron::ser::PrettyConfig::default())
|
||||
.map_err(|error| format!("could not serialize material {}: {error}", draft.path))
|
||||
.and_then(|text| {
|
||||
fs::write(&draft.path, text)
|
||||
.map_err(|error| format!("could not write material {}: {error}", draft.path))
|
||||
publish_authored_file(
|
||||
world,
|
||||
Path::new(&draft.path),
|
||||
text.as_bytes(),
|
||||
&draft.disk_snapshot,
|
||||
FileWriteIntent::Material,
|
||||
)
|
||||
});
|
||||
match result {
|
||||
Ok(()) => {
|
||||
Ok(disk_snapshot) => {
|
||||
if let Some(current) = world
|
||||
.resource_mut::<AssetBrowserUiState>()
|
||||
.material_draft
|
||||
.as_mut()
|
||||
{
|
||||
current.error = None;
|
||||
current.disk_snapshot = disk_snapshot;
|
||||
}
|
||||
world.resource_mut::<EditorAssets>().refresh();
|
||||
invalidate_on_catalog_refresh(world);
|
||||
@@ -2556,8 +2584,13 @@ fn create_material_instance_from_base(world: &mut World, base_path: &str, base_l
|
||||
let result = ron::ser::to_string_pretty(&instance, ron::ser::PrettyConfig::default())
|
||||
.map_err(|error| format!("could not serialize material instance: {error}"))
|
||||
.and_then(|text| {
|
||||
fs::write(&path, text)
|
||||
.map_err(|error| format!("could not write {}: {error}", path.display()))
|
||||
publish_authored_file(
|
||||
world,
|
||||
&path,
|
||||
text.as_bytes(),
|
||||
&FileSnapshot::missing(),
|
||||
FileWriteIntent::MaterialInstance,
|
||||
)
|
||||
});
|
||||
if let Err(error) = result {
|
||||
world.resource_mut::<SceneIo>().status = error;
|
||||
@@ -2845,10 +2878,19 @@ fn ensure_material_instance_draft(world: &mut World, path: &str, fallback_label:
|
||||
if !needs_load {
|
||||
return;
|
||||
}
|
||||
let draft = match MaterialInstanceAsset::load_from_path(path) {
|
||||
Ok(asset) => MaterialInstanceAssetDraft {
|
||||
let loaded = fs::read_to_string(path)
|
||||
.map_err(|error| format!("could not read {path}: {error}"))
|
||||
.and_then(|text| {
|
||||
let snapshot = FileSnapshot::from_loaded_bytes(Path::new(path), text.as_bytes());
|
||||
ron::from_str::<MaterialInstanceAsset>(&text)
|
||||
.map(|asset| (asset, snapshot))
|
||||
.map_err(|error| format!("invalid material-instance RON in {path}: {error}"))
|
||||
});
|
||||
let draft = match loaded {
|
||||
Ok((asset, disk_snapshot)) => MaterialInstanceAssetDraft {
|
||||
path: path.to_string(),
|
||||
asset,
|
||||
disk_snapshot,
|
||||
error: None,
|
||||
},
|
||||
Err(error) => MaterialInstanceAssetDraft {
|
||||
@@ -2860,6 +2902,8 @@ fn ensure_material_instance_draft(world: &mut World, path: &str, fallback_label:
|
||||
parameters: Vec::new(),
|
||||
textures: Vec::new(),
|
||||
},
|
||||
disk_snapshot: FileSnapshot::capture(Path::new(path))
|
||||
.unwrap_or_else(|_| FileSnapshot::missing()),
|
||||
error: Some(error),
|
||||
},
|
||||
};
|
||||
@@ -2884,18 +2928,24 @@ fn save_material_instance_draft(world: &mut World) {
|
||||
ron::ser::to_string_pretty(&draft.asset, ron::ser::PrettyConfig::default())
|
||||
.map_err(|error| format!("could not serialize material instance: {error}"))
|
||||
.and_then(|text| {
|
||||
fs::write(&draft.path, text)
|
||||
.map_err(|error| format!("could not write {}: {error}", draft.path))
|
||||
publish_authored_file(
|
||||
world,
|
||||
Path::new(&draft.path),
|
||||
text.as_bytes(),
|
||||
&draft.disk_snapshot,
|
||||
FileWriteIntent::MaterialInstance,
|
||||
)
|
||||
})
|
||||
};
|
||||
match result {
|
||||
Ok(()) => {
|
||||
Ok(disk_snapshot) => {
|
||||
if let Some(current) = world
|
||||
.resource_mut::<AssetBrowserUiState>()
|
||||
.material_instance_draft
|
||||
.as_mut()
|
||||
{
|
||||
current.error = None;
|
||||
current.disk_snapshot = disk_snapshot;
|
||||
}
|
||||
world.resource_mut::<EditorAssets>().refresh();
|
||||
invalidate_on_catalog_refresh(world);
|
||||
@@ -4380,10 +4430,181 @@ fn dedup_strings(values: &mut Vec<String>) {
|
||||
values.retain(|value| seen.insert(value.clone()));
|
||||
}
|
||||
|
||||
pub(crate) fn validate_material_conflict_destination(
|
||||
world: &World,
|
||||
destination: &Path,
|
||||
) -> Result<String, String> {
|
||||
let root = PathBuf::from(&world.resource::<crate::project_io::ProjectWorkspace>().root);
|
||||
let root = root.canonicalize().unwrap_or(root);
|
||||
let absolute = if destination.is_absolute() {
|
||||
destination.to_path_buf()
|
||||
} else {
|
||||
root.join(destination)
|
||||
};
|
||||
let absolute = absolute
|
||||
.parent()
|
||||
.and_then(|parent| parent.canonicalize().ok())
|
||||
.and_then(|parent| destination.file_name().map(|name| parent.join(name)))
|
||||
.unwrap_or(absolute);
|
||||
let relative = absolute.strip_prefix(&root).map_err(|_| {
|
||||
format!(
|
||||
"Material assets must stay inside {}",
|
||||
root.join("assets").display()
|
||||
)
|
||||
})?;
|
||||
if !relative.starts_with("assets") {
|
||||
return Err(format!(
|
||||
"Material assets must stay inside {}",
|
||||
root.join("assets").display()
|
||||
));
|
||||
}
|
||||
Ok(relative.to_string_lossy().replace('\\', "/"))
|
||||
}
|
||||
|
||||
pub(crate) fn reload_material_after_file_conflict(
|
||||
world: &mut World,
|
||||
path: &Path,
|
||||
intent: &FileWriteIntent,
|
||||
) -> Result<String, String> {
|
||||
let path = path.to_string_lossy();
|
||||
{
|
||||
let mut state = world.resource_mut::<AssetBrowserUiState>();
|
||||
match intent {
|
||||
FileWriteIntent::Material => {
|
||||
if state
|
||||
.material_draft
|
||||
.as_ref()
|
||||
.is_some_and(|draft| draft.path == path)
|
||||
{
|
||||
state.material_draft = None;
|
||||
}
|
||||
}
|
||||
FileWriteIntent::MaterialInstance => {
|
||||
if state
|
||||
.material_instance_draft
|
||||
.as_ref()
|
||||
.is_some_and(|draft| draft.path == path)
|
||||
{
|
||||
state.material_instance_draft = None;
|
||||
}
|
||||
}
|
||||
_ => return Err("the conflict is not an editable material document".into()),
|
||||
}
|
||||
}
|
||||
world.resource_mut::<EditorAssets>().refresh();
|
||||
invalidate_on_catalog_refresh(world);
|
||||
Ok(format!("Reloaded {} from disk", path))
|
||||
}
|
||||
|
||||
pub(crate) fn adopt_material_conflict_save_as(
|
||||
world: &mut World,
|
||||
original_path: &Path,
|
||||
catalog_path: String,
|
||||
disk_snapshot: FileSnapshot,
|
||||
intent: &FileWriteIntent,
|
||||
) -> Result<String, String> {
|
||||
let original_path = original_path.to_string_lossy();
|
||||
{
|
||||
let mut state = world.resource_mut::<AssetBrowserUiState>();
|
||||
match intent {
|
||||
FileWriteIntent::Material => {
|
||||
if let Some(draft) = state
|
||||
.material_draft
|
||||
.as_mut()
|
||||
.filter(|draft| draft.path == original_path)
|
||||
{
|
||||
draft.path.clone_from(&catalog_path);
|
||||
draft.disk_snapshot = disk_snapshot;
|
||||
draft.error = None;
|
||||
} else {
|
||||
let asset = MaterialAsset::load_from_path(&catalog_path)?;
|
||||
state.material_draft = Some(MaterialAssetDraft {
|
||||
path: catalog_path.clone(),
|
||||
asset,
|
||||
disk_snapshot,
|
||||
error: None,
|
||||
});
|
||||
}
|
||||
}
|
||||
FileWriteIntent::MaterialInstance => {
|
||||
if let Some(draft) = state
|
||||
.material_instance_draft
|
||||
.as_mut()
|
||||
.filter(|draft| draft.path == original_path)
|
||||
{
|
||||
draft.path.clone_from(&catalog_path);
|
||||
draft.disk_snapshot = disk_snapshot;
|
||||
draft.error = None;
|
||||
} else {
|
||||
let asset = MaterialInstanceAsset::load_from_path(&catalog_path)?;
|
||||
state.material_instance_draft = Some(MaterialInstanceAssetDraft {
|
||||
path: catalog_path.clone(),
|
||||
asset,
|
||||
disk_snapshot,
|
||||
error: None,
|
||||
});
|
||||
}
|
||||
}
|
||||
_ => return Err("the conflict is not an editable material document".into()),
|
||||
}
|
||||
}
|
||||
{
|
||||
let mut assets = world.resource_mut::<EditorAssets>();
|
||||
assets.refresh();
|
||||
assets.select(AssetSelection::File(catalog_path.clone()));
|
||||
}
|
||||
invalidate_on_catalog_refresh(world);
|
||||
Ok(format!("Saved material copy to {catalog_path}"))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn material_apply_refuses_an_external_revision() {
|
||||
let root = std::env::temp_dir().join(format!(
|
||||
"blacksite-material-external-write-{}",
|
||||
uuid::Uuid::new_v4()
|
||||
));
|
||||
let path = root.join("assets/materials/test.ron");
|
||||
fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
fs::write(&path, b"loaded").unwrap();
|
||||
let disk_snapshot = FileSnapshot::capture(&path).unwrap();
|
||||
let draft = MaterialAssetDraft {
|
||||
path: path.to_string_lossy().into_owned(),
|
||||
asset: MaterialAsset {
|
||||
schema_version: shared::MATERIAL_ASSET_SCHEMA_VERSION,
|
||||
label: "Test".into(),
|
||||
shader: None,
|
||||
shader_ref: None,
|
||||
render_state: shared::MaterialRenderState::default(),
|
||||
material: MaterialDesc::default(),
|
||||
},
|
||||
disk_snapshot,
|
||||
error: None,
|
||||
};
|
||||
let state = AssetBrowserUiState {
|
||||
material_draft: Some(draft),
|
||||
..Default::default()
|
||||
};
|
||||
let mut world = World::new();
|
||||
world.insert_resource(state);
|
||||
world.insert_resource(SceneIo::default());
|
||||
fs::write(&path, b"external").unwrap();
|
||||
|
||||
save_material_draft(&mut world);
|
||||
|
||||
assert_eq!(fs::read(&path).unwrap(), b"external");
|
||||
assert!(world
|
||||
.resource::<AssetBrowserUiState>()
|
||||
.material_draft
|
||||
.as_ref()
|
||||
.and_then(|draft| draft.error.as_deref())
|
||||
.is_some_and(|error| error.contains("changed outside Blacksite")));
|
||||
fs::remove_dir_all(root).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn audio_filter_matches_only_audio_clips() {
|
||||
let audio = EditorAsset {
|
||||
|
||||
@@ -7,6 +7,7 @@ use shared::{MaterialAsset, MaterialInstanceAsset};
|
||||
|
||||
use crate::asset_db::ImportSettings;
|
||||
use crate::assets::{AssetSelection, ASSETS_ROOT, BUILTINS_FOLDER};
|
||||
use crate::project::collaboration::FileSnapshot;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum AssetBrowserView {
|
||||
@@ -69,6 +70,7 @@ pub(crate) struct ImportSettingsDraft {
|
||||
pub(crate) struct MaterialAssetDraft {
|
||||
pub(crate) path: String,
|
||||
pub(crate) asset: MaterialAsset,
|
||||
pub(crate) disk_snapshot: FileSnapshot,
|
||||
pub(crate) error: Option<String>,
|
||||
}
|
||||
|
||||
@@ -76,6 +78,7 @@ pub(crate) struct MaterialAssetDraft {
|
||||
pub(crate) struct MaterialInstanceAssetDraft {
|
||||
pub(crate) path: String,
|
||||
pub(crate) asset: MaterialInstanceAsset,
|
||||
pub(crate) disk_snapshot: FileSnapshot,
|
||||
pub(crate) error: Option<String>,
|
||||
}
|
||||
|
||||
|
||||
@@ -39,6 +39,10 @@ use crate::project_io::UserPreferences;
|
||||
use crate::selection::SelectedEntity;
|
||||
use crate::state::EditorMode;
|
||||
|
||||
pub(crate) use asset_browser::{
|
||||
adopt_material_conflict_save_as, reload_material_after_file_conflict,
|
||||
validate_material_conflict_destination,
|
||||
};
|
||||
pub use build::BuildPanel;
|
||||
pub use diagnostics::{BrushDiagnosticsPanel, DiagnosticsPanel};
|
||||
pub use layout::LayoutSaveTimer;
|
||||
@@ -215,6 +219,8 @@ impl UiState {
|
||||
project_settings_window(world, ctx, &mut panel);
|
||||
});
|
||||
|
||||
crate::collaboration::file_conflict_modal(world, ctx);
|
||||
|
||||
if ctx.input(|input| input.key_pressed(egui::Key::F1)) {
|
||||
world.resource_mut::<ViewportUiState>().shortcuts_open = true;
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ use egui_phosphor_icons::icons;
|
||||
|
||||
use crate::history::EditorHistory;
|
||||
use crate::operators::ActiveOperator;
|
||||
use crate::project::collaboration::{file_status_indicator_ui, CollaborationState};
|
||||
use crate::scene_io::SceneIo;
|
||||
use crate::state::{EditorMode, PlayPaused};
|
||||
|
||||
@@ -47,6 +48,16 @@ pub fn status_bar_ui(
|
||||
.on_hover_text(status);
|
||||
},
|
||||
|ui| {
|
||||
if let (Some(state), Some(path)) = (
|
||||
world.get_resource::<CollaborationState>(),
|
||||
world.resource::<SceneIo>().active_path.as_deref(),
|
||||
) {
|
||||
let status = state.file_status(path);
|
||||
if status.indicator().is_some() {
|
||||
let _ = file_status_indicator_ui(ui, &status, path);
|
||||
ui.separator();
|
||||
}
|
||||
}
|
||||
let (mode_icon, mode_label, mode_color) = match mode {
|
||||
EditorMode::Editing => (icons::PENCIL_SIMPLE, "EDIT", ACCENT),
|
||||
EditorMode::Playing => {
|
||||
|
||||
@@ -227,17 +227,22 @@ impl Default for InputSettings {
|
||||
|
||||
/// Loads settings from disk, falling back to defaults.
|
||||
pub fn load_project_settings_from_path(path: &str) -> ProjectSettings {
|
||||
load_project_settings_with_source(path).0
|
||||
}
|
||||
|
||||
/// Loads settings plus the exact source text used when the file was readable.
|
||||
pub fn load_project_settings_with_source(path: &str) -> (ProjectSettings, Option<String>) {
|
||||
match std::fs::read_to_string(path) {
|
||||
Ok(contents) => match ron::from_str(&contents) {
|
||||
Ok(settings) => settings,
|
||||
Ok(settings) => (settings, Some(contents)),
|
||||
Err(error) => {
|
||||
warn!("Failed to parse {path}: {error}; using defaults");
|
||||
ProjectSettings::default()
|
||||
(ProjectSettings::default(), Some(contents))
|
||||
}
|
||||
},
|
||||
Err(error) => {
|
||||
warn!("Could not read {path}: {error}; using defaults");
|
||||
ProjectSettings::default()
|
||||
(ProjectSettings::default(), None)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -266,6 +271,27 @@ mod tests {
|
||||
assert_eq!(parsed.rendering.gi_mode, settings.rendering.gi_mode);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn settings_load_returns_the_exact_source_for_revision_guards() {
|
||||
let root = std::env::temp_dir().join(format!(
|
||||
"blacksite-settings-source-{}",
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_nanos()
|
||||
));
|
||||
let path = root.join("project.ron");
|
||||
std::fs::create_dir_all(&root).unwrap();
|
||||
let source = save_project_settings_to_string(&ProjectSettings::default()).unwrap();
|
||||
std::fs::write(&path, &source).unwrap();
|
||||
|
||||
let (settings, loaded_source) = load_project_settings_with_source(path.to_str().unwrap());
|
||||
|
||||
assert_eq!(settings.name, ProjectSettings::default().name);
|
||||
assert_eq!(loaded_source.as_deref(), Some(source.as_str()));
|
||||
std::fs::remove_dir_all(root).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legacy_manifest_defaults_project_identity_fields() {
|
||||
let legacy = r#"(
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use bevy::prelude::*;
|
||||
|
||||
use crate::{
|
||||
load_project_settings_from_path, save_project_settings_to_string, PhysicsSettings,
|
||||
load_project_settings_with_source, save_project_settings_to_string, PhysicsSettings,
|
||||
ProjectSettings, DEFAULT_PROJECT_PATH,
|
||||
};
|
||||
|
||||
@@ -56,6 +56,8 @@ impl SimTuning {
|
||||
pub struct ProjectSettingsIo {
|
||||
pub path: String,
|
||||
pub dirty: bool,
|
||||
/// Exact source loaded or last saved by this process; collaboration guards hash it.
|
||||
pub loaded_source: Option<String>,
|
||||
}
|
||||
|
||||
impl Default for ProjectSettingsIo {
|
||||
@@ -63,6 +65,7 @@ impl Default for ProjectSettingsIo {
|
||||
Self {
|
||||
path: DEFAULT_PROJECT_PATH.into(),
|
||||
dirty: false,
|
||||
loaded_source: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -91,8 +94,9 @@ impl Plugin for ProjectSettingsPlugin {
|
||||
}
|
||||
}
|
||||
|
||||
fn load_settings(mut commands: Commands, io: Res<ProjectSettingsIo>) {
|
||||
let settings = load_project_settings_from_path(&io.path);
|
||||
fn load_settings(mut commands: Commands, mut io: ResMut<ProjectSettingsIo>) {
|
||||
let (settings, source) = load_project_settings_with_source(&io.path);
|
||||
io.loaded_source = source;
|
||||
let tuning = SimTuning::from_physics(&settings.physics);
|
||||
commands.insert_resource(settings);
|
||||
commands.insert_resource(tuning);
|
||||
@@ -103,13 +107,17 @@ pub fn sync_sim_tuning(settings: &ProjectSettings, mut tuning: ResMut<SimTuning>
|
||||
*tuning = SimTuning::from_physics(&settings.physics);
|
||||
}
|
||||
|
||||
/// Persists settings to the path in [`ProjectSettingsIo`].
|
||||
/// Low-level unconditional persistence for non-editor callers.
|
||||
///
|
||||
/// The editor uses its guarded authored-file publication path instead so external revisions cannot
|
||||
/// be overwritten.
|
||||
pub fn save_project_settings(
|
||||
settings: &ProjectSettings,
|
||||
io: &mut ProjectSettingsIo,
|
||||
) -> Result<(), String> {
|
||||
let text = save_project_settings_to_string(settings).map_err(|error| error.to_string())?;
|
||||
std::fs::write(&io.path, text).map_err(|error| error.to_string())?;
|
||||
std::fs::write(&io.path, &text).map_err(|error| error.to_string())?;
|
||||
io.loaded_source = Some(text);
|
||||
io.dirty = false;
|
||||
Ok(())
|
||||
}
|
||||
Reference in new issue
Block a user