raui_core/widget/component/
mod.rs

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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
pub mod containers;
pub mod image_box;
pub mod interactive;
pub mod space_box;
pub mod text_box;

use crate::{
    messenger::Message,
    props::{Props, PropsData},
    widget::{
        context::WidgetContext,
        node::{WidgetNode, WidgetNodePrefab},
        utils::{Rect, Vec2},
        FnWidget, WidgetId, WidgetIdOrRef, WidgetRef,
    },
    MessageData, PrefabValue, PropsData, Scalar,
};
use serde::{Deserialize, Serialize};
use std::{any::TypeId, collections::HashMap, convert::TryFrom};

fn is_false(v: &bool) -> bool {
    !*v
}

#[derive(PropsData, Debug, Default, Clone, Serialize, Deserialize)]
#[props_data(crate::props::PropsData)]
#[prefab(crate::Prefab)]
pub struct MessageForwardProps {
    #[serde(default)]
    #[serde(skip_serializing_if = "WidgetIdOrRef::is_none")]
    pub to: WidgetIdOrRef,
    #[serde(default)]
    #[serde(skip)]
    pub types: Vec<TypeId>,
    #[serde(default)]
    #[serde(skip_serializing_if = "is_false")]
    pub no_wrap: bool,
}

#[derive(MessageData, Debug, Clone)]
#[message_data(crate::messenger::MessageData)]
pub struct ForwardedMessage {
    pub sender: WidgetId,
    pub data: Message,
}

pub fn use_message_forward(context: &mut WidgetContext) {
    context.life_cycle.change(|context| {
        let (id, no_wrap, types) = match context.props.read::<MessageForwardProps>() {
            Ok(forward) => match forward.to.read() {
                Some(id) => (id, forward.no_wrap, &forward.types),
                _ => return,
            },
            _ => match context.shared_props.read::<MessageForwardProps>() {
                Ok(forward) => match forward.to.read() {
                    Some(id) => (id, forward.no_wrap, &forward.types),
                    _ => return,
                },
                _ => return,
            },
        };
        for msg in context.messenger.messages {
            let t = msg.as_any().type_id();
            if types.contains(&t) {
                if no_wrap {
                    context
                        .messenger
                        .write_raw(id.to_owned(), msg.clone_message());
                } else {
                    context.messenger.write(
                        id.to_owned(),
                        ForwardedMessage {
                            sender: context.id.to_owned(),
                            data: msg.clone_message(),
                        },
                    );
                }
            }
        }
    });
}

#[derive(MessageData, Debug, Copy, Clone, PartialEq)]
#[message_data(crate::messenger::MessageData)]
pub enum ResizeListenerSignal {
    Register,
    Unregister,
    Change(Vec2),
}

pub fn use_resize_listener(context: &mut WidgetContext) {
    context.life_cycle.mount(|context| {
        context.signals.write(ResizeListenerSignal::Register);
    });

    context.life_cycle.unmount(|context| {
        context.signals.write(ResizeListenerSignal::Unregister);
    });
}

#[derive(PropsData, Debug, Default, Clone, Serialize, Deserialize)]
#[props_data(crate::props::PropsData)]
#[prefab(crate::Prefab)]
pub struct RelativeLayoutProps {
    #[serde(default)]
    #[serde(skip_serializing_if = "WidgetIdOrRef::is_none")]
    pub relative_to: WidgetIdOrRef,
}

#[derive(MessageData, Debug, Clone, PartialEq)]
#[message_data(crate::messenger::MessageData)]
pub enum RelativeLayoutListenerSignal {
    /// (relative to id)
    Register(WidgetId),
    Unregister,
    /// (outer box size, inner box rect)
    Change(Vec2, Rect),
}

pub fn use_relative_layout_listener(context: &mut WidgetContext) {
    context.life_cycle.mount(|context| {
        if let Ok(props) = context.props.read::<RelativeLayoutProps>() {
            if let Some(relative_to) = props.relative_to.read() {
                context
                    .signals
                    .write(RelativeLayoutListenerSignal::Register(relative_to));
            }
        }
    });

    // TODO: when user will change widget IDs after mounting, we might want to re-register
    // this widget with new IDs.

    context.life_cycle.unmount(|context| {
        context
            .signals
            .write(RelativeLayoutListenerSignal::Unregister);
    });
}

#[derive(PropsData, Debug, Copy, Clone, Serialize, Deserialize)]
#[props_data(crate::props::PropsData)]
#[prefab(crate::Prefab)]
pub struct WidgetAlpha(pub Scalar);

impl Default for WidgetAlpha {
    fn default() -> Self {
        Self(1.0)
    }
}

impl WidgetAlpha {
    pub fn multiply(&mut self, alpha: Scalar) {
        self.0 *= alpha;
    }
}

#[derive(Clone)]
pub struct WidgetComponent {
    pub processor: FnWidget,
    pub type_name: String,
    pub key: Option<String>,
    pub idref: Option<WidgetRef>,
    pub props: Props,
    pub shared_props: Option<Props>,
    pub listed_slots: Vec<WidgetNode>,
    pub named_slots: HashMap<String, WidgetNode>,
}

impl WidgetComponent {
    pub fn new(processor: FnWidget, type_name: impl ToString) -> Self {
        Self {
            processor,
            type_name: type_name.to_string(),
            key: None,
            idref: None,
            props: Props::default(),
            shared_props: None,
            listed_slots: Vec::new(),
            named_slots: HashMap::new(),
        }
    }

    pub fn key<T>(mut self, v: T) -> Self
    where
        T: ToString,
    {
        self.key = Some(v.to_string());
        self
    }

    pub fn idref<T>(mut self, v: T) -> Self
    where
        T: Into<WidgetRef>,
    {
        self.idref = Some(v.into());
        self
    }

    pub fn maybe_idref<T>(mut self, v: Option<T>) -> Self
    where
        T: Into<WidgetRef>,
    {
        self.idref = v.map(|v| v.into());
        self
    }

    pub fn with_props<T>(mut self, v: T) -> Self
    where
        T: 'static + PropsData,
    {
        self.props.write(v);
        self
    }

    pub fn maybe_with_props<T>(self, v: Option<T>) -> Self
    where
        T: 'static + PropsData,
    {
        if let Some(v) = v {
            self.with_props(v)
        } else {
            self
        }
    }

    pub fn merge_props(mut self, v: Props) -> Self {
        let props = std::mem::take(&mut self.props);
        self.props = props.merge(v);
        self
    }

    pub fn with_shared_props<T>(mut self, v: T) -> Self
    where
        T: 'static + PropsData,
    {
        if let Some(props) = &mut self.shared_props {
            props.write(v);
        } else {
            self.shared_props = Some(Props::new(v));
        }
        self
    }

    pub fn maybe_with_shared_props<T>(self, v: Option<T>) -> Self
    where
        T: 'static + PropsData,
    {
        if let Some(v) = v {
            self.with_shared_props(v)
        } else {
            self
        }
    }

    pub fn merge_shared_props(mut self, v: Props) -> Self {
        if let Some(props) = self.shared_props.take() {
            self.shared_props = Some(props.merge(v));
        } else {
            self.shared_props = Some(v);
        }
        self
    }

    pub fn listed_slot<T>(mut self, v: T) -> Self
    where
        T: Into<WidgetNode>,
    {
        self.listed_slots.push(v.into());
        self
    }

    pub fn maybe_listed_slot<T>(mut self, v: Option<T>) -> Self
    where
        T: Into<WidgetNode>,
    {
        if let Some(v) = v {
            self.listed_slots.push(v.into());
        }
        self
    }

    pub fn listed_slots<I, T>(mut self, v: I) -> Self
    where
        I: IntoIterator<Item = T>,
        T: Into<WidgetNode>,
    {
        self.listed_slots.extend(v.into_iter().map(|v| v.into()));
        self
    }

    pub fn named_slot<T>(mut self, k: impl ToString, v: T) -> Self
    where
        T: Into<WidgetNode>,
    {
        self.named_slots.insert(k.to_string(), v.into());
        self
    }

    pub fn maybe_named_slot<T>(mut self, k: impl ToString, v: Option<T>) -> Self
    where
        T: Into<WidgetNode>,
    {
        if let Some(v) = v {
            self.named_slots.insert(k.to_string(), v.into());
        }
        self
    }

    pub fn named_slots<I, K, T>(mut self, v: I) -> Self
    where
        I: IntoIterator<Item = (K, T)>,
        K: ToString,
        T: Into<WidgetNode>,
    {
        self.named_slots
            .extend(v.into_iter().map(|(k, v)| (k.to_string(), v.into())));
        self
    }

    pub fn remap_props<F>(&mut self, mut f: F)
    where
        F: FnMut(Props) -> Props,
    {
        let props = std::mem::take(&mut self.props);
        self.props = (f)(props);
    }

    pub fn remap_shared_props<F>(&mut self, mut f: F)
    where
        F: FnMut(Props) -> Props,
    {
        if let Some(shared_props) = &mut self.shared_props {
            let props = std::mem::take(shared_props);
            *shared_props = (f)(props);
        } else {
            self.shared_props = Some((f)(Default::default()));
        }
    }
}

impl std::fmt::Debug for WidgetComponent {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut s = f.debug_struct("WidgetComponent");
        s.field("type_name", &self.type_name);
        if let Some(key) = &self.key {
            s.field("key", key);
        }
        s.field("props", &self.props);
        s.field("shared_props", &self.shared_props);
        if !self.listed_slots.is_empty() {
            s.field("listed_slots", &self.listed_slots);
        }
        if !self.named_slots.is_empty() {
            s.field("named_slots", &self.named_slots);
        }
        s.finish()
    }
}

impl TryFrom<WidgetNode> for WidgetComponent {
    type Error = ();

    fn try_from(node: WidgetNode) -> Result<Self, Self::Error> {
        if let WidgetNode::Component(v) = node {
            Ok(v)
        } else {
            Err(())
        }
    }
}

#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub(crate) struct WidgetComponentPrefab {
    #[serde(default)]
    pub type_name: String,
    #[serde(default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub key: Option<String>,
    #[serde(default)]
    pub props: PrefabValue,
    #[serde(default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub shared_props: Option<PrefabValue>,
    #[serde(default)]
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub listed_slots: Vec<WidgetNodePrefab>,
    #[serde(default)]
    #[serde(skip_serializing_if = "HashMap::is_empty")]
    pub named_slots: HashMap<String, WidgetNodePrefab>,
}