Skip to main content

libobs_wrapper\scenes\scene_item/
mod.rs

1//! Scene items essentially hold the transform information and the source in a scene itself.
2//! They are specific to the scene which they were created in.
3mod traits;
4pub use traits::SceneItemExtSceneTrait;
5
6use std::{
7    fmt::Debug,
8    hash::Hash,
9    sync::{Arc, Mutex},
10};
11
12use libobs::{obs_scene_item, obs_transform_info, obs_video_info};
13use num_traits::FromPrimitive;
14
15use crate::{
16    enums::{
17        ObsAlignment, ObsBlendMethod, ObsBlendMode, ObsBoundsType, ObsOrderMovement, ObsScaleType,
18    },
19    graphics::Vec2,
20    impl_obs_drop,
21    macros::trait_with_optional_send_sync,
22    run_with_obs,
23    runtime::ObsRuntime,
24    scenes::{ObsSceneRef, ObsTransformInfo, ObsTransformInfoBuilder},
25    sources::ObsSourceTrait,
26    unsafe_send::{Sendable, SmartPointerSendable},
27    utils::{ObsDropGuard, ObsError},
28};
29
30/// Pixel crop applied to a scene item before its transform is evaluated.
31///
32/// Values map directly to libobs's left/top/right/bottom scene-item crop. Positive values
33/// remove pixels from the corresponding edge of the underlying source.
34#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
35pub struct ObsSceneItemCrop {
36    pub left: i32,
37    pub top: i32,
38    pub right: i32,
39    pub bottom: i32,
40}
41
42impl ObsSceneItemCrop {
43    pub const fn new(left: i32, top: i32, right: i32, bottom: i32) -> Self {
44        Self {
45            left,
46            top,
47            right,
48            bottom,
49        }
50    }
51}
52
53impl From<ObsSceneItemCrop> for libobs::obs_sceneitem_crop {
54    fn from(value: ObsSceneItemCrop) -> Self {
55        Self {
56            left: value.left,
57            top: value.top,
58            right: value.right,
59            bottom: value.bottom,
60        }
61    }
62}
63
64impl From<libobs::obs_sceneitem_crop> for ObsSceneItemCrop {
65    fn from(value: libobs::obs_sceneitem_crop) -> Self {
66        Self::new(value.left, value.top, value.right, value.bottom)
67    }
68}
69
70/// Complete render-transform state for one scene item. Unlike [`ObsTransformInfo`], this also
71/// includes edge crop, scaling filter, and blending state stored outside `obs_transform_info`.
72#[derive(Debug, Clone, PartialEq)]
73pub struct ObsSceneItemTransformSnapshot {
74    pub position: Vec2,
75    pub scale: Vec2,
76    pub alignment: ObsAlignment,
77    pub rotation: f32,
78    pub bounds: Vec2,
79    pub bounds_type: ObsBoundsType,
80    pub bounds_alignment: ObsAlignment,
81    pub crop_to_bounds: bool,
82    pub crop: ObsSceneItemCrop,
83    pub scale_filter: ObsScaleType,
84    pub blend_method: ObsBlendMethod,
85    pub blend_mode: ObsBlendMode,
86}
87
88/// Restorable scene-item state including transform, visibility, locking and native z-order.
89#[derive(Debug, Clone, PartialEq)]
90pub struct ObsSceneItemStateSnapshot {
91    pub transform: ObsSceneItemTransformSnapshot,
92    pub visible: bool,
93    pub locked: bool,
94    pub order_position: i32,
95}
96
97#[derive(Debug)]
98pub(super) struct _ObsSceneItemDropGuard {
99    scene_item: Sendable<*mut obs_scene_item>,
100    removed: Arc<Mutex<bool>>,
101    runtime: ObsRuntime,
102}
103
104impl ObsDropGuard for _ObsSceneItemDropGuard {}
105impl_obs_drop!(
106    _ObsSceneItemDropGuard,
107    (scene_item, removed),
108    move || unsafe {
109        // Safety: construction takes an explicit native scene-item reference. Remove the item from
110        // its scene at most once, then release the reference owned by this managed handle.
111        let mut removed = removed
112            .lock()
113            .unwrap_or_else(|poisoned| poisoned.into_inner());
114        if !*removed {
115            libobs::obs_sceneitem_remove(scene_item.0);
116            *removed = true;
117        }
118        libobs::obs_sceneitem_release(scene_item.0);
119    }
120);
121
122/// Wraps one explicit native scene-item reference in the managed lifetime lease used by all
123/// scene-item handle types. The caller must already own one `obs_sceneitem_addref` reference.
124pub(super) fn wrap_owned_scene_item_ref(
125    scene_item: Sendable<*mut obs_scene_item>,
126    runtime: ObsRuntime,
127) -> (SmartPointerSendable<*mut obs_scene_item>, Arc<Mutex<bool>>) {
128    let removed = Arc::new(Mutex::new(false));
129    let drop_guard = _ObsSceneItemDropGuard {
130        scene_item: scene_item.clone(),
131        removed: removed.clone(),
132        runtime: runtime.clone(),
133    };
134    let handle = SmartPointerSendable::new(
135        scene_item.0,
136        Arc::new(drop_guard),
137        runtime.native_registry(),
138    );
139    (handle, removed)
140}
141
142pub(super) fn scene_item_native_handle<T: SceneItemTrait + ?Sized>(
143    item: &T,
144) -> SmartPointerSendable<*mut obs_scene_item> {
145    item.__native_handle().clone()
146}
147
148pub(super) fn mark_scene_item_removed<T: SceneItemTrait + ?Sized>(item: &T) {
149    let mut removed = item
150        .__removed_flag()
151        .lock()
152        .unwrap_or_else(|poisoned| poisoned.into_inner());
153    *removed = true;
154}
155
156#[derive(Debug, Clone)]
157/// Holds the specific source that was added to the scene and its scene item.
158/// If this struct is attached to the scene, it'll not be dropped as the scene
159/// internally stores this struct, thus the source will also not be dropped.
160pub struct ObsSceneItemRef<T: ObsSourceTrait + Clone> {
161    // Drop the scene item first...
162    scene_item_ptr: SmartPointerSendable<*mut obs_scene_item>,
163    removed: Arc<Mutex<bool>>,
164    runtime: ObsRuntime,
165    // Then the scene
166    // Note: Ideally, we'd want to keep the whole ObsScene struct, however
167    // that would lead to a circular dependency, meaning that this SceneItem / the scene
168    // would never be dropped. Because the only argument the scene takes is its name
169    // and there are no settings attached to it, it's safe to only have a SmartPointer
170    // and not the full scene
171    _scene_ptr: SmartPointerSendable<*mut libobs::obs_scene>,
172
173    // And at last the source
174    underlying_source: T,
175}
176
177/// Type-erased managed scene-item handle used when libobs itself replaces a native item, such as
178/// during group ungrouping. Ordinary source insertion still returns [`ObsSceneItemRef<T>`].
179#[derive(Debug, Clone)]
180pub struct ObsSceneItemHandle {
181    scene_item_ptr: SmartPointerSendable<*mut obs_scene_item>,
182    removed: Arc<Mutex<bool>>,
183    runtime: ObsRuntime,
184    _scene_ptr: SmartPointerSendable<*mut libobs::obs_scene_t>,
185}
186
187impl ObsSceneItemHandle {
188    pub(super) fn from_owned_native_ref(
189        item: Sendable<*mut obs_scene_item>,
190        scene_ptr: SmartPointerSendable<*mut libobs::obs_scene_t>,
191        runtime: ObsRuntime,
192    ) -> Self {
193        let (scene_item_ptr, removed) = wrap_owned_scene_item_ref(item, runtime.clone());
194        Self {
195            scene_item_ptr,
196            removed,
197            runtime,
198            _scene_ptr: scene_ptr,
199        }
200    }
201}
202
203impl<T: ObsSourceTrait + Clone> ObsSceneItemRef<T> {
204    pub(crate) fn new(
205        scene: &ObsSceneRef,
206        source: T,
207        runtime: ObsRuntime,
208    ) -> Result<Self, ObsError> {
209        runtime.ensure_same_runtime(source.runtime())?;
210        runtime.ensure_same_runtime(&scene.runtime)?;
211        let scene_ptr = scene.as_ptr();
212        let source_ptr = source.__native_handle();
213
214        let scene_item_ptr = run_with_obs!(runtime, (scene_ptr, source_ptr), move || {
215            let ptr = unsafe {
216                // SAFETY: This actor command captures scene/source leases, retaining both
217                // native references through the synchronous scene insertion.
218                libobs::obs_scene_add(scene_ptr.get_ptr(), source_ptr.get_ptr())
219            };
220
221            if ptr.is_null() {
222                Err(ObsError::NullPointer(None))
223            } else {
224                unsafe {
225                    // Safety: `ptr` is a live item returned by obs_scene_add. The managed handle
226                    // owns this added reference until its drop guard releases it.
227                    libobs::obs_sceneitem_addref(ptr);
228                }
229                Ok(Sendable(ptr))
230            }
231        })??;
232
233        let removed = Arc::new(Mutex::new(false));
234        let drop_guard = _ObsSceneItemDropGuard {
235            scene_item: scene_item_ptr.clone(),
236            removed: removed.clone(),
237            runtime: runtime.clone(),
238        };
239
240        let scene_item_ptr = SmartPointerSendable::new(
241            scene_item_ptr.0,
242            Arc::new(drop_guard),
243            runtime.native_registry(),
244        );
245
246        Ok(Self {
247            underlying_source: source,
248            _scene_ptr: scene.as_ptr().clone(),
249            scene_item_ptr,
250            removed,
251            runtime,
252        })
253    }
254}
255
256trait_with_optional_send_sync! {
257    pub(crate) trait SceneItemTraitSealed: Debug {
258        fn __native_handle(&self) -> &SmartPointerSendable<*mut obs_scene_item>;
259        fn __removed_flag(&self) -> &Arc<Mutex<bool>>;
260    }
261}
262
263trait_with_optional_send_sync! {
264    #[allow(private_bounds)]
265    pub trait SceneItemTrait: SceneItemTraitSealed {
266        fn runtime(&self) -> ObsRuntime;
267
268        fn object_id(&self) -> crate::unsafe_send::NativeObjectId {
269            self.__native_handle().native_id()
270        }
271
272        /// Returns the persistent UUID of the source represented by this scene item.
273        ///
274        /// This is safe to serialize and is distinct from the runtime-scoped scene-item
275        /// [`NativeObjectId`](crate::unsafe_send::NativeObjectId).
276        fn source_persistent_uuid(&self) -> Result<String, ObsError> {
277            let item = self.__native_handle().clone();
278            run_with_obs!(self.runtime(), (item), move || unsafe {
279                // Safety: the managed scene item remains alive for the actor call. The source is
280                // borrowed only long enough to copy libobs's persistent UUID string.
281                let source = libobs::obs_sceneitem_get_source(item.get_ptr());
282                if source.is_null() {
283                    return Err(ObsError::NullPointer(Some(
284                        "scene item has no source".into(),
285                    )));
286                }
287                let uuid = libobs::obs_source_get_uuid(source);
288                if uuid.is_null() {
289                    return Err(ObsError::NullPointer(Some(
290                        "scene-item source has no persistent UUID".into(),
291                    )));
292                }
293                Ok(std::ffi::CStr::from_ptr(uuid).to_string_lossy().into_owned())
294            })?
295        }
296
297        /// Removes this item from its scene immediately while keeping the typed handle valid
298        /// until its final Rust reference is dropped. Repeated calls are harmless.
299        fn remove_from_scene(&self) -> Result<(), ObsError> {
300            let mut removed = self
301                .__removed_flag()
302                .lock()
303                .unwrap_or_else(|poisoned| poisoned.into_inner());
304            if *removed {
305                return Ok(());
306            }
307            let self_ptr = self.__native_handle().clone();
308            run_with_obs!(self.runtime(), (self_ptr), move || unsafe {
309                // Safety: the managed item owns a native reference, so removal cannot invalidate
310                // the pointer until the drop guard later releases that reference.
311                libobs::obs_sceneitem_remove(self_ptr.get_ptr());
312            })?;
313            *removed = true;
314            Ok(())
315        }
316
317        /// Whether this item has been explicitly removed from its scene.
318        fn is_removed(&self) -> bool {
319            *self
320                .__removed_flag()
321                .lock()
322                .unwrap_or_else(|poisoned| poisoned.into_inner())
323        }
324
325        /// Gets the transform info of the given source in this scene.
326        fn get_transform_info(&self) -> Result<ObsTransformInfo, ObsError> {
327            let self_ptr = self.__native_handle().clone();
328            let item_info = run_with_obs!(self.runtime(), (self_ptr), move || {
329                let mut item_info: obs_transform_info = unsafe {
330                    // Safety: this is safe to call because we are filling a struct with zeros
331                    std::mem::zeroed()
332                };
333                unsafe {
334                    // Safety: Fill the transform info struct with the data
335                    libobs::obs_sceneitem_get_info2(self_ptr.get_ptr(), &mut item_info)
336                };
337
338                ObsTransformInfo(item_info)
339            })?;
340
341            Ok(item_info)
342        }
343
344        /// Gets the position of the given source in this scene.
345        fn get_source_position(&self) -> Result<Vec2, ObsError> {
346            let self_ptr = self.__native_handle().clone();
347            let position = run_with_obs!(self.runtime(), (self_ptr), move || {
348                let main_pos = unsafe {
349                    // Safety: this is safe to call because we a filling a struct with zeros
350                    let mut main_pos: libobs::vec2 = std::mem::zeroed();
351
352                    // Safety: Fill the vec2 struct with the position data
353                    libobs::obs_sceneitem_get_pos(self_ptr.get_ptr(), &mut main_pos);
354
355                    main_pos
356                };
357
358                Vec2::from(main_pos)
359            })?;
360
361            Ok(position)
362        }
363
364        /// Gets the scale of the given source in this scene.
365        fn get_source_scale(&self) -> Result<Vec2, ObsError> {
366            let self_ptr = self.__native_handle().clone();
367            let scale = run_with_obs!(self.runtime(), (self_ptr), move || {
368                let main_pos = unsafe {
369                    // Safety: this is safe to call because we a filling a struct with zeros
370                    let mut main_pos: libobs::vec2 = std::mem::zeroed();
371
372                    // Safety: Fill the vec2 struct with the scale data, this using the correct size
373                    libobs::obs_sceneitem_get_scale(self_ptr.get_ptr(), &mut main_pos);
374
375                    main_pos
376                };
377
378                Vec2::from(main_pos)
379            })?;
380
381            Ok(scale)
382        }
383
384        /// Sets the position of the given source in this scene.
385        fn set_source_position(&self, position: Vec2) -> Result<(), ObsError> {
386            let self_ptr = self.__native_handle().clone();
387
388            run_with_obs!(self.runtime(), (self_ptr), move || {
389                let position: libobs::vec2 = position.into();
390
391                unsafe {
392                    // SAFETY: self_ptr retains the native scene-item reference through this actor
393                    // call.
394                    libobs::obs_sceneitem_set_pos(self_ptr.get_ptr(), &position);
395                }
396            })?;
397
398            Ok(())
399        }
400
401        /// Sets the transform info of the given source in this scene.
402        /// The `ObsTransformInfo` can be built by using the `ObsTransformInfoBuilder`.
403        fn set_transform_info(&self, info: &ObsTransformInfo) -> Result<(), ObsError> {
404            let item_info = info.clone();
405            let self_ptr = self.__native_handle().clone();
406
407            run_with_obs!(self.runtime(), (self_ptr, item_info), move || {
408                let item_info = item_info.0;
409
410                unsafe {
411                    // SAFETY: self_ptr retains the item on the actor; item_info is a live local
412                    // input copied synchronously by libobs.
413                    libobs::obs_sceneitem_set_info2(self_ptr.get_ptr(), &item_info);
414                }
415            })?;
416
417            Ok(())
418        }
419
420        /// Fits the given source to the screen size.
421        /// If the source is locked, no action is taken.
422        ///
423        /// Returns `Ok(true)` if the source was resized, `Ok(false)` if the source was locked and not resized.
424        fn fit_source_to_screen(&self) -> Result<bool, ObsError> {
425            let self_ptr = self.__native_handle().clone();
426            let is_locked = {
427                run_with_obs!(self.runtime(), (self_ptr), move || unsafe {
428                    // SAFETY: self_ptr retains the native scene-item reference through this actor
429                    // call.
430                    libobs::obs_sceneitem_locked(self_ptr.get_ptr())
431                })?
432            };
433
434            if is_locked {
435                return Ok(false);
436            }
437
438            let (base_width, base_height) = run_with_obs!(self.runtime(), (), move || {
439                let mut ovi = std::mem::MaybeUninit::<obs_video_info>::uninit();
440                let success = unsafe {
441                    // Safety: This is safe because we are providing a valid pointer to be filled
442                    libobs::obs_get_video_info(ovi.as_mut_ptr())
443                };
444
445                if success {
446                    let res = unsafe {
447                        // Safety: This is safe because libobs filled the pointer and returned success
448                        ovi.assume_init()
449                    };
450
451                    Ok((res.base_width, res.base_height))
452                } else {
453                    Err(ObsError::NullPointer(Some(
454                        "Failed to get video info".to_string(),
455                    )))
456                }
457            })??;
458
459            let bounds_crop = run_with_obs!(self.runtime(), (self_ptr), move || {
460                unsafe {
461                    // SAFETY: self_ptr retains the native scene-item reference through this actor
462                    // call.
463                    libobs::obs_sceneitem_get_bounds_crop(self_ptr.get_ptr())
464                }
465            })?;
466
467            // We are not constructing it from the source here because we want to reset full transform (so we use build instead of build_with_fallback)
468            let item_info = ObsTransformInfoBuilder::new()
469                .set_bounds_type(ObsBoundsType::ScaleInner)
470                .set_crop_to_bounds(bounds_crop)
471                .build(base_width, base_height);
472
473            self.set_transform_info(&item_info)?;
474            Ok(true)
475        }
476
477        /// Returns whether the item is visible.
478        fn is_visible(&self) -> Result<bool, ObsError> {
479            let self_ptr = self.__native_handle().clone();
480            run_with_obs!(self.runtime(), (self_ptr), move || unsafe {
481                // Safety: the managed item retains a native reference for the actor call.
482                libobs::obs_sceneitem_visible(self_ptr.get_ptr())
483            })
484        }
485
486        /// Returns the explicit pixel crop applied to this scene item.
487        fn crop(&self) -> Result<ObsSceneItemCrop, ObsError> {
488            let self_ptr = self.__native_handle().clone();
489            run_with_obs!(self.runtime(), (self_ptr), move || unsafe {
490                // Safety: the managed item retains a native reference for the actor call. The
491                // output structure is initialized even if libobs unexpectedly declines to write.
492                let mut crop = libobs::obs_sceneitem_crop {
493                    left: 0,
494                    top: 0,
495                    right: 0,
496                    bottom: 0,
497                };
498                libobs::obs_sceneitem_get_crop(self_ptr.get_ptr(), &mut crop);
499                ObsSceneItemCrop::from(crop)
500            })
501        }
502
503        /// Replaces the explicit left/top/right/bottom pixel crop for this scene item.
504        /// Negative edge values are clamped to zero by libobs.
505        fn set_crop(&self, crop: ObsSceneItemCrop) -> Result<(), ObsError> {
506            let self_ptr = self.__native_handle().clone();
507            run_with_obs!(self.runtime(), (self_ptr), move || unsafe {
508                // Safety: the managed item retains a native reference for the actor call and the
509                // converted crop value lives for the complete native setter invocation.
510                let crop: libobs::obs_sceneitem_crop = crop.into();
511                libobs::obs_sceneitem_set_crop(self_ptr.get_ptr(), &crop);
512            })
513        }
514
515        /// Shows or hides the item.
516        fn set_visible(&self, visible: bool) -> Result<(), ObsError> {
517            let self_ptr = self.__native_handle().clone();
518            run_with_obs!(self.runtime(), (self_ptr), move || unsafe {
519                // Safety: the managed item retains a native reference for the actor call.
520                let _ = libobs::obs_sceneitem_set_visible(self_ptr.get_ptr(), visible);
521            })
522        }
523
524        /// Returns whether the item transform is locked.
525        fn is_locked(&self) -> Result<bool, ObsError> {
526            let self_ptr = self.__native_handle().clone();
527            run_with_obs!(self.runtime(), (self_ptr), move || unsafe {
528                // Safety: the managed item retains a native reference for the actor call.
529                libobs::obs_sceneitem_locked(self_ptr.get_ptr())
530            })
531        }
532
533        /// Locks or unlocks the item transform.
534        fn set_locked(&self, locked: bool) -> Result<(), ObsError> {
535            let self_ptr = self.__native_handle().clone();
536            run_with_obs!(self.runtime(), (self_ptr), move || unsafe {
537                // Safety: the managed item retains a native reference for the actor call.
538                let _ = libobs::obs_sceneitem_set_locked(self_ptr.get_ptr(), locked);
539            })
540        }
541
542        /// Returns the clockwise rotation in degrees.
543        fn rotation(&self) -> Result<f32, ObsError> {
544            let self_ptr = self.__native_handle().clone();
545            run_with_obs!(self.runtime(), (self_ptr), move || unsafe {
546                // Safety: the managed item retains a native reference for the actor call.
547                libobs::obs_sceneitem_get_rot(self_ptr.get_ptr())
548            })
549        }
550
551        /// Sets the clockwise rotation in degrees.
552        fn set_rotation(&self, degrees: f32) -> Result<(), ObsError> {
553            let self_ptr = self.__native_handle().clone();
554            run_with_obs!(self.runtime(), (self_ptr), move || unsafe {
555                // Safety: the managed item retains a native reference for the actor call.
556                libobs::obs_sceneitem_set_rot(self_ptr.get_ptr(), degrees);
557            })
558        }
559
560        /// Returns the item's zero-based order position within its scene.
561        fn order_position(&self) -> Result<i32, ObsError> {
562            let self_ptr = self.__native_handle().clone();
563            run_with_obs!(self.runtime(), (self_ptr), move || unsafe {
564                // Safety: the managed item retains a native reference for the actor call.
565                libobs::obs_sceneitem_get_order_position(self_ptr.get_ptr())
566            })
567        }
568
569        /// Moves the item to an absolute order position within its scene.
570        fn set_order_position(&self, position: i32) -> Result<(), ObsError> {
571            if position < 0 {
572                return Err(ObsError::InvalidOperation(
573                    "Scene item order position cannot be negative".to_string(),
574                ));
575            }
576            let self_ptr = self.__native_handle().clone();
577            run_with_obs!(self.runtime(), (self_ptr), move || unsafe {
578                // Safety: the managed item retains a native reference for the actor call.
579                libobs::obs_sceneitem_set_order_position(self_ptr.get_ptr(), position);
580            })
581        }
582
583        /// Moves the item relative to the other items in its scene.
584        fn move_order(&self, movement: ObsOrderMovement) -> Result<(), ObsError> {
585            let self_ptr = self.__native_handle().clone();
586            run_with_obs!(self.runtime(), (self_ptr), move || unsafe {
587                // Safety: the managed item retains a native reference for the actor call.
588                libobs::obs_sceneitem_set_order(self_ptr.get_ptr(), movement as libobs::obs_order_movement);
589            })
590        }
591
592        /// Returns the scaling filter used when this item is resized.
593        fn scale_filter(&self) -> Result<ObsScaleType, ObsError> {
594            let self_ptr = self.__native_handle().clone();
595            let raw = run_with_obs!(self.runtime(), (self_ptr), move || unsafe {
596                // Safety: the managed scene-item reference remains alive for the actor call.
597                libobs::obs_sceneitem_get_scale_filter(self_ptr.get_ptr())
598            })?;
599            ObsScaleType::from_i64(raw as i64).ok_or_else(|| {
600                ObsError::EnumConversionError(format!("unknown scene-item scale filter {raw}"))
601            })
602        }
603
604        fn set_scale_filter(&self, filter: ObsScaleType) -> Result<(), ObsError> {
605            let self_ptr = self.__native_handle().clone();
606            run_with_obs!(self.runtime(), (self_ptr), move || unsafe {
607                // Safety: the managed item remains alive and `filter` is a libobs enum value.
608                libobs::obs_sceneitem_set_scale_filter(
609                    self_ptr.get_ptr(),
610                    filter as libobs::obs_scale_type,
611                );
612            })
613        }
614
615        fn blend_method(&self) -> Result<ObsBlendMethod, ObsError> {
616            let self_ptr = self.__native_handle().clone();
617            let raw = run_with_obs!(self.runtime(), (self_ptr), move || unsafe {
618                // Safety: the managed scene-item reference remains alive for the actor call.
619                libobs::obs_sceneitem_get_blending_method(self_ptr.get_ptr())
620            })?;
621            ObsBlendMethod::from_i64(raw as i64).ok_or_else(|| {
622                ObsError::EnumConversionError(format!("unknown scene-item blend method {raw}"))
623            })
624        }
625
626        fn set_blend_method(&self, method: ObsBlendMethod) -> Result<(), ObsError> {
627            let self_ptr = self.__native_handle().clone();
628            run_with_obs!(self.runtime(), (self_ptr), move || unsafe {
629                // Safety: the managed item remains alive and `method` is a libobs enum value.
630                libobs::obs_sceneitem_set_blending_method(
631                    self_ptr.get_ptr(),
632                    method as libobs::obs_blending_method,
633                );
634            })
635        }
636
637        fn blend_mode(&self) -> Result<ObsBlendMode, ObsError> {
638            let self_ptr = self.__native_handle().clone();
639            let raw = run_with_obs!(self.runtime(), (self_ptr), move || unsafe {
640                // Safety: the managed scene-item reference remains alive for the actor call.
641                libobs::obs_sceneitem_get_blending_mode(self_ptr.get_ptr())
642            })?;
643            ObsBlendMode::from_i64(raw as i64).ok_or_else(|| {
644                ObsError::EnumConversionError(format!("unknown scene-item blend mode {raw}"))
645            })
646        }
647
648        fn set_blend_mode(&self, mode: ObsBlendMode) -> Result<(), ObsError> {
649            let self_ptr = self.__native_handle().clone();
650            run_with_obs!(self.runtime(), (self_ptr), move || unsafe {
651                // Safety: the managed item remains alive and `mode` is a libobs enum value.
652                libobs::obs_sceneitem_set_blending_mode(
653                    self_ptr.get_ptr(),
654                    mode as libobs::obs_blending_type,
655                );
656            })
657        }
658
659        /// Captures every transform-affecting scene-item property exposed by libobs.
660        fn transform_snapshot(&self) -> Result<ObsSceneItemTransformSnapshot, ObsError> {
661            let info = self.get_transform_info()?;
662            let bounds_type = info.get_bounds_type().ok_or_else(|| {
663                ObsError::EnumConversionError("unknown scene-item bounds type".into())
664            })?;
665            Ok(ObsSceneItemTransformSnapshot {
666                position: info.get_pos(),
667                scale: info.get_scale(),
668                alignment: ObsAlignment::from_bits_retain(info.get_alignment()),
669                rotation: info.get_rot(),
670                bounds: info.get_bounds(),
671                bounds_type,
672                bounds_alignment: ObsAlignment::from_bits_retain(info.get_bounds_alignment()),
673                crop_to_bounds: info.get_crop_to_bounds(),
674                crop: self.crop()?,
675                scale_filter: self.scale_filter()?,
676                blend_method: self.blend_method()?,
677                blend_mode: self.blend_mode()?,
678            })
679        }
680
681        /// Restores a transform snapshot through the same managed actor seam as individual setters.
682        fn apply_transform_snapshot(
683            &self,
684            snapshot: &ObsSceneItemTransformSnapshot,
685        ) -> Result<(), ObsError> {
686            let info = ObsTransformInfoBuilder::new()
687                .set_pos(snapshot.position)
688                .set_scale(snapshot.scale)
689                .set_alignment(snapshot.alignment)
690                .set_rot(snapshot.rotation)
691                .set_bounds(snapshot.bounds)
692                .set_bounds_type(snapshot.bounds_type)
693                .set_bounds_alignment(snapshot.bounds_alignment)
694                .set_crop_to_bounds(snapshot.crop_to_bounds)
695                .build_with_fallback(self)?;
696            self.set_transform_info(&info)?;
697            self.set_crop(snapshot.crop)?;
698            self.set_scale_filter(snapshot.scale_filter)?;
699            self.set_blend_method(snapshot.blend_method)?;
700            self.set_blend_mode(snapshot.blend_mode)
701        }
702
703        fn state_snapshot(&self) -> Result<ObsSceneItemStateSnapshot, ObsError> {
704            Ok(ObsSceneItemStateSnapshot {
705                transform: self.transform_snapshot()?,
706                visible: self.is_visible()?,
707                locked: self.is_locked()?,
708                order_position: self.order_position()?,
709            })
710        }
711
712        fn apply_state_snapshot(
713            &self,
714            snapshot: &ObsSceneItemStateSnapshot,
715        ) -> Result<(), ObsError> {
716            self.apply_transform_snapshot(&snapshot.transform)?;
717            self.set_visible(snapshot.visible)?;
718            self.set_locked(snapshot.locked)?;
719            self.set_order_position(snapshot.order_position)
720        }
721
722        /// Preferred shorthand for [`SceneItemTrait::get_source_position`].
723        fn position(&self) -> Result<Vec2, ObsError> {
724            self.get_source_position()
725        }
726
727        /// Preferred shorthand for [`SceneItemTrait::set_source_position`].
728        fn set_position(&self, position: Vec2) -> Result<(), ObsError> {
729            self.set_source_position(position)
730        }
731
732        /// Preferred shorthand for [`SceneItemTrait::get_source_scale`].
733        fn scale(&self) -> Result<Vec2, ObsError> {
734            self.get_source_scale()
735        }
736
737        /// Preferred shorthand for [`SceneItemTrait::set_source_scale`].
738        fn set_scale(&self, scale: Vec2) -> Result<(), ObsError> {
739            self.set_source_scale(scale)
740        }
741
742        /// Sets the scale of the given source in this scene.
743        fn set_source_scale(&self, scale: Vec2) -> Result<(), ObsError> {
744            let self_ptr = self.__native_handle().clone();
745
746            run_with_obs!(self.runtime(), (self_ptr), move || {
747                let scale: libobs::vec2 = scale.into();
748
749                unsafe {
750                    // SAFETY: self_ptr retains the native scene-item reference through this actor
751                    // call.
752                    libobs::obs_sceneitem_set_scale(self_ptr.get_ptr(), &scale);
753                }
754            })?;
755
756            Ok(())
757        }
758    }
759}
760
761impl SceneItemTraitSealed for ObsSceneItemHandle {
762    fn __native_handle(&self) -> &SmartPointerSendable<*mut obs_scene_item> {
763        &self.scene_item_ptr
764    }
765
766    fn __removed_flag(&self) -> &Arc<Mutex<bool>> {
767        &self.removed
768    }
769}
770
771impl SceneItemTrait for ObsSceneItemHandle {
772    fn runtime(&self) -> ObsRuntime {
773        self.runtime.clone()
774    }
775}
776
777impl<T: ObsSourceTrait + Clone> SceneItemTraitSealed for ObsSceneItemRef<T> {
778    fn __native_handle(&self) -> &SmartPointerSendable<*mut obs_scene_item> {
779        &self.scene_item_ptr
780    }
781
782    fn __removed_flag(&self) -> &Arc<Mutex<bool>> {
783        &self.removed
784    }
785}
786
787impl<T: ObsSourceTrait + Clone> SceneItemTrait for ObsSceneItemRef<T> {
788    fn runtime(&self) -> ObsRuntime {
789        self.runtime.clone()
790    }
791}
792
793impl<T> ObsSceneItemRef<T>
794where
795    T: ObsSourceTrait + Clone,
796{
797    /// Returns a reference to the specific source type.
798    pub fn inner_source(&self) -> &T {
799        &self.underlying_source
800    }
801
802    /// Returns a reference to the specific source type.
803    pub fn inner_source_mut(&mut self) -> &mut T {
804        &mut self.underlying_source
805    }
806}
807
808// The macro doesn't support generics yet, so we implement it manually
809//impl_eq_of_ptr!(SceneItemRef<T>, scene_item_ptr);
810
811impl<T: ObsSourceTrait + Clone> PartialEq for ObsSceneItemRef<T> {
812    fn eq(&self, other: &Self) -> bool {
813        self.scene_item_ptr.native_id() == other.scene_item_ptr.native_id()
814    }
815}
816
817impl<T: ObsSourceTrait + Clone> Eq for ObsSceneItemRef<T> {}
818
819impl<T: ObsSourceTrait + Clone> Hash for ObsSceneItemRef<T> {
820    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
821        self.scene_item_ptr.native_id().hash(state);
822    }
823}
824
825#[cfg(test)]
826mod crop_tests {
827    use super::ObsSceneItemCrop;
828
829    #[test]
830    fn obs_scene_item_crop_round_trips_native_layout() {
831        let crop = ObsSceneItemCrop::new(1, 2, 3, 4);
832        let native: libobs::obs_sceneitem_crop = crop.into();
833        assert_eq!(native.left, 1);
834        assert_eq!(native.top, 2);
835        assert_eq!(native.right, 3);
836        assert_eq!(native.bottom, 4);
837        assert_eq!(ObsSceneItemCrop::from(native), crop);
838    }
839
840    #[test]
841    fn obs_scene_item_crop_default_is_uncropped() {
842        assert_eq!(
843            ObsSceneItemCrop::default(),
844            ObsSceneItemCrop::new(0, 0, 0, 0)
845        );
846    }
847}