1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
// Copyright 2021-2022 Aaron Erhardt <aaron.erhardt@t-online.de>
// Copyright 2022 System76 <info@system76.com>
// SPDX-License-Identifier: MIT or Apache-2.0

use std::fmt::Debug;

use crate::channel::{AsyncComponentSender, Sender};
use crate::loading_widgets::LoadingWidgets;

use super::{AsyncComponentBuilder, AsyncComponentParts};

/// Asynchronous variant of [`Component`](crate::Component).
///
/// `AsyncComponent` is powerful and flexible, but for many use-cases the [`SimpleAsyncComponent`]
/// convenience trait will suffice.
#[async_trait::async_trait(?Send)]
pub trait AsyncComponent: Sized + 'static {
    /// Messages which are received from commands executing in the background.
    type CommandOutput: Debug + Send + 'static;

    /// The message type that the component accepts as inputs.
    type Input: Debug + 'static;

    /// The message type that the component provides as outputs.
    type Output: Debug + 'static;

    /// The parameter used to initialize the component.
    type Init;

    /// The widget that was constructed by the component.
    type Root: Debug + Clone;

    /// The type that's used for storing widgets created for this component.
    type Widgets: 'static;

    /// Create a builder for this component.
    #[must_use]
    fn builder() -> AsyncComponentBuilder<Self> {
        AsyncComponentBuilder::<Self>::default()
    }

    /// Initializes the root widget
    #[must_use]
    fn init_root() -> Self::Root;

    /// Allows you to initialize the root widget with a temporary value
    /// as a placeholder until the [`init()`](AsyncComponent::init)
    /// future completes.
    ///
    /// This method does nothing by default.
    #[must_use]
    fn init_loading_widgets(_root: &mut Self::Root) -> Option<LoadingWidgets> {
        None
    }

    /// Creates the initial model and view, docking it into the component.
    async fn init(
        init: Self::Init,
        root: Self::Root,
        sender: AsyncComponentSender<Self>,
    ) -> AsyncComponentParts<Self>;

    /// Processes inputs received by the component.
    #[allow(unused)]
    async fn update(
        &mut self,
        message: Self::Input,
        sender: AsyncComponentSender<Self>,
        root: &Self::Root,
    ) {
    }

    /// Defines how the component should respond to command updates.
    #[allow(unused)]
    async fn update_cmd(
        &mut self,
        message: Self::CommandOutput,
        sender: AsyncComponentSender<Self>,
        root: &Self::Root,
    ) {
    }

    /// Updates the model and view upon completion of a command.
    ///
    /// Overriding this method is helpful if you need access to the widgets while processing a
    /// command output.
    ///
    /// The default implementation of this method calls [`update_cmd`] followed by [`update_view`].
    /// If you override this method while using the [`component`] macro, you must remember to call
    /// [`update_view`] in your implementation. Otherwise, the view will not reflect the updated
    /// model.
    ///
    /// [`update_cmd`]: Self::update_cmd
    /// [`update_view`]: Self::update_view
    /// [`component`]: relm4_macros::component
    async fn update_cmd_with_view(
        &mut self,
        widgets: &mut Self::Widgets,
        message: Self::CommandOutput,
        sender: AsyncComponentSender<Self>,
        root: &Self::Root,
    ) {
        self.update_cmd(message, sender.clone(), root).await;
        self.update_view(widgets, sender);
    }

    /// Updates the view after the model has been updated.
    #[allow(unused)]
    fn update_view(&self, widgets: &mut Self::Widgets, sender: AsyncComponentSender<Self>) {}

    /// Updates the model and view when a new input is received.
    ///
    /// Overriding this method is helpful if you need access to the widgets while processing an
    /// input.
    ///
    /// The default implementation of this method calls [`update`] followed by [`update_view`]. If
    /// you override this method while using the [`component`] macro, you must remember to
    /// call [`update_view`] in your implementation. Otherwise, the view will not reflect the
    /// updated model.
    ///
    /// [`update`]: Self::update
    /// [`update_view`]: Self::update_view
    /// [`component`]: relm4_macros::component
    async fn update_with_view(
        &mut self,
        widgets: &mut Self::Widgets,
        message: Self::Input,
        sender: AsyncComponentSender<Self>,
        root: &Self::Root,
    ) {
        self.update(message, sender.clone(), root).await;
        self.update_view(widgets, sender);
    }

    /// Last method called before a component is shut down.
    ///
    /// This method is guaranteed to be called even when the entire application is shut down.
    #[allow(unused)]
    fn shutdown(&mut self, widgets: &mut Self::Widgets, output: Sender<Self::Output>) {}

    /// An identifier for the component used for debug logging.
    ///
    /// The default implementation of this method uses the address of the component, but
    /// implementations are free to provide more meaningful identifiers.
    #[must_use]
    fn id(&self) -> String {
        format!("{:p}", &self)
    }
}

/// Asynchronous variant of [`SimpleComponent`](crate::SimpleComponent).
#[async_trait::async_trait(?Send)]
pub trait SimpleAsyncComponent: Sized + 'static {
    /// The message type that the component accepts as inputs.
    type Input: Debug + 'static;

    /// The message type that the component provides as outputs.
    type Output: Debug + 'static;

    /// The parameter used to initialize the component.
    type Init;

    /// The widget that was constructed by the component.
    type Root: Debug + Clone;

    /// The type that's used for storing widgets created for this component.
    type Widgets: 'static;

    /// Initializes the root widget
    #[must_use]
    fn init_root() -> Self::Root;

    /// Allows you to initialize the root widget with a temporary value
    /// as a placeholder until the [`init()`](AsyncComponent::init)
    /// future completes.
    ///
    /// This method does nothing by default.
    #[must_use]
    fn init_loading_widgets(_root: &mut Self::Root) -> Option<LoadingWidgets> {
        None
    }

    /// Creates the initial model and view, docking it into the component.
    async fn init(
        init: Self::Init,
        root: Self::Root,
        sender: AsyncComponentSender<Self>,
    ) -> AsyncComponentParts<Self>;

    /// Processes inputs received by the component.
    #[allow(unused)]
    async fn update(&mut self, message: Self::Input, sender: AsyncComponentSender<Self>) {}

    /// Defines how the component should respond to command updates.
    #[allow(unused)]
    async fn update_cmd(&mut self, input: &Sender<Self::Input>, output: Sender<Self::Output>) {}

    /// Updates the view after the model has been updated.
    #[allow(unused)]
    fn update_view(&self, widgets: &mut Self::Widgets, sender: AsyncComponentSender<Self>) {}

    /// Last method called before a component is shut down.
    ///
    /// This method is guaranteed to be called even when the entire application is shut down.
    #[allow(unused)]
    fn shutdown(&mut self, widgets: &mut Self::Widgets, output: Sender<Self::Output>) {}
}

#[async_trait::async_trait(?Send)]
impl<C> AsyncComponent for C
where
    C: SimpleAsyncComponent,
{
    type Init = C::Init;
    type Input = C::Input;
    type Output = C::Output;
    type Root = C::Root;
    type Widgets = C::Widgets;

    type CommandOutput = ();

    fn init_root() -> Self::Root {
        C::init_root()
    }

    fn init_loading_widgets(root: &mut Self::Root) -> Option<LoadingWidgets> {
        C::init_loading_widgets(root)
    }

    async fn init(
        init: Self::Init,
        root: Self::Root,
        sender: AsyncComponentSender<Self>,
    ) -> AsyncComponentParts<Self> {
        C::init(init, root, sender).await
    }

    async fn update(
        &mut self,
        message: Self::Input,
        sender: AsyncComponentSender<Self>,
        _root: &Self::Root,
    ) {
        C::update(self, message, sender).await;
    }

    fn update_view(&self, widgets: &mut Self::Widgets, sender: AsyncComponentSender<Self>) {
        C::update_view(self, widgets, sender);
    }

    fn shutdown(&mut self, widgets: &mut Self::Widgets, output: Sender<Self::Output>) {
        self.shutdown(widgets, output);
    }
}

/// An empty, non-interactive component as a placeholder for tests.
#[async_trait::async_trait(?Send)]
impl SimpleAsyncComponent for () {
    type Input = ();
    type Output = ();
    type Init = ();
    type Root = ();
    type Widgets = ();

    fn init_root() -> Self::Root {}

    async fn init(
        _init: Self::Init,
        _root: Self::Root,
        _sender: AsyncComponentSender<Self>,
    ) -> AsyncComponentParts<Self> {
        AsyncComponentParts {
            model: (),
            widgets: (),
        }
    }
}