fui-rs 0.2.5

Retained Rust UI for native desktop and WebAssembly applications
Documentation
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
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
use crate::drag_drop::{DragDropEffects, DropProposal};
use crate::file::{register_browser_file, BrowserFile};
use crate::node::NodeRef;
use std::cell::RefCell;
#[cfg(feature = "native-runtime")]
use std::path::Path;

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum ExternalDragEventType {
    Enter = 1,
    Over = 2,
    Leave = 3,
    Drop = 4,
    Unknown,
}

impl ExternalDragEventType {
    pub(crate) fn from_raw(value: u32) -> Self {
        match value {
            1 => Self::Enter,
            2 => Self::Over,
            3 => Self::Leave,
            4 => Self::Drop,
            _ => Self::Unknown,
        }
    }
}

#[repr(u32)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ExternalDropItemKind {
    File = 1,
    Text = 2,
    Uri = 3,
    Unknown(u32),
}

impl ExternalDropItemKind {
    pub(crate) fn from_raw(value: u32) -> Self {
        match value {
            1 => Self::File,
            2 => Self::Text,
            3 => Self::Uri,
            _ => Self::Unknown(value),
        }
    }
}

#[derive(Clone, Debug)]
pub struct ExternalDropItemInfo {
    pub id: String,
    pub kind: ExternalDropItemKind,
    pub name: String,
    pub mime_type: Option<String>,
    pub size_bytes: f64,
    pub file: Option<BrowserFile>,
}

impl ExternalDropItemInfo {
    pub fn new(
        id: impl Into<String>,
        kind: ExternalDropItemKind,
        name: impl Into<String>,
        mime_type: Option<String>,
        size_bytes: f64,
        file: Option<BrowserFile>,
    ) -> Self {
        Self {
            id: id.into(),
            kind,
            name: name.into(),
            mime_type,
            size_bytes,
            file,
        }
    }

    #[cfg(feature = "native-runtime")]
    pub fn native_path(&self) -> Option<&Path> {
        (self.kind == ExternalDropItemKind::File).then(|| Path::new(&self.id))
    }
}

#[derive(Clone, Debug)]
pub struct ExternalDropEventArgs {
    pub x: f32,
    pub y: f32,
    pub modifiers: u32,
    pub items: Vec<ExternalDropItemInfo>,
}

impl ExternalDropEventArgs {
    pub fn new(x: f32, y: f32, modifiers: u32, items: Vec<ExternalDropItemInfo>) -> Self {
        Self {
            x,
            y,
            modifiers,
            items,
        }
    }
}

#[derive(Default)]
struct ExternalDropState {
    active_target: Option<NodeRef>,
    active_effect: DragDropEffects,
}

thread_local! {
    static STATE: RefCell<ExternalDropState> = RefCell::new(ExternalDropState::default());
}

fn is_default_proposal(proposal: DropProposal) -> bool {
    proposal.effect == DragDropEffects::None && !proposal.show_insertion_marker
}

fn normalize_effect(candidate: DragDropEffects) -> DragDropEffects {
    let masked = (candidate as u32)
        & ((DragDropEffects::Copy as u32)
            | (DragDropEffects::Move as u32)
            | (DragDropEffects::Link as u32));
    if masked == DragDropEffects::None as u32 {
        return DragDropEffects::None;
    }
    if (masked & DragDropEffects::Move as u32) != 0 {
        return DragDropEffects::Move;
    }
    if (masked & DragDropEffects::Copy as u32) != 0 {
        return DragDropEffects::Copy;
    }
    if (masked & DragDropEffects::Link as u32) != 0 {
        return DragDropEffects::Link;
    }
    DragDropEffects::None
}

fn resolve_drop_target(pointed_node: Option<NodeRef>) -> Option<NodeRef> {
    let mut current = pointed_node;
    while let Some(node) = current {
        if node.allows_external_drop() {
            return Some(node);
        }
        current = node.parent();
    }
    None
}

fn finish(
    state: &mut ExternalDropState,
    x: f32,
    y: f32,
    modifiers: u32,
    items: &[ExternalDropItemInfo],
    notify_target_leave: bool,
) {
    let target = state.active_target.take();
    state.active_effect = DragDropEffects::None;
    if notify_target_leave {
        if let Some(target) = target {
            target.handle_external_drag_leave(ExternalDropEventArgs::new(
                x,
                y,
                modifiers,
                items.to_vec(),
            ));
        }
    }
}

pub(crate) fn handle_event(
    pointed_node: Option<NodeRef>,
    event_type: ExternalDragEventType,
    x: f32,
    y: f32,
    modifiers: u32,
    items: Vec<ExternalDropItemInfo>,
) -> DragDropEffects {
    STATE.with(|slot| {
        let mut state = slot.borrow_mut();
        if event_type == ExternalDragEventType::Leave {
            finish(&mut state, x, y, modifiers, &items, true);
            return DragDropEffects::None;
        }

        let target = resolve_drop_target(pointed_node);
        let args = ExternalDropEventArgs::new(x, y, modifiers, items.clone());
        let mut proposal = DropProposal::none();
        let target_changed = match (&target, &state.active_target) {
            (Some(target), Some(active)) => target.handle() != active.handle(),
            (None, None) => false,
            _ => true,
        };
        if target_changed {
            if let Some(previous_target) = state.active_target.take() {
                previous_target.handle_external_drag_leave(args.clone());
            }
            state.active_target = target.clone();
            state.active_effect = DragDropEffects::None;
            if let Some(target) = target.as_ref() {
                if target.has_external_drag_enter_handler() {
                    proposal = target.handle_external_drag_enter(args.clone());
                }
            }
        }

        let Some(target) = target else {
            state.active_effect = DragDropEffects::None;
            return DragDropEffects::None;
        };

        if target.has_external_drag_over_handler() {
            proposal = target.handle_external_drag_over(args.clone());
        } else if is_default_proposal(proposal) {
            proposal = DropProposal::new(state.active_effect, false);
        }

        let effect = normalize_effect(proposal.effect);
        state.active_effect = effect;
        if event_type == ExternalDragEventType::Drop {
            if effect != DragDropEffects::None {
                target.handle_external_drop_event(args);
            }
            finish(&mut state, x, y, modifiers, &items, true);
        }
        effect
    })
}

pub(crate) fn handle_node_destroyed(node: NodeRef) {
    STATE.with(|slot| {
        let mut state = slot.borrow_mut();
        let Some(active_target) = state.active_target.as_ref() else {
            return;
        };
        if active_target.handle() == node.handle() {
            state.active_target = None;
            state.active_effect = DragDropEffects::None;
        }
    });
}

pub(crate) fn reset() {
    STATE.with(|slot| {
        let mut state = slot.borrow_mut();
        state.active_target = None;
        state.active_effect = DragDropEffects::None;
    });
}

pub(crate) fn decode_payload(
    payload_ptr: *const u8,
    payload_len: u32,
) -> Vec<ExternalDropItemInfo> {
    let mut items = Vec::new();
    if payload_ptr.is_null() || payload_len == 0 {
        return items;
    }
    let bytes = unsafe { std::slice::from_raw_parts(payload_ptr, payload_len as usize) };
    if bytes.len() < 4 {
        crate::logger::warn("ExternalDrop", "Malformed external drop payload header.");
        return items;
    }
    let mut cursor = 0usize;
    let item_count = u32::from_le_bytes(bytes[cursor..cursor + 4].try_into().unwrap_or([0; 4]));
    cursor += 4;
    for index in 0..item_count {
        if cursor + 12 > bytes.len() {
            crate::logger::warn(
                "ExternalDrop",
                &format!("Truncated external drop item header at index {}.", index),
            );
            return items;
        }
        let kind = ExternalDropItemKind::from_raw(u32::from_le_bytes(
            bytes[cursor..cursor + 4].try_into().unwrap_or([0; 4]),
        ));
        cursor += 4;
        let size_bytes = f64::from_le_bytes(bytes[cursor..cursor + 8].try_into().unwrap_or([0; 8]));
        cursor += 8;

        let Some(id) = decode_string(bytes, &mut cursor, "id", index) else {
            return items;
        };
        let Some(name) = decode_string(bytes, &mut cursor, "name", index) else {
            return items;
        };
        let Some(mime_type) = decode_string(bytes, &mut cursor, "mime", index) else {
            return items;
        };
        let mime_type = if mime_type.is_empty() {
            None
        } else {
            Some(mime_type)
        };
        let file = if kind == ExternalDropItemKind::File && !id.is_empty() {
            Some(register_browser_file(
                id.clone(),
                name.clone(),
                mime_type.clone(),
                size_bytes as u64,
                0,
            ))
        } else {
            None
        };
        items.push(ExternalDropItemInfo::new(
            id, kind, name, mime_type, size_bytes, file,
        ));
    }
    items
}

fn decode_string(bytes: &[u8], cursor: &mut usize, label: &str, index: u32) -> Option<String> {
    if *cursor + 4 > bytes.len() {
        crate::logger::warn(
            "ExternalDrop",
            &format!(
                "Truncated external drop item {} length at index {}.",
                label, index
            ),
        );
        return None;
    }
    let len = u32::from_le_bytes(bytes[*cursor..*cursor + 4].try_into().unwrap_or([0; 4])) as usize;
    *cursor += 4;
    if *cursor + len > bytes.len() {
        crate::logger::warn(
            "ExternalDrop",
            &format!("Truncated external drop item {} at index {}.", label, index),
        );
        return None;
    }
    let value = String::from_utf8_lossy(&bytes[*cursor..*cursor + len]).into_owned();
    *cursor += len;
    Some(value)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::drag_drop::DropProposal;
    use crate::event::reset as reset_events;
    use crate::node::{flex_box, Node};
    use std::cell::{Cell, RefCell};
    use std::rc::Rc;

    #[test]
    fn routes_external_drop_enter_over_leave_and_drop() {
        reset();
        reset_events();

        let root = flex_box();
        let target = flex_box();
        root.child(&target);

        let enter_count = Rc::new(Cell::new(0));
        let over_count = Rc::new(Cell::new(0));
        let leave_count = Rc::new(Cell::new(0));
        let drop_count = Rc::new(Cell::new(0));
        let last_name = Rc::new(RefCell::new(String::new()));

        target
            .allow_external_drop(true)
            .on_external_drag_enter({
                let enter_count = enter_count.clone();
                let last_name = last_name.clone();
                move |args| {
                    enter_count.set(enter_count.get() + 1);
                    if let Some(item) = args.items.first() {
                        last_name.replace(item.name.clone());
                    }
                    DropProposal::new(DragDropEffects::Copy, false)
                }
            })
            .on_external_drag_over({
                let over_count = over_count.clone();
                move |_args| {
                    over_count.set(over_count.get() + 1);
                    DropProposal::new(DragDropEffects::Copy, false)
                }
            })
            .on_external_drag_leave({
                let leave_count = leave_count.clone();
                move |_args| {
                    leave_count.set(leave_count.get() + 1);
                }
            })
            .on_external_drop({
                let drop_count = drop_count.clone();
                move |_args| {
                    drop_count.set(drop_count.get() + 1);
                }
            });

        let items = vec![ExternalDropItemInfo::new(
            "external-drop-1",
            ExternalDropItemKind::File,
            "todo.txt",
            Some("text/plain".to_string()),
            10.0,
            None,
        )];

        assert_eq!(
            handle_event(
                Some(target.node_ref()),
                ExternalDragEventType::Enter,
                12.0,
                18.0,
                0,
                items.clone(),
            ),
            DragDropEffects::Copy
        );
        assert_eq!(
            handle_event(
                Some(target.node_ref()),
                ExternalDragEventType::Over,
                14.0,
                19.0,
                0,
                items.clone(),
            ),
            DragDropEffects::Copy
        );
        assert_eq!(
            handle_event(
                Some(target.node_ref()),
                ExternalDragEventType::Drop,
                16.0,
                20.0,
                0,
                items,
            ),
            DragDropEffects::Copy
        );

        assert_eq!(enter_count.get(), 1);
        assert_eq!(over_count.get(), 3);
        assert_eq!(leave_count.get(), 1);
        assert_eq!(drop_count.get(), 1);
        assert_eq!(last_name.borrow().as_str(), "todo.txt");
    }

    #[test]
    fn decodes_unknown_external_item_kind_without_registering_file() {
        reset();
        reset_events();

        let mut payload = Vec::new();
        payload.extend_from_slice(&1u32.to_le_bytes());
        payload.extend_from_slice(&99u32.to_le_bytes());
        payload.extend_from_slice(&123.0f64.to_le_bytes());
        for value in ["external-drop-unknown", "note.txt", "text/plain"] {
            payload.extend_from_slice(&(value.len() as u32).to_le_bytes());
            payload.extend_from_slice(value.as_bytes());
        }

        let items = decode_payload(payload.as_ptr(), payload.len() as u32);
        assert_eq!(items.len(), 1);
        assert_eq!(items[0].kind, ExternalDropItemKind::Unknown(99));
        assert_eq!(items[0].id, "external-drop-unknown");
        assert_eq!(items[0].name, "note.txt");
        assert_eq!(items[0].mime_type.as_deref(), Some("text/plain"));
        assert!(items[0].file.is_none());
    }
}