Skip to main content

libobs_simple/
scene_collection.rs

1//! Versioned application-level scene collection persistence.
2//!
3//! This is intentionally not an OBS Studio frontend project-file parser. It persists the subset
4//! owned by libobs-rs's managed scene/source model: shared sources, settings/hotkeys, filters,
5//! scenes, native groups, item ordering and complete managed scene-item state.
6
7use std::{
8    collections::{BTreeMap, HashMap, HashSet},
9    fmt,
10    fs::{self, File},
11    io::Write,
12    path::{Path, PathBuf},
13};
14
15use libobs_wrapper::{
16    context::ObsContext,
17    data::{object::ObsObjectTrait, ObsData, ObsDataGetters},
18    enums::{ObsAlignment, ObsBlendMethod, ObsBlendMode, ObsBoundsType, ObsScaleType},
19    graphics::Vec2,
20    scenes::{
21        ObsSceneItemCrop, ObsSceneItemStateSnapshot, ObsSceneItemTransformSnapshot, ObsSceneRef,
22        SceneItemTrait,
23    },
24    sources::{ObsFilterRef, ObsSourceRef, ObsSourceTrait},
25    utils::ObsError,
26};
27use num_traits::FromPrimitive;
28use serde::{Deserialize, Serialize};
29use serde_json::Value;
30
31pub const SCENE_COLLECTION_SCHEMA_VERSION: u32 = 1;
32const REDACTED_SECRET: &str = "__LIBOBS_RS_REDACTED_SECRET__";
33const REDACTED_PATH: &str = "__LIBOBS_RS_REDACTED_PATH__";
34
35#[derive(Debug)]
36pub enum SceneCollectionError {
37    Obs(ObsError),
38    Io(std::io::Error),
39    Json(serde_json::Error),
40    UnsupportedVersion { found: u32, supported: u32 },
41    InvalidDocument(String),
42}
43
44impl fmt::Display for SceneCollectionError {
45    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
46        match self {
47            Self::Obs(error) => write!(f, "{error}"),
48            Self::Io(error) => write!(f, "scene collection I/O error: {error}"),
49            Self::Json(error) => write!(f, "scene collection JSON error: {error}"),
50            Self::UnsupportedVersion { found, supported } => write!(
51                f,
52                "scene collection schema version {found} is unsupported (current version {supported})"
53            ),
54            Self::InvalidDocument(message) => write!(f, "invalid scene collection: {message}"),
55        }
56    }
57}
58
59impl std::error::Error for SceneCollectionError {}
60
61impl From<ObsError> for SceneCollectionError {
62    fn from(value: ObsError) -> Self {
63        Self::Obs(value)
64    }
65}
66
67impl From<std::io::Error> for SceneCollectionError {
68    fn from(value: std::io::Error) -> Self {
69        Self::Io(value)
70    }
71}
72
73impl From<serde_json::Error> for SceneCollectionError {
74    fn from(value: serde_json::Error) -> Self {
75        Self::Json(value)
76    }
77}
78
79#[derive(Debug, Clone, Copy, PartialEq, Eq)]
80pub enum RestoreMode {
81    /// Abort on missing source/filter plugins and on missing machine-local files discovered in
82    /// obvious path/file settings.
83    Strict,
84    /// Restore everything possible and return diagnostics for skipped/degraded objects.
85    BestEffort,
86}
87
88#[derive(Debug, Clone, Copy, PartialEq, Eq)]
89pub enum SecretHandling {
90    Include,
91    Redact,
92}
93
94#[derive(Debug, Clone, Copy, PartialEq, Eq)]
95pub enum MachinePathHandling {
96    Include,
97    RedactAbsolute,
98}
99
100#[derive(Debug, Clone, Copy, PartialEq, Eq)]
101pub struct SceneCollectionExportPolicy {
102    pub secrets: SecretHandling,
103    pub machine_paths: MachinePathHandling,
104}
105
106impl SceneCollectionExportPolicy {
107    pub const fn include_all() -> Self {
108        Self {
109            secrets: SecretHandling::Include,
110            machine_paths: MachinePathHandling::Include,
111        }
112    }
113
114    pub const fn portable_redacted() -> Self {
115        Self {
116            secrets: SecretHandling::Redact,
117            machine_paths: MachinePathHandling::RedactAbsolute,
118        }
119    }
120}
121
122impl Default for SceneCollectionExportPolicy {
123    fn default() -> Self {
124        Self::portable_redacted()
125    }
126}
127
128#[derive(Debug, Clone, PartialEq, Eq)]
129pub struct ExportRedaction {
130    pub object_id: String,
131    pub setting_path: String,
132    pub reason: &'static str,
133}
134
135#[derive(Debug, Clone)]
136pub struct SceneCollectionExport {
137    pub json: String,
138    pub redactions: Vec<ExportRedaction>,
139}
140
141#[derive(Debug, Clone, PartialEq, Eq)]
142pub enum RestoreDiagnosticKind {
143    MissingSourcePlugin,
144    MissingFilterPlugin,
145    MissingFile,
146    SkippedSceneItem,
147    RedactedSetting,
148}
149
150#[derive(Debug, Clone, PartialEq, Eq)]
151pub struct RestoreDiagnostic {
152    pub kind: RestoreDiagnosticKind,
153    pub object_id: String,
154    pub message: String,
155}
156
157#[derive(Debug)]
158pub struct RestoredSceneCollection {
159    /// Sources are retained here even when a persisted source is not currently present in a scene.
160    pub sources: HashMap<String, ObsSourceRef>,
161    pub scenes: HashMap<String, ObsSceneRef>,
162    pub diagnostics: Vec<RestoreDiagnostic>,
163}
164
165#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
166pub struct SceneCollectionDocument {
167    pub version: u32,
168    #[serde(default)]
169    pub name: Option<String>,
170    pub sources: Vec<PersistedSource>,
171    pub scenes: Vec<PersistedScene>,
172    #[serde(default, flatten)]
173    pub extra: BTreeMap<String, Value>,
174}
175
176#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
177pub struct PersistedSource {
178    /// Stable document identity. Captures use libobs's persistent source UUID.
179    pub id: String,
180    pub plugin_id: String,
181    pub name: String,
182    pub settings: Value,
183    #[serde(default)]
184    pub hotkeys: Value,
185    #[serde(default)]
186    pub filters: Vec<PersistedFilter>,
187    #[serde(default, flatten)]
188    pub extra: BTreeMap<String, Value>,
189}
190
191#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
192pub struct PersistedFilter {
193    pub id: String,
194    pub plugin_id: String,
195    pub name: String,
196    pub settings: Value,
197    #[serde(default)]
198    pub hotkeys: Value,
199    #[serde(default, flatten)]
200    pub extra: BTreeMap<String, Value>,
201}
202
203#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
204pub struct PersistedScene {
205    pub id: String,
206    pub name: String,
207    /// Native bottom-to-top order.
208    pub items: Vec<PersistedSceneNode>,
209    #[serde(default, flatten)]
210    pub extra: BTreeMap<String, Value>,
211}
212
213#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
214#[serde(tag = "kind", rename_all = "snake_case")]
215pub enum PersistedSceneNode {
216    Source(PersistedSourceItem),
217    Group(PersistedGroup),
218}
219
220#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
221pub struct PersistedSourceItem {
222    /// Stable document item identity. It is not a native scene-item pointer/ID.
223    pub id: String,
224    pub source_id: String,
225    pub state: PersistedSceneItemState,
226    #[serde(default, flatten)]
227    pub extra: BTreeMap<String, Value>,
228}
229
230#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
231pub struct PersistedGroup {
232    /// Stable group-source UUID at capture time.
233    pub id: String,
234    pub name: String,
235    pub state: PersistedSceneItemState,
236    /// OBS's managed group API intentionally supports one group level; nested groups are rejected
237    /// on restore instead of being silently flattened.
238    pub items: Vec<PersistedSourceItem>,
239    #[serde(default, flatten)]
240    pub extra: BTreeMap<String, Value>,
241}
242
243#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
244pub struct PersistedSceneItemState {
245    pub position: [f32; 2],
246    pub scale: [f32; 2],
247    pub alignment: u32,
248    pub rotation: f32,
249    pub bounds: [f32; 2],
250    pub bounds_type: i64,
251    pub bounds_alignment: u32,
252    pub crop_to_bounds: bool,
253    pub crop: [i32; 4],
254    pub scale_filter: i64,
255    pub blend_method: i64,
256    pub blend_mode: i64,
257    pub visible: bool,
258    pub locked: bool,
259    pub order_position: i32,
260}
261
262impl PersistedSceneItemState {
263    fn capture(item: &dyn SceneItemTrait) -> Result<Self, ObsError> {
264        let snapshot = item.state_snapshot()?;
265        Ok(Self::from_snapshot(&snapshot))
266    }
267
268    pub fn from_snapshot(snapshot: &ObsSceneItemStateSnapshot) -> Self {
269        let transform = &snapshot.transform;
270        Self {
271            position: [*transform.position.x(), *transform.position.y()],
272            scale: [*transform.scale.x(), *transform.scale.y()],
273            alignment: transform.alignment.bits(),
274            rotation: transform.rotation,
275            bounds: [*transform.bounds.x(), *transform.bounds.y()],
276            bounds_type: transform.bounds_type as i64,
277            bounds_alignment: transform.bounds_alignment.bits(),
278            crop_to_bounds: transform.crop_to_bounds,
279            crop: [
280                transform.crop.left,
281                transform.crop.top,
282                transform.crop.right,
283                transform.crop.bottom,
284            ],
285            scale_filter: transform.scale_filter as i64,
286            blend_method: transform.blend_method as i64,
287            blend_mode: transform.blend_mode as i64,
288            visible: snapshot.visible,
289            locked: snapshot.locked,
290            order_position: snapshot.order_position,
291        }
292    }
293
294    pub fn to_snapshot(&self) -> Result<ObsSceneItemStateSnapshot, SceneCollectionError> {
295        let bounds_type = ObsBoundsType::from_i64(self.bounds_type).ok_or_else(|| {
296            SceneCollectionError::InvalidDocument(format!(
297                "unknown bounds type {}",
298                self.bounds_type
299            ))
300        })?;
301        let scale_filter = ObsScaleType::from_i64(self.scale_filter).ok_or_else(|| {
302            SceneCollectionError::InvalidDocument(format!(
303                "unknown scale filter {}",
304                self.scale_filter
305            ))
306        })?;
307        let blend_method = ObsBlendMethod::from_i64(self.blend_method).ok_or_else(|| {
308            SceneCollectionError::InvalidDocument(format!(
309                "unknown blend method {}",
310                self.blend_method
311            ))
312        })?;
313        let blend_mode = ObsBlendMode::from_i64(self.blend_mode).ok_or_else(|| {
314            SceneCollectionError::InvalidDocument(format!("unknown blend mode {}", self.blend_mode))
315        })?;
316
317        Ok(ObsSceneItemStateSnapshot {
318            transform: ObsSceneItemTransformSnapshot {
319                position: Vec2::new(self.position[0], self.position[1]),
320                scale: Vec2::new(self.scale[0], self.scale[1]),
321                alignment: ObsAlignment::from_bits_retain(self.alignment),
322                rotation: self.rotation,
323                bounds: Vec2::new(self.bounds[0], self.bounds[1]),
324                bounds_type,
325                bounds_alignment: ObsAlignment::from_bits_retain(self.bounds_alignment),
326                crop_to_bounds: self.crop_to_bounds,
327                crop: ObsSceneItemCrop::new(self.crop[0], self.crop[1], self.crop[2], self.crop[3]),
328                scale_filter,
329                blend_method,
330                blend_mode,
331            },
332            visible: self.visible,
333            locked: self.locked,
334            order_position: self.order_position,
335        })
336    }
337}
338
339#[derive(Debug, Clone)]
340struct SceneHistoryEntry {
341    label: String,
342    before: SceneCollectionDocument,
343    after: SceneCollectionDocument,
344}
345
346/// Undo/redo editor for the persisted scene-collection model.
347///
348/// History stores complete versioned document snapshots rather than runtime/native object IDs.
349/// Item/source/group IDs therefore remain stable across undo/redo. Group/ungroup operations accept
350/// the *post-operation* replacement snapshots, matching libobs's native semantics where ungrouping
351/// creates replacement parent-scene items instead of preserving the old native handles.
352#[derive(Debug, Clone)]
353pub struct SceneCollectionEditor {
354    document: SceneCollectionDocument,
355    undo: Vec<SceneHistoryEntry>,
356    redo: Vec<SceneHistoryEntry>,
357}
358
359impl SceneCollectionEditor {
360    pub fn new(document: SceneCollectionDocument) -> Result<Self, SceneCollectionError> {
361        document.validate_version()?;
362        document.validate_references()?;
363        Ok(Self {
364            document,
365            undo: Vec::new(),
366            redo: Vec::new(),
367        })
368    }
369
370    pub fn document(&self) -> &SceneCollectionDocument {
371        &self.document
372    }
373
374    pub fn into_document(self) -> SceneCollectionDocument {
375        self.document
376    }
377
378    pub fn can_undo(&self) -> bool {
379        !self.undo.is_empty()
380    }
381
382    pub fn can_redo(&self) -> bool {
383        !self.redo.is_empty()
384    }
385
386    pub fn next_undo_label(&self) -> Option<&str> {
387        self.undo.last().map(|entry| entry.label.as_str())
388    }
389
390    pub fn next_redo_label(&self) -> Option<&str> {
391        self.redo.last().map(|entry| entry.label.as_str())
392    }
393
394    pub fn undo(&mut self) -> bool {
395        let Some(entry) = self.undo.pop() else {
396            return false;
397        };
398        self.document = entry.before.clone();
399        self.redo.push(entry);
400        true
401    }
402
403    pub fn redo(&mut self) -> bool {
404        let Some(entry) = self.redo.pop() else {
405            return false;
406        };
407        self.document = entry.after.clone();
408        self.undo.push(entry);
409        true
410    }
411
412    /// Replaces one item's complete persisted transform/visibility/lock/order snapshot.
413    pub fn set_item_state(
414        &mut self,
415        scene_id: &str,
416        item_id: &str,
417        state: PersistedSceneItemState,
418    ) -> Result<(), SceneCollectionError> {
419        self.transact("scene item state", |document| {
420            let item = find_source_item_mut(document, scene_id, item_id)?;
421            item.state = state;
422            Ok(())
423        })
424    }
425
426    /// Reorders one top-level source/group node in the persisted native bottom-to-top order.
427    pub fn move_top_level_item(
428        &mut self,
429        scene_id: &str,
430        item_id: &str,
431        new_index: usize,
432    ) -> Result<(), SceneCollectionError> {
433        self.transact("scene item order", |document| {
434            let scene = find_scene_mut(document, scene_id)?;
435            if new_index >= scene.items.len() {
436                return Err(SceneCollectionError::InvalidDocument(format!(
437                    "top-level order index {new_index} is out of range"
438                )));
439            }
440            let old_index = scene
441                .items
442                .iter()
443                .position(|node| node_id(node) == item_id)
444                .ok_or_else(|| {
445                    SceneCollectionError::InvalidDocument(format!(
446                        "scene '{scene_id}' has no top-level item '{item_id}'"
447                    ))
448                })?;
449            let node = scene.items.remove(old_index);
450            scene.items.insert(new_index, node);
451            for (index, node) in scene.items.iter_mut().enumerate() {
452                node_state_mut(node).order_position = index as i32;
453            }
454            Ok(())
455        })
456    }
457
458    /// Replaces selected top-level source items with the supplied post-grouping snapshot.
459    ///
460    /// `group.items` must contain exactly the selected persistent item IDs. This lets a live editor
461    /// capture libobs's post-reparent child snapshots and record them without pretending native
462    /// scene-item handles survived grouping unchanged.
463    pub fn replace_items_with_group(
464        &mut self,
465        scene_id: &str,
466        selected_item_ids: &[String],
467        group: PersistedGroup,
468    ) -> Result<(), SceneCollectionError> {
469        self.transact("group scene items", |document| {
470            if selected_item_ids.is_empty() {
471                return Err(SceneCollectionError::InvalidDocument(
472                    "cannot create an empty group edit".into(),
473                ));
474            }
475            let selected = selected_item_ids.iter().cloned().collect::<HashSet<_>>();
476            let group_ids = group
477                .items
478                .iter()
479                .map(|item| item.id.clone())
480                .collect::<HashSet<_>>();
481            if selected != group_ids {
482                return Err(SceneCollectionError::InvalidDocument(
483                    "group replacement children must exactly match selected item IDs".into(),
484                ));
485            }
486            let scene = find_scene_mut(document, scene_id)?;
487            if scene.items.iter().any(|node| node_id(node) == group.id) {
488                return Err(SceneCollectionError::InvalidDocument(format!(
489                    "group id '{}' already exists in scene",
490                    group.id
491                )));
492            }
493
494            let mut insertion = None;
495            let mut found = HashSet::new();
496            let mut retained = Vec::with_capacity(scene.items.len());
497            for (index, node) in std::mem::take(&mut scene.items).into_iter().enumerate() {
498                if selected.contains(node_id(&node)) {
499                    if !matches!(node, PersistedSceneNode::Source(_)) {
500                        return Err(SceneCollectionError::InvalidDocument(
501                            "only top-level source items can be grouped".into(),
502                        ));
503                    }
504                    insertion.get_or_insert(index);
505                    found.insert(node_id(&node).to_owned());
506                } else {
507                    retained.push(node);
508                }
509            }
510            if found != selected {
511                return Err(SceneCollectionError::InvalidDocument(
512                    "one or more selected item IDs were not found at scene top level".into(),
513                ));
514            }
515            let insertion = insertion.unwrap_or(retained.len()).min(retained.len());
516            retained.insert(insertion, PersistedSceneNode::Group(group));
517            scene.items = retained;
518            for (index, node) in scene.items.iter_mut().enumerate() {
519                node_state_mut(node).order_position = index as i32;
520            }
521            Ok(())
522        })
523    }
524
525    /// Replaces a group with the post-ungroup replacement item snapshots returned/captured after
526    /// libobs created new parent-scene items.
527    pub fn ungroup_with_replacements(
528        &mut self,
529        scene_id: &str,
530        group_id: &str,
531        replacements: Vec<PersistedSourceItem>,
532    ) -> Result<(), SceneCollectionError> {
533        self.transact("ungroup scene items", |document| {
534            let scene = find_scene_mut(document, scene_id)?;
535            let index = scene
536                .items
537                .iter()
538                .position(|node| node_id(node) == group_id)
539                .ok_or_else(|| {
540                    SceneCollectionError::InvalidDocument(format!(
541                        "scene '{scene_id}' has no group '{group_id}'"
542                    ))
543                })?;
544            let PersistedSceneNode::Group(group) = &scene.items[index] else {
545                return Err(SceneCollectionError::InvalidDocument(format!(
546                    "item '{group_id}' is not a group"
547                )));
548            };
549            let old_ids = group
550                .items
551                .iter()
552                .map(|item| (&item.id, &item.source_id))
553                .collect::<HashSet<_>>();
554            let replacement_ids = replacements
555                .iter()
556                .map(|item| (&item.id, &item.source_id))
557                .collect::<HashSet<_>>();
558            if old_ids != replacement_ids {
559                return Err(SceneCollectionError::InvalidDocument(
560                    "ungroup replacement IDs/sources must match the group's children".into(),
561                ));
562            }
563            scene.items.remove(index);
564            for (offset, replacement) in replacements.into_iter().enumerate() {
565                scene
566                    .items
567                    .insert(index + offset, PersistedSceneNode::Source(replacement));
568            }
569            for (position, node) in scene.items.iter_mut().enumerate() {
570                node_state_mut(node).order_position = position as i32;
571            }
572            Ok(())
573        })
574    }
575
576    fn transact(
577        &mut self,
578        label: &str,
579        edit: impl FnOnce(&mut SceneCollectionDocument) -> Result<(), SceneCollectionError>,
580    ) -> Result<(), SceneCollectionError> {
581        let before = self.document.clone();
582        edit(&mut self.document)?;
583        self.document.validate_references()?;
584        let after = self.document.clone();
585        self.undo.push(SceneHistoryEntry {
586            label: label.to_owned(),
587            before,
588            after,
589        });
590        self.redo.clear();
591        Ok(())
592    }
593}
594
595fn find_scene_mut<'a>(
596    document: &'a mut SceneCollectionDocument,
597    scene_id: &str,
598) -> Result<&'a mut PersistedScene, SceneCollectionError> {
599    document
600        .scenes
601        .iter_mut()
602        .find(|scene| scene.id == scene_id)
603        .ok_or_else(|| {
604            SceneCollectionError::InvalidDocument(format!("unknown scene id '{scene_id}'"))
605        })
606}
607
608fn find_source_item_mut<'a>(
609    document: &'a mut SceneCollectionDocument,
610    scene_id: &str,
611    item_id: &str,
612) -> Result<&'a mut PersistedSourceItem, SceneCollectionError> {
613    let scene = find_scene_mut(document, scene_id)?;
614    for node in &mut scene.items {
615        match node {
616            PersistedSceneNode::Source(item) if item.id == item_id => return Ok(item),
617            PersistedSceneNode::Group(group) => {
618                if let Some(item) = group.items.iter_mut().find(|item| item.id == item_id) {
619                    return Ok(item);
620                }
621            }
622            _ => {}
623        }
624    }
625    Err(SceneCollectionError::InvalidDocument(format!(
626        "scene '{scene_id}' has no source item '{item_id}'"
627    )))
628}
629
630fn node_id(node: &PersistedSceneNode) -> &str {
631    match node {
632        PersistedSceneNode::Source(item) => &item.id,
633        PersistedSceneNode::Group(group) => &group.id,
634    }
635}
636
637fn node_state_mut(node: &mut PersistedSceneNode) -> &mut PersistedSceneItemState {
638    match node {
639        PersistedSceneNode::Source(item) => &mut item.state,
640        PersistedSceneNode::Group(group) => &mut group.state,
641    }
642}
643
644impl SceneCollectionDocument {
645    pub fn new(name: Option<String>) -> Self {
646        Self {
647            version: SCENE_COLLECTION_SCHEMA_VERSION,
648            name,
649            sources: Vec::new(),
650            scenes: Vec::new(),
651            extra: BTreeMap::new(),
652        }
653    }
654
655    /// Captures every scene managed by `context`.
656    pub fn capture_context(context: &ObsContext) -> Result<Self, SceneCollectionError> {
657        Self::capture(&context.scenes()?)
658    }
659
660    /// Captures the supplied managed scenes and every shared source/filter they reference.
661    pub fn capture(scenes: &[ObsSceneRef]) -> Result<Self, SceneCollectionError> {
662        let mut document = Self::new(None);
663        let mut sources = HashMap::<String, PersistedSource>::new();
664
665        for scene in scenes {
666            for source in scene.managed_sources()? {
667                let persisted = capture_source(source.as_ref())?;
668                sources.entry(persisted.id.clone()).or_insert(persisted);
669            }
670            document.scenes.push(capture_scene(scene)?);
671        }
672
673        document.sources = sources.into_values().collect();
674        document.sources.sort_by(|a, b| a.id.cmp(&b.id));
675        Ok(document)
676    }
677
678    pub fn from_json(json: &str) -> Result<Self, SceneCollectionError> {
679        let document: Self = serde_json::from_str(json)?;
680        document.validate_version()?;
681        document.validate_references()?;
682        Ok(document)
683    }
684
685    pub fn load(path: impl AsRef<Path>) -> Result<Self, SceneCollectionError> {
686        Self::from_json(&fs::read_to_string(path)?)
687    }
688
689    pub fn to_json(&self) -> Result<String, SceneCollectionError> {
690        self.validate_version()?;
691        self.validate_references()?;
692        Ok(serde_json::to_string_pretty(self)?)
693    }
694
695    /// Serializes using an explicit secret/path policy. Unknown JSON fields captured through
696    /// `extra` maps are preserved.
697    pub fn export(
698        &self,
699        policy: SceneCollectionExportPolicy,
700    ) -> Result<SceneCollectionExport, SceneCollectionError> {
701        self.validate_version()?;
702        self.validate_references()?;
703        let mut sanitized = self.clone();
704        let mut redactions = Vec::new();
705        for source in &mut sanitized.sources {
706            sanitize_value(
707                &source.id,
708                "settings",
709                &mut source.settings,
710                policy,
711                &mut redactions,
712            );
713            sanitize_value(
714                &source.id,
715                "hotkeys",
716                &mut source.hotkeys,
717                policy,
718                &mut redactions,
719            );
720            for filter in &mut source.filters {
721                sanitize_value(
722                    &filter.id,
723                    "settings",
724                    &mut filter.settings,
725                    policy,
726                    &mut redactions,
727                );
728                sanitize_value(
729                    &filter.id,
730                    "hotkeys",
731                    &mut filter.hotkeys,
732                    policy,
733                    &mut redactions,
734                );
735            }
736        }
737        Ok(SceneCollectionExport {
738            json: serde_json::to_string_pretty(&sanitized)?,
739            redactions,
740        })
741    }
742
743    /// Writes through a same-directory temporary file so serialization/write failures never
744    /// truncate an existing collection. On platforms where rename-over-existing is unavailable,
745    /// the old file is first moved to a backup and restored on replacement failure.
746    pub fn save_atomic(
747        &self,
748        path: impl AsRef<Path>,
749        policy: SceneCollectionExportPolicy,
750    ) -> Result<Vec<ExportRedaction>, SceneCollectionError> {
751        let path = path.as_ref();
752        let export = self.export(policy)?;
753        atomic_write(path, export.json.as_bytes())?;
754        Ok(export.redactions)
755    }
756
757    pub fn restore(
758        &self,
759        context: &mut ObsContext,
760        mode: RestoreMode,
761    ) -> Result<RestoredSceneCollection, SceneCollectionError> {
762        self.validate_version()?;
763        self.validate_references()?;
764
765        let mut diagnostics = Vec::new();
766        let mut sources = HashMap::<String, ObsSourceRef>::new();
767
768        for persisted in &self.sources {
769            let Some(source_type) = context.source_type(&persisted.plugin_id)? else {
770                let diagnostic = RestoreDiagnostic {
771                    kind: RestoreDiagnosticKind::MissingSourcePlugin,
772                    object_id: persisted.id.clone(),
773                    message: format!(
774                        "source '{}' requires missing OBS plugin type '{}'",
775                        persisted.name, persisted.plugin_id
776                    ),
777                };
778                if mode == RestoreMode::Strict {
779                    return Err(SceneCollectionError::InvalidDocument(diagnostic.message));
780                }
781                diagnostics.push(diagnostic);
782                continue;
783            };
784
785            inspect_missing_files(&persisted.id, &persisted.settings, mode, &mut diagnostics)?;
786            inspect_redacted_fields(&persisted.id, &persisted.settings, &mut diagnostics);
787            let settings = obs_data_from_value(context, &persisted.settings)?.into_immutable();
788            let hotkeys = obs_data_from_value(context, &persisted.hotkeys)?.into_immutable();
789            let source = ObsSourceRef::new(
790                source_type.id(),
791                persisted.name.as_str(),
792                Some(settings),
793                Some(hotkeys),
794                context.runtime().clone(),
795            )?;
796
797            for filter in &persisted.filters {
798                let Some(filter_type) = context.source_type(&filter.plugin_id)? else {
799                    let diagnostic = RestoreDiagnostic {
800                        kind: RestoreDiagnosticKind::MissingFilterPlugin,
801                        object_id: filter.id.clone(),
802                        message: format!(
803                            "filter '{}' requires missing OBS plugin type '{}'",
804                            filter.name, filter.plugin_id
805                        ),
806                    };
807                    if mode == RestoreMode::Strict {
808                        return Err(SceneCollectionError::InvalidDocument(diagnostic.message));
809                    }
810                    diagnostics.push(diagnostic);
811                    continue;
812                };
813                inspect_missing_files(&filter.id, &filter.settings, mode, &mut diagnostics)?;
814                inspect_redacted_fields(&filter.id, &filter.settings, &mut diagnostics);
815                let settings = obs_data_from_value(context, &filter.settings)?.into_immutable();
816                let hotkeys = obs_data_from_value(context, &filter.hotkeys)?.into_immutable();
817                let filter_ref = ObsFilterRef::new(
818                    filter_type.id(),
819                    filter.name.as_str(),
820                    Some(settings),
821                    Some(hotkeys),
822                    context.runtime().clone(),
823                )?;
824                source.apply_filter(&filter_ref)?;
825            }
826            sources.insert(persisted.id.clone(), source);
827        }
828
829        let mut restored_scenes = HashMap::new();
830        for persisted_scene in &self.scenes {
831            let mut scene = context.scene(persisted_scene.name.as_str(), None)?;
832            restore_scene_items(
833                &mut scene,
834                &persisted_scene.items,
835                &sources,
836                mode,
837                &mut diagnostics,
838            )?;
839            restored_scenes.insert(persisted_scene.id.clone(), scene);
840        }
841
842        Ok(RestoredSceneCollection {
843            sources,
844            scenes: restored_scenes,
845            diagnostics,
846        })
847    }
848
849    fn validate_version(&self) -> Result<(), SceneCollectionError> {
850        if self.version != SCENE_COLLECTION_SCHEMA_VERSION {
851            return Err(SceneCollectionError::UnsupportedVersion {
852                found: self.version,
853                supported: SCENE_COLLECTION_SCHEMA_VERSION,
854            });
855        }
856        Ok(())
857    }
858
859    fn validate_references(&self) -> Result<(), SceneCollectionError> {
860        let mut source_ids = HashSet::new();
861        for source in &self.sources {
862            if !source_ids.insert(source.id.as_str()) {
863                return Err(SceneCollectionError::InvalidDocument(format!(
864                    "duplicate source id '{}'",
865                    source.id
866                )));
867            }
868        }
869        let mut scene_ids = HashSet::new();
870        let mut item_ids = HashSet::new();
871        for scene in &self.scenes {
872            if !scene_ids.insert(scene.id.as_str()) {
873                return Err(SceneCollectionError::InvalidDocument(format!(
874                    "duplicate scene id '{}'",
875                    scene.id
876                )));
877            }
878            for node in &scene.items {
879                match node {
880                    PersistedSceneNode::Source(item) => {
881                        validate_item(item, &source_ids, &mut item_ids)?;
882                    }
883                    PersistedSceneNode::Group(group) => {
884                        if !item_ids.insert(group.id.as_str()) {
885                            return Err(SceneCollectionError::InvalidDocument(format!(
886                                "duplicate scene item/group id '{}'",
887                                group.id
888                            )));
889                        }
890                        for item in &group.items {
891                            validate_item(item, &source_ids, &mut item_ids)?;
892                        }
893                    }
894                }
895            }
896        }
897        Ok(())
898    }
899}
900
901fn capture_source(source: &dyn ObsSourceTrait) -> Result<PersistedSource, SceneCollectionError> {
902    let id = source.persistent_uuid()?;
903    let settings = serde_json::from_str(&source.settings()?.get_json()?)?;
904    let hotkeys = serde_json::from_str(&source.hotkey_data()?.get_json()?)?;
905    let mut filters = Vec::new();
906    for guard in source.get_active_filters()? {
907        let filter = guard.get_inner();
908        filters.push(PersistedFilter {
909            id: filter.persistent_uuid()?,
910            plugin_id: filter.id().to_string(),
911            name: filter.name().to_string(),
912            settings: serde_json::from_str(&filter.settings()?.get_json()?)?,
913            hotkeys: serde_json::from_str(&filter.hotkey_data()?.get_json()?)?,
914            extra: BTreeMap::new(),
915        });
916    }
917    Ok(PersistedSource {
918        id,
919        plugin_id: source.id().to_string(),
920        name: source.name().to_string(),
921        settings,
922        hotkeys,
923        filters,
924        extra: BTreeMap::new(),
925    })
926}
927
928fn capture_scene(scene: &ObsSceneRef) -> Result<PersistedScene, SceneCollectionError> {
929    let scene_id = scene.persistent_uuid()?;
930    let groups = scene.groups()?;
931    let groups_by_runtime_id = groups
932        .into_iter()
933        .map(|group| (group.object_id(), group))
934        .collect::<HashMap<_, _>>();
935    let mut occurrence = HashMap::<String, usize>::new();
936    let mut items = Vec::new();
937
938    for item in scene.items_in_order()? {
939        if let Some(group) = groups_by_runtime_id.get(&item.object_id()) {
940            let mut children = Vec::new();
941            for child in group.items_in_order()? {
942                children.push(capture_source_item(
943                    child.as_ref(),
944                    &scene_id,
945                    &mut occurrence,
946                )?);
947            }
948            items.push(PersistedSceneNode::Group(PersistedGroup {
949                id: item.source_persistent_uuid()?,
950                name: group.name().to_string(),
951                state: PersistedSceneItemState::capture(item.as_ref())?,
952                items: children,
953                extra: BTreeMap::new(),
954            }));
955        } else {
956            items.push(PersistedSceneNode::Source(capture_source_item(
957                item.as_ref(),
958                &scene_id,
959                &mut occurrence,
960            )?));
961        }
962    }
963
964    Ok(PersistedScene {
965        id: scene_id,
966        name: scene.name().to_string(),
967        items,
968        extra: BTreeMap::new(),
969    })
970}
971
972fn capture_source_item(
973    item: &dyn SceneItemTrait,
974    scene_id: &str,
975    occurrence: &mut HashMap<String, usize>,
976) -> Result<PersistedSourceItem, SceneCollectionError> {
977    let source_id = item.source_persistent_uuid()?;
978    let index = occurrence.entry(source_id.clone()).or_default();
979    let id = format!("{scene_id}:{source_id}:item:{index}");
980    *index += 1;
981    Ok(PersistedSourceItem {
982        id,
983        source_id,
984        state: PersistedSceneItemState::capture(item)?,
985        extra: BTreeMap::new(),
986    })
987}
988
989fn restore_scene_items(
990    scene: &mut ObsSceneRef,
991    nodes: &[PersistedSceneNode],
992    sources: &HashMap<String, ObsSourceRef>,
993    mode: RestoreMode,
994    diagnostics: &mut Vec<RestoreDiagnostic>,
995) -> Result<(), SceneCollectionError> {
996    for node in nodes {
997        match node {
998            PersistedSceneNode::Source(item) => {
999                let Some(source) = sources.get(&item.source_id) else {
1000                    skip_missing_item(item, mode, diagnostics)?;
1001                    continue;
1002                };
1003                let runtime_item = scene.add(source.clone())?;
1004                runtime_item.apply_state_snapshot(&item.state.to_snapshot()?)?;
1005            }
1006            PersistedSceneNode::Group(group) => {
1007                let runtime_group = scene.create_group(group.name.as_str())?;
1008                for child in &group.items {
1009                    let Some(source) = sources.get(&child.source_id) else {
1010                        skip_missing_item(child, mode, diagnostics)?;
1011                        continue;
1012                    };
1013                    let runtime_item = scene.add(source.clone())?;
1014                    runtime_group.add_item(&runtime_item)?;
1015                    runtime_item.apply_state_snapshot(&child.state.to_snapshot()?)?;
1016                }
1017                runtime_group.apply_state_snapshot(&group.state.to_snapshot()?)?;
1018            }
1019        }
1020    }
1021    Ok(())
1022}
1023
1024fn skip_missing_item(
1025    item: &PersistedSourceItem,
1026    mode: RestoreMode,
1027    diagnostics: &mut Vec<RestoreDiagnostic>,
1028) -> Result<(), SceneCollectionError> {
1029    let message = format!(
1030        "scene item '{}' references source '{}' which could not be restored",
1031        item.id, item.source_id
1032    );
1033    if mode == RestoreMode::Strict {
1034        return Err(SceneCollectionError::InvalidDocument(message));
1035    }
1036    diagnostics.push(RestoreDiagnostic {
1037        kind: RestoreDiagnosticKind::SkippedSceneItem,
1038        object_id: item.id.clone(),
1039        message,
1040    });
1041    Ok(())
1042}
1043
1044fn validate_item<'a>(
1045    item: &'a PersistedSourceItem,
1046    sources: &HashSet<&'a str>,
1047    item_ids: &mut HashSet<&'a str>,
1048) -> Result<(), SceneCollectionError> {
1049    if !item_ids.insert(item.id.as_str()) {
1050        return Err(SceneCollectionError::InvalidDocument(format!(
1051            "duplicate scene item id '{}'",
1052            item.id
1053        )));
1054    }
1055    if !sources.contains(item.source_id.as_str()) {
1056        return Err(SceneCollectionError::InvalidDocument(format!(
1057            "scene item '{}' references unknown source '{}'",
1058            item.id, item.source_id
1059        )));
1060    }
1061    Ok(())
1062}
1063
1064fn obs_data_from_value(
1065    context: &ObsContext,
1066    value: &Value,
1067) -> Result<ObsData, SceneCollectionError> {
1068    Ok(ObsData::from_json(
1069        &serde_json::to_string(value)?,
1070        context.runtime().clone(),
1071    )?)
1072}
1073
1074fn inspect_missing_files(
1075    object_id: &str,
1076    settings: &Value,
1077    mode: RestoreMode,
1078    diagnostics: &mut Vec<RestoreDiagnostic>,
1079) -> Result<(), SceneCollectionError> {
1080    let mut missing = Vec::<PathBuf>::new();
1081    walk_values(settings, "", &mut |key, value| {
1082        if !looks_like_path_key(key) {
1083            return;
1084        }
1085        if let Some(text) = value.as_str() {
1086            let path = Path::new(text);
1087            if looks_like_absolute_path(text) && !path.exists() {
1088                missing.push(path.to_path_buf());
1089            }
1090        }
1091    });
1092    for path in missing {
1093        let message = format!(
1094            "persisted setting references missing local path '{}'",
1095            path.display()
1096        );
1097        if mode == RestoreMode::Strict {
1098            return Err(SceneCollectionError::InvalidDocument(format!(
1099                "{object_id}: {message}"
1100            )));
1101        }
1102        diagnostics.push(RestoreDiagnostic {
1103            kind: RestoreDiagnosticKind::MissingFile,
1104            object_id: object_id.to_owned(),
1105            message,
1106        });
1107    }
1108    Ok(())
1109}
1110
1111fn inspect_redacted_fields(
1112    object_id: &str,
1113    settings: &Value,
1114    diagnostics: &mut Vec<RestoreDiagnostic>,
1115) {
1116    walk_values(settings, "", &mut |key, value| {
1117        let Some(text) = value.as_str() else {
1118            return;
1119        };
1120        if text == REDACTED_SECRET || text == REDACTED_PATH {
1121            diagnostics.push(RestoreDiagnostic {
1122                kind: RestoreDiagnosticKind::RedactedSetting,
1123                object_id: object_id.to_owned(),
1124                message: format!(
1125                    "setting '{key}' was redacted during export and must be supplied for this machine"
1126                ),
1127            });
1128        }
1129    });
1130}
1131
1132fn sanitize_value(
1133    object_id: &str,
1134    root: &str,
1135    value: &mut Value,
1136    policy: SceneCollectionExportPolicy,
1137    redactions: &mut Vec<ExportRedaction>,
1138) {
1139    sanitize_value_inner(object_id, root, "", value, policy, redactions);
1140}
1141
1142fn sanitize_value_inner(
1143    object_id: &str,
1144    root: &str,
1145    path: &str,
1146    value: &mut Value,
1147    policy: SceneCollectionExportPolicy,
1148    redactions: &mut Vec<ExportRedaction>,
1149) {
1150    match value {
1151        Value::Object(map) => {
1152            for (key, child) in map {
1153                let child_path = if path.is_empty() {
1154                    key.clone()
1155                } else {
1156                    format!("{path}.{key}")
1157                };
1158                if policy.secrets == SecretHandling::Redact
1159                    && looks_like_secret_key(key)
1160                    && !child.is_null()
1161                {
1162                    *child = Value::String(REDACTED_SECRET.into());
1163                    redactions.push(ExportRedaction {
1164                        object_id: object_id.to_owned(),
1165                        setting_path: format!("{root}.{child_path}"),
1166                        reason: "secret",
1167                    });
1168                    continue;
1169                }
1170                if policy.machine_paths == MachinePathHandling::RedactAbsolute
1171                    && looks_like_path_key(key)
1172                    && child.as_str().is_some_and(looks_like_absolute_path)
1173                {
1174                    *child = Value::String(REDACTED_PATH.into());
1175                    redactions.push(ExportRedaction {
1176                        object_id: object_id.to_owned(),
1177                        setting_path: format!("{root}.{child_path}"),
1178                        reason: "machine_path",
1179                    });
1180                    continue;
1181                }
1182                sanitize_value_inner(object_id, root, &child_path, child, policy, redactions);
1183            }
1184        }
1185        Value::Array(values) => {
1186            for (index, child) in values.iter_mut().enumerate() {
1187                sanitize_value_inner(
1188                    object_id,
1189                    root,
1190                    &format!("{path}[{index}]"),
1191                    child,
1192                    policy,
1193                    redactions,
1194                );
1195            }
1196        }
1197        _ => {}
1198    }
1199}
1200
1201fn walk_values(value: &Value, path: &str, callback: &mut impl FnMut(&str, &Value)) {
1202    match value {
1203        Value::Object(map) => {
1204            for (key, child) in map {
1205                let child_path = if path.is_empty() {
1206                    key.clone()
1207                } else {
1208                    format!("{path}.{key}")
1209                };
1210                callback(key, child);
1211                walk_values(child, &child_path, callback);
1212            }
1213        }
1214        Value::Array(values) => {
1215            for child in values {
1216                walk_values(child, path, callback);
1217            }
1218        }
1219        _ => {}
1220    }
1221}
1222
1223fn looks_like_secret_key(key: &str) -> bool {
1224    let key = key.to_ascii_lowercase();
1225    key.contains("password")
1226        || key.contains("secret")
1227        || key.contains("token")
1228        || key.contains("credential")
1229        || key == "stream_key"
1230        || key.ends_with("_stream_key")
1231        || key.ends_with("_api_key")
1232}
1233
1234/// Whether `text` is an absolute path on *any* supported platform.
1235///
1236/// Scene collections move between machines, so a Windows export must still
1237/// recognize `/home/...` and a Linux/macOS export must recognize `C:\...` or
1238/// `\\server\share` paths.
1239fn looks_like_absolute_path(text: &str) -> bool {
1240    if Path::new(text).is_absolute() || text.starts_with('/') || text.starts_with('\\') {
1241        return true;
1242    }
1243    let bytes = text.as_bytes();
1244    bytes.len() >= 3
1245        && bytes[0].is_ascii_alphabetic()
1246        && bytes[1] == b':'
1247        && matches!(bytes[2], b'\\' | b'/')
1248}
1249
1250fn looks_like_path_key(key: &str) -> bool {
1251    let key = key.to_ascii_lowercase();
1252    key.contains("path")
1253        || key == "file"
1254        || key.ends_with("_file")
1255        || key.contains("filename")
1256        || key == "local_file"
1257}
1258
1259fn atomic_write(path: &Path, bytes: &[u8]) -> Result<(), SceneCollectionError> {
1260    let parent = path.parent().unwrap_or_else(|| Path::new("."));
1261    fs::create_dir_all(parent)?;
1262    let file_name = path
1263        .file_name()
1264        .and_then(|name| name.to_str())
1265        .ok_or_else(|| SceneCollectionError::InvalidDocument("invalid output filename".into()))?;
1266    let temp = parent.join(format!(".{file_name}.tmp-{}", std::process::id()));
1267    let backup = parent.join(format!(".{file_name}.bak-{}", std::process::id()));
1268
1269    let write_result = (|| -> Result<(), std::io::Error> {
1270        let mut file = File::create(&temp)?;
1271        file.write_all(bytes)?;
1272        file.sync_all()?;
1273        Ok(())
1274    })();
1275    if let Err(error) = write_result {
1276        let _ = fs::remove_file(&temp);
1277        return Err(error.into());
1278    }
1279
1280    match fs::rename(&temp, path) {
1281        Ok(()) => Ok(()),
1282        Err(_first_error) if path.exists() => {
1283            fs::rename(path, &backup)?;
1284            match fs::rename(&temp, path) {
1285                Ok(()) => {
1286                    let _ = fs::remove_file(&backup);
1287                    Ok(())
1288                }
1289                Err(error) => {
1290                    let _ = fs::rename(&backup, path);
1291                    let _ = fs::remove_file(&temp);
1292                    Err(error.into())
1293                }
1294            }
1295        }
1296        Err(error) => {
1297            let _ = fs::remove_file(&temp);
1298            Err(error.into())
1299        }
1300    }
1301}
1302
1303#[cfg(test)]
1304mod tests {
1305    use super::*;
1306
1307    fn state(order: i32) -> PersistedSceneItemState {
1308        PersistedSceneItemState {
1309            position: [1.0, 2.0],
1310            scale: [1.0, 1.0],
1311            alignment: ObsAlignment::CENTER.bits(),
1312            rotation: 0.0,
1313            bounds: [1920.0, 1080.0],
1314            bounds_type: ObsBoundsType::None as i64,
1315            bounds_alignment: ObsAlignment::CENTER.bits(),
1316            crop_to_bounds: false,
1317            crop: [0, 0, 0, 0],
1318            scale_filter: ObsScaleType::Bilinear as i64,
1319            blend_method: ObsBlendMethod::Default as i64,
1320            blend_mode: ObsBlendMode::Normal as i64,
1321            visible: true,
1322            locked: false,
1323            order_position: order,
1324        }
1325    }
1326
1327    fn fixture() -> SceneCollectionDocument {
1328        SceneCollectionDocument {
1329            version: SCENE_COLLECTION_SCHEMA_VERSION,
1330            name: Some("test".into()),
1331            sources: vec![PersistedSource {
1332                id: "source-a".into(),
1333                plugin_id: "color_source_v3".into(),
1334                name: "Color".into(),
1335                settings: serde_json::json!({"width": 640, "password": "secret"}),
1336                hotkeys: serde_json::json!({}),
1337                filters: vec![],
1338                extra: BTreeMap::new(),
1339            }],
1340            scenes: vec![PersistedScene {
1341                id: "scene-a".into(),
1342                name: "Scene".into(),
1343                items: vec![PersistedSceneNode::Source(PersistedSourceItem {
1344                    id: "item-a".into(),
1345                    source_id: "source-a".into(),
1346                    state: state(0),
1347                    extra: BTreeMap::new(),
1348                })],
1349                extra: BTreeMap::new(),
1350            }],
1351            extra: BTreeMap::from([("future_field".into(), serde_json::json!({"x": 1}))]),
1352        }
1353    }
1354
1355    #[test]
1356    fn versioned_json_round_trip_preserves_unknown_fields() {
1357        let document = fixture();
1358        let json = document.to_json().unwrap();
1359        let decoded = SceneCollectionDocument::from_json(&json).unwrap();
1360        assert_eq!(decoded, document);
1361        assert!(decoded.extra.contains_key("future_field"));
1362    }
1363
1364    #[test]
1365    fn unsupported_schema_is_rejected() {
1366        let mut document = fixture();
1367        document.version += 1;
1368        assert!(matches!(
1369            SceneCollectionDocument::from_json(&serde_json::to_string(&document).unwrap()),
1370            Err(SceneCollectionError::UnsupportedVersion { .. })
1371        ));
1372    }
1373
1374    #[test]
1375    fn malformed_or_dangling_references_are_rejected() {
1376        assert!(SceneCollectionDocument::from_json("{").is_err());
1377        let mut document = fixture();
1378        let PersistedSceneNode::Source(item) = &mut document.scenes[0].items[0] else {
1379            unreachable!()
1380        };
1381        item.source_id = "missing".into();
1382        assert!(document.to_json().is_err());
1383    }
1384
1385    #[test]
1386    fn portable_export_redacts_secrets_and_machine_paths() {
1387        let mut document = fixture();
1388        document.sources[0].settings["local_file"] = Value::String("/home/user/private.mp4".into());
1389        let export = document
1390            .export(SceneCollectionExportPolicy::portable_redacted())
1391            .unwrap();
1392        let decoded: Value = serde_json::from_str(&export.json).unwrap();
1393        assert_eq!(
1394            decoded["sources"][0]["settings"]["password"],
1395            REDACTED_SECRET
1396        );
1397        assert_eq!(
1398            decoded["sources"][0]["settings"]["local_file"],
1399            REDACTED_PATH
1400        );
1401        assert_eq!(export.redactions.len(), 2);
1402    }
1403
1404    #[test]
1405    fn absolute_paths_are_recognized_for_every_platform() {
1406        for path in [
1407            "/home/user/private.mp4",
1408            "C:\\Users\\user\\private.mp4",
1409            "c:/Users/user/private.mp4",
1410            "\\\\server\\share\\private.mp4",
1411        ] {
1412            assert!(looks_like_absolute_path(path), "{path} should be absolute");
1413        }
1414        for path in ["private.mp4", "media/private.mp4", "C:private.mp4", ""] {
1415            assert!(!looks_like_absolute_path(path), "{path} should be relative");
1416        }
1417    }
1418
1419    #[test]
1420    fn scene_item_state_round_trips_runtime_snapshot_shape() {
1421        let persisted = state(3);
1422        let snapshot = persisted.to_snapshot().unwrap();
1423        assert_eq!(snapshot.order_position, 3);
1424        assert_eq!(snapshot.transform.position, Vec2::new(1.0, 2.0));
1425        assert_eq!(PersistedSceneItemState::from_snapshot(&snapshot), persisted);
1426    }
1427
1428    #[test]
1429    fn editor_undo_redo_restores_item_state_by_stable_id() {
1430        let document = fixture();
1431        let original = document.scenes[0].items[0].clone();
1432        let mut editor = SceneCollectionEditor::new(document).unwrap();
1433        let mut changed = state(0);
1434        changed.position = [99.0, 123.0];
1435        editor
1436            .set_item_state("scene-a", "item-a", changed.clone())
1437            .unwrap();
1438        let PersistedSceneNode::Source(item) = &editor.document().scenes[0].items[0] else {
1439            unreachable!()
1440        };
1441        assert_eq!(item.state, changed);
1442        assert!(editor.undo());
1443        assert_eq!(editor.document().scenes[0].items[0], original);
1444        assert!(editor.redo());
1445        let PersistedSceneNode::Source(item) = &editor.document().scenes[0].items[0] else {
1446            unreachable!()
1447        };
1448        assert_eq!(item.state.position, [99.0, 123.0]);
1449    }
1450
1451    #[test]
1452    fn editor_models_group_and_ungroup_replacement_semantics() {
1453        let mut document = fixture();
1454        document.sources.push(PersistedSource {
1455            id: "source-b".into(),
1456            plugin_id: "color_source_v3".into(),
1457            name: "Color B".into(),
1458            settings: serde_json::json!({}),
1459            hotkeys: serde_json::json!({}),
1460            filters: vec![],
1461            extra: BTreeMap::new(),
1462        });
1463        document.scenes[0]
1464            .items
1465            .push(PersistedSceneNode::Source(PersistedSourceItem {
1466                id: "item-b".into(),
1467                source_id: "source-b".into(),
1468                state: state(1),
1469                extra: BTreeMap::new(),
1470            }));
1471        let mut editor = SceneCollectionEditor::new(document).unwrap();
1472        let grouped_children = vec![
1473            PersistedSourceItem {
1474                id: "item-a".into(),
1475                source_id: "source-a".into(),
1476                state: state(0),
1477                extra: BTreeMap::new(),
1478            },
1479            PersistedSourceItem {
1480                id: "item-b".into(),
1481                source_id: "source-b".into(),
1482                state: state(1),
1483                extra: BTreeMap::new(),
1484            },
1485        ];
1486        editor
1487            .replace_items_with_group(
1488                "scene-a",
1489                &["item-a".into(), "item-b".into()],
1490                PersistedGroup {
1491                    id: "group-a".into(),
1492                    name: "Group".into(),
1493                    state: state(0),
1494                    items: grouped_children.clone(),
1495                    extra: BTreeMap::new(),
1496                },
1497            )
1498            .unwrap();
1499        assert!(matches!(
1500            &editor.document().scenes[0].items[..],
1501            [PersistedSceneNode::Group(group)] if group.id == "group-a"
1502        ));
1503
1504        let mut replacements = grouped_children;
1505        replacements[0].state.position = [400.0, 200.0];
1506        replacements[1].state.position = [800.0, 500.0];
1507        editor
1508            .ungroup_with_replacements("scene-a", "group-a", replacements.clone())
1509            .unwrap();
1510        assert_eq!(editor.document().scenes[0].items.len(), 2);
1511        let PersistedSceneNode::Source(first) = &editor.document().scenes[0].items[0] else {
1512            unreachable!()
1513        };
1514        assert_eq!(first.id, "item-a");
1515        assert_eq!(first.state.position, [400.0, 200.0]);
1516
1517        assert!(editor.undo());
1518        assert!(matches!(
1519            &editor.document().scenes[0].items[..],
1520            [PersistedSceneNode::Group(group)] if group.id == "group-a"
1521        ));
1522        assert!(editor.redo());
1523        assert!(matches!(
1524            &editor.document().scenes[0].items[..],
1525            [PersistedSceneNode::Source(_), PersistedSceneNode::Source(_)]
1526        ));
1527    }
1528
1529    #[test]
1530    fn atomic_save_replaces_without_truncating() {
1531        let root = std::env::temp_dir().join(format!(
1532            "libobs-rs-scene-collection-{}-{}",
1533            std::process::id(),
1534            // Test thread names contain `::`, which is not valid in Windows file names.
1535            std::thread::current()
1536                .name()
1537                .unwrap_or("test")
1538                .replace(|c: char| !c.is_ascii_alphanumeric(), "_")
1539        ));
1540        let _ = fs::remove_dir_all(&root);
1541        fs::create_dir_all(&root).unwrap();
1542        let path = root.join("collection.json");
1543        fs::write(&path, "old").unwrap();
1544        fixture()
1545            .save_atomic(&path, SceneCollectionExportPolicy::include_all())
1546            .unwrap();
1547        let loaded = SceneCollectionDocument::load(&path).unwrap();
1548        assert_eq!(loaded.name.as_deref(), Some("test"));
1549        let _ = fs::remove_dir_all(root);
1550    }
1551}