Skip to main content

rsiot/components/cmp_slint/
config.rs

1use std::time::Duration;
2
3use slint::ComponentHandle;
4use tokio::sync::mpsc;
5use tracing::warn;
6
7use crate::message::MsgDataBound;
8
9pub type FnInput<TMsg, TMainWindow> = fn(TMsg, TMainWindow);
10pub type FnOutput<TMsg, TMainWindow> = fn(TMainWindow, OutputSender<TMsg>);
11
12// ANCHOR: Config
13/// Настройки компонента cmp_slint
14pub struct Config<TMsg, TMainWindow>
15where
16    Self: Sync,
17    TMsg: MsgDataBound,
18    TMainWindow: ComponentHandle,
19{
20    /// Ссылка на главное окно
21    pub slint_window: super::SlintWindow<TMainWindow>,
22
23    /// Функция обработки входящих сообщений
24    ///
25    /// *Пример:*
26    ///
27    /// ```rust
28    /// fn_input: |msg, w| {
29    ///     let input_data = w.global::<Input>();
30    ///     let Some(msg) = msg.get_custom_data() else {
31    ///         return;
32    ///     };
33    ///     match msg {
34    ///         Custom::LiveCounter(msg) => match msg {
35    ///             Livecounter::Counter(c) => input_data.set_value_from_phone(c as i32),
36    ///         },
37    ///         _ => (),
38    ///     };
39    /// },
40    /// ```
41    pub fn_input: FnInput<TMsg, TMainWindow>,
42
43    /// Функция генерирования исходящих сообщений
44    pub fn_output: FnOutput<TMsg, TMainWindow>,
45
46    /// Период фильтрации исходящих сообщений
47    pub output_period: Duration,
48}
49// ANCHOR: Config
50
51impl<TMsg, TMainWindow> Clone for Config<TMsg, TMainWindow>
52where
53    TMsg: MsgDataBound,
54    TMainWindow: ComponentHandle,
55{
56    fn clone(&self) -> Self {
57        Self {
58            slint_window: self.slint_window.clone(),
59            fn_input: self.fn_input,
60            fn_output: self.fn_output,
61            output_period: Duration::from_millis(100),
62        }
63    }
64}
65
66/// Отправка исходящих сообщений из коллбеков Slint
67#[derive(Clone)]
68pub struct OutputSender<TMsg>
69where
70    TMsg: MsgDataBound,
71{
72    tx: mpsc::Sender<TMsg>,
73}
74impl<TMsg> OutputSender<TMsg>
75where
76    TMsg: MsgDataBound,
77{
78    /// Создать новый экземпляр OutputSender
79    pub fn new(tx: &mpsc::Sender<TMsg>) -> Self {
80        Self { tx: tx.clone() }
81    }
82
83    /// Отправить исходящее сообщение
84    pub fn send(&self, msg: TMsg) {
85        let res = self.tx.blocking_send(msg);
86
87        if let Err(e) = res {
88            warn!("Error sending from slint callback: {e:?}");
89        }
90    }
91}