Skip to main content

ferroui_base/rendering/composition/server/
server_composition_surface.rs

1use super::IServerObject;
2use crate::platform::{IBitmapImpl, IDrawingContextImpl};
3use crate::{Rect, Size};
4use std::cell::RefCell;
5use std::rc::Rc;
6
7/// The `Changed` delegate of a server-side surface: the callbacks of the
8/// visuals that show it.
9#[derive(Default)]
10pub struct ServerCompositionSurfaceChanged {
11    handlers: RefCell<Vec<(usize, Rc<dyn Fn()>)>>,
12}
13
14impl ServerCompositionSurfaceChanged {
15    pub fn new() -> Self {
16        Self::default()
17    }
18
19    /// `Changed += handler`; `key` identifies the subscriber.
20    pub fn add(&self, key: usize, handler: Rc<dyn Fn()>) {
21        self.handlers.borrow_mut().push((key, handler));
22    }
23
24    /// `Changed -= handler`.
25    pub fn remove(&self, key: usize) {
26        let mut handlers = self.handlers.borrow_mut();
27        if let Some(index) = handlers.iter().rposition(|(k, _)| *k == key) {
28            handlers.remove(index);
29        }
30    }
31
32    /// `Changed?.Invoke()`.
33    pub fn invoke(&self) {
34        let handlers: Vec<_> = self.handlers.borrow().iter().map(|(_, h)| h.clone()).collect();
35        for handler in handlers {
36            handler();
37        }
38    }
39}
40
41/// Server-side counterpart of a composition surface: something that
42/// provides a bitmap to the surface visuals that show it.
43///
44/// The WinUI port adds the surfaces whose content is not a bitmap (a
45/// visual surface renders a visual subtree): what a surface visual or a
46/// surface brush shows goes through [`natural_size`](Self::natural_size)
47/// and [`draw`](Self::draw), whose defaults use the bitmap.
48pub trait IServerCompositionSurface: IServerObject {
49    /// The current content of the surface.
50    fn bitmap(&self) -> Option<std::sync::Arc<crate::platform::SharedBitmapImpl>>;
51
52    /// Raised when the content changed.
53    fn changed(&self) -> &ServerCompositionSurfaceChanged;
54
55    /// The size of the content in device independent pixels (the natural
56    /// size of WinUI's surfaces), which a surface brush lays out; `None`
57    /// while the surface has no content. The default is the size of the
58    /// bitmap at its DPI.
59    fn natural_size(&self) -> Option<Size> {
60        let bitmap = self.bitmap()?;
61        let size = bitmap.pixel_size().to_size_with_dpi_vector(bitmap.dpi());
62        (size.width > 0.0 && size.height > 0.0).then_some(size)
63    }
64
65    /// Draws the whole content of the surface into `dest`, in the
66    /// coordinates of `canvas`. The default draws the bitmap.
67    fn draw(&self, canvas: &mut dyn IDrawingContextImpl, dest: Rect, opacity: f64) {
68        let Some(bitmap) = self.bitmap() else { return };
69        canvas.draw_bitmap(&*bitmap, opacity, Rect::from_size(bitmap.pixel_size().to_size(1.0)), dest);
70    }
71}