Skip to main content

whisker_linux/
module.rs

1use std::collections::{HashMap, HashSet};
2use std::fmt;
3use std::rc::Rc;
4
5use gtk4 as gtk;
6use whisker::runtime::module::{ModuleEventEmitter, ModulePromise, RustModuleDefinition};
7use whisker_protocol::{
8    MeasuredSize, ModuleMeasureRequest, NodeId, TextStyleSnapshot, WhiskerValue,
9};
10
11use crate::scene::{ProviderEvent, SharedScrollFeedback};
12
13/// Linux implementation of one module, as returned by its Host crate.
14#[derive(Clone, Default)]
15pub struct LinuxModuleDefinition {
16    pub(crate) service: RustModuleDefinition,
17    pub(crate) views: Vec<LinuxViewFactory>,
18}
19
20impl fmt::Debug for LinuxModuleDefinition {
21    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
22        formatter
23            .debug_struct("LinuxModuleDefinition")
24            .field("service", &self.service)
25            .field(
26                "views",
27                &self.views.iter().map(|view| &view.name).collect::<Vec<_>>(),
28            )
29            .finish()
30    }
31}
32
33impl From<RustModuleDefinition> for LinuxModuleDefinition {
34    fn from(service: RustModuleDefinition) -> Self {
35        Self {
36            service,
37            views: Vec::new(),
38        }
39    }
40}
41
42impl LinuxModuleDefinition {
43    /// Starts an empty Linux module declaration.
44    pub fn new() -> Self {
45        Self::default()
46    }
47
48    /// Declares the package-qualified service module name.
49    pub fn name(mut self, name: impl Into<String>) -> Self {
50        self.service = self.service.name(name);
51        self
52    }
53
54    /// Declares one synchronous service function.
55    pub fn function(
56        mut self,
57        name: impl Into<String>,
58        handler: impl Fn(&[WhiskerValue], &ModuleEventEmitter) -> WhiskerValue + 'static,
59    ) -> Self {
60        self.service = self.service.function(name, handler);
61        self
62    }
63
64    /// Declares one asynchronous service function.
65    pub fn async_function(
66        mut self,
67        name: impl Into<String>,
68        handler: impl Fn(&[WhiskerValue], ModulePromise, &ModuleEventEmitter) + 'static,
69    ) -> Self {
70        self.service = self.service.async_function(name, handler);
71        self
72    }
73
74    /// Declares one service event.
75    pub fn event(mut self, name: impl Into<String>) -> Self {
76        self.service = self.service.event(name);
77        self
78    }
79
80    /// Declares one view backed by a GTK widget.
81    pub fn view<W>(mut self, view: LinuxViewDefinition<W>) -> Self
82    where
83        W: LinuxView,
84    {
85        self.views.push(view.into_factory());
86        self
87    }
88}
89
90/// Content object of one mounted module view.
91pub trait LinuxView: 'static {
92    /// GTK widget placed in the node's content box.
93    fn widget(&self) -> gtk::Widget;
94}
95
96impl LinuxView for gtk::Widget {
97    fn widget(&self) -> gtk::Widget {
98        self.clone()
99    }
100}
101
102/// Delivers native widget events to the node that owns the widget.
103#[derive(Clone)]
104pub struct LinuxEventEmitter {
105    node: NodeId,
106    events: Rc<HashSet<String>>,
107    feedback: SharedScrollFeedback,
108    wake: Rc<dyn Fn()>,
109}
110
111impl LinuxEventEmitter {
112    /// Queues one declared event for the next runtime turn; undeclared events are dropped.
113    pub fn emit(&self, event: impl Into<String>, detail: WhiskerValue) -> bool {
114        let name = event.into();
115        if !self.events.contains(&name) {
116            return false;
117        }
118        self.feedback.borrow_mut().push_event(ProviderEvent {
119            target: self.node,
120            name,
121            detail,
122        });
123        (self.wake)();
124        true
125    }
126}
127
128type PropSetter<W> = Rc<dyn Fn(&W, &WhiskerValue)>;
129type PropClearer<W> = Rc<dyn Fn(&W)>;
130type CommandHandler<W> = Rc<dyn Fn(&W, &WhiskerValue)>;
131type TextStyleHandler<W> = Rc<dyn Fn(&W, &TextStyleSnapshot)>;
132pub(crate) type MeasureHandler = Rc<dyn Fn(&ModuleMeasureRequest) -> Option<MeasuredSize>>;
133
134struct ViewBindings<W> {
135    properties: HashMap<String, (PropSetter<W>, PropClearer<W>)>,
136    commands: HashMap<String, CommandHandler<W>>,
137    text_style: Option<TextStyleHandler<W>>,
138}
139
140/// The `View { Prop / Events / Command }` portion of a Linux declaration.
141pub struct LinuxViewDefinition<W> {
142    name: String,
143    create: Rc<dyn Fn(LinuxEventEmitter) -> W>,
144    events: HashSet<String>,
145    bindings: ViewBindings<W>,
146    measurement: Option<MeasureHandler>,
147}
148
149impl<W> LinuxViewDefinition<W>
150where
151    W: LinuxView,
152{
153    /// Declares how the widget is created for each mounted node.
154    pub fn new(name: impl Into<String>, create: impl Fn(LinuxEventEmitter) -> W + 'static) -> Self {
155        Self {
156            name: name.into(),
157            create: Rc::new(create),
158            events: HashSet::new(),
159            bindings: ViewBindings {
160                properties: HashMap::new(),
161                commands: HashMap::new(),
162                text_style: None,
163            },
164            measurement: None,
165        }
166    }
167
168    /// Declares one property by its stable Host name.
169    pub fn prop(
170        mut self,
171        property: impl Into<String>,
172        set: impl Fn(&W, &WhiskerValue) + 'static,
173        clear: impl Fn(&W) + 'static,
174    ) -> Self {
175        let property = property.into();
176        assert!(
177            self.bindings
178                .properties
179                .insert(property.clone(), (Rc::new(set), Rc::new(clear)))
180                .is_none(),
181            "duplicate Linux property binding for {property}"
182        );
183        self
184    }
185
186    /// Declares one event by its stable Host name.
187    pub fn event(mut self, event: impl Into<String>) -> Self {
188        let event = event.into();
189        assert!(
190            self.events.insert(event.clone()),
191            "duplicate Linux event binding for {event}"
192        );
193        self
194    }
195
196    /// Declares one command by its stable Host name.
197    pub fn command(
198        mut self,
199        command: impl Into<String>,
200        handler: impl Fn(&W, &WhiskerValue) + 'static,
201    ) -> Self {
202        let command = command.into();
203        assert!(
204            self.bindings
205                .commands
206                .insert(command.clone(), Rc::new(handler))
207                .is_none(),
208            "duplicate Linux command binding for {command}"
209        );
210        self
211    }
212
213    /// Receives the resolved inherited text style.
214    pub fn text_style(mut self, update: impl Fn(&W, &TextStyleSnapshot) + 'static) -> Self {
215        assert!(
216            self.bindings.text_style.replace(Rc::new(update)).is_none(),
217            "duplicate Linux TextStyle binding for {}",
218            self.name
219        );
220        self
221    }
222
223    /// Returns the intrinsic size, or `None` when the request is unsupported.
224    pub fn measure(
225        mut self,
226        measure: impl Fn(&ModuleMeasureRequest) -> Option<MeasuredSize> + 'static,
227    ) -> Self {
228        assert!(
229            self.measurement.replace(Rc::new(measure)).is_none(),
230            "duplicate Linux Measurement binding for {}",
231            self.name
232        );
233        self
234    }
235
236    fn into_factory(self) -> LinuxViewFactory {
237        let create = self.create;
238        let bindings = Rc::new(self.bindings);
239        LinuxViewFactory {
240            name: self.name,
241            events: Rc::new(self.events),
242            measurement: self.measurement,
243            create: Rc::new(move |emitter| {
244                Box::new(BoundView {
245                    widget: create(emitter),
246                    bindings: Rc::clone(&bindings),
247                })
248            }),
249        }
250    }
251}
252
253/// Type-erased view declaration bound to an element by name.
254#[derive(Clone)]
255pub(crate) struct LinuxViewFactory {
256    pub(crate) name: String,
257    events: Rc<HashSet<String>>,
258    pub(crate) measurement: Option<MeasureHandler>,
259    create: Rc<dyn Fn(LinuxEventEmitter) -> Box<dyn NativeView>>,
260}
261
262impl LinuxViewFactory {
263    pub(crate) fn create(
264        &self,
265        node: NodeId,
266        feedback: SharedScrollFeedback,
267        wake: Rc<dyn Fn()>,
268    ) -> Box<dyn NativeView> {
269        (self.create)(LinuxEventEmitter {
270            node,
271            events: Rc::clone(&self.events),
272            feedback,
273            wake,
274        })
275    }
276}
277
278/// One mounted module widget.
279pub(crate) trait NativeView {
280    fn widget(&self) -> gtk::Widget;
281    fn set_property(&self, property: &str, value: Option<&WhiskerValue>);
282    fn invoke(&self, command: &str, arguments: &WhiskerValue);
283    fn set_text_style(&self, style: &TextStyleSnapshot);
284}
285
286struct BoundView<W> {
287    widget: W,
288    bindings: Rc<ViewBindings<W>>,
289}
290
291impl<W> NativeView for BoundView<W>
292where
293    W: LinuxView,
294{
295    fn widget(&self) -> gtk::Widget {
296        self.widget.widget()
297    }
298
299    fn set_property(&self, property: &str, value: Option<&WhiskerValue>) {
300        if let Some((set, clear)) = self.bindings.properties.get(property) {
301            match value {
302                Some(value) => set(&self.widget, value),
303                None => clear(&self.widget),
304            }
305        }
306    }
307
308    fn invoke(&self, command: &str, arguments: &WhiskerValue) {
309        if let Some(handler) = self.bindings.commands.get(command) {
310            handler(&self.widget, arguments);
311        }
312    }
313
314    fn set_text_style(&self, style: &TextStyleSnapshot) {
315        if let Some(update) = &self.bindings.text_style {
316            update(&self.widget, style);
317        }
318    }
319}