Skip to main content

termrs_core/
widget.rs

1use crate::{
2    input::{Event, EventStatus},
3    render::{Position, RenderContext, Size},
4};
5
6mod event_context;
7
8pub use copyrs::clipboard;
9pub use copyrs::{Clipboard, ClipboardBinaryKind, ClipboardContent, ClipboardTextKind, Result};
10pub use event_context::*;
11
12pub trait LayoutInfo {
13    /// Returns the bounding box size.
14    fn bounds(&self) -> Size;
15}
16
17impl LayoutInfo for Size {
18    fn bounds(&self) -> Size {
19        *self
20    }
21}
22
23/// Information about [`Widget`] rendering.
24pub trait RenderInfo {
25    /// Returns bounding box size
26    /// of the rendered content
27    fn bounds(&self) -> Size;
28
29    /// Returns top-left position
30    /// of the bounding box.
31    fn position(&self) -> Position;
32}
33
34pub struct SimpleRenderInfo {
35    pub bounds: Size,
36    pub position: Position,
37}
38
39impl RenderInfo for SimpleRenderInfo {
40    fn bounds(&self) -> Size {
41        self.bounds
42    }
43
44    fn position(&self) -> Position {
45        self.position
46    }
47}
48
49impl SimpleRenderInfo {
50    pub fn new(bounds: Size, position: Position) -> Self {
51        Self { bounds, position }
52    }
53}
54
55/// An object which can render itself to the [`RenderContext`]
56/// and can handle input.
57pub trait Widget<Message> {
58    type LayoutInfo: LayoutInfo;
59    type RenderInfo: RenderInfo;
60
61    /// Renders itself to the given context
62    /// based on the state.
63    fn render(
64        &self,
65        position: Position,
66        layout_info: &Self::LayoutInfo,
67        context: &mut dyn RenderContext,
68    ) -> std::io::Result<Self::RenderInfo>;
69
70    /// Calculates and returns layout information
71    /// based on the available size.
72    fn layout(&self, available_size: Size) -> Self::LayoutInfo;
73
74    /// Handled the given event.
75    fn on_event(
76        &mut self,
77        event: &Event,
78        render_info: &Self::RenderInfo,
79        event_context: &mut dyn EventContext<Message>,
80    ) -> EventStatus {
81        let _ = event;
82        let _ = render_info;
83        let _ = event_context;
84
85        EventStatus::Ignored
86    }
87}