rust_widgets 1.1.2

Pure Rust cross-platform native GUI library with hardware-adaptive rendering, 60+ widgets, touch/gesture support, i18n, and SVG-pipeline-accurate output
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
//! Shared backend state model used by platform adapters.
use super::{DropEvent, WidgetTriggerEvent, WidgetTriggerKind};
use crate::compat::HashMap;
use crate::compat::Mutex;
use crate::core::ObjectId;
use alloc::collections::VecDeque;
use core::hash::Hash;
use core::sync::atomic::{AtomicU64, Ordering};
/// Generic widget state record owned by backend state model.
#[cfg(all(feature = "serde", not(any(feature = "mini", feature = "embedded"))))]
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug)]
#[cfg_attr(
    all(feature = "serde", not(any(feature = "mini", feature = "embedded"))),
    derive(Serialize, Deserialize)
)]
pub struct WidgetRecord<K> {
    /// Backend-specific widget kind discriminator.
    pub kind: K,
    /// Widget text/content payload.
    pub text: String,
    /// Visibility state.
    pub visible: bool,
    /// Enabled/disabled state.
    pub enabled: bool,
    /// IME enabled state.
    pub ime_enabled: bool,
    /// Accessibility label.
    pub accessibility_name: String,
    /// Geometry origin x.
    pub x: i32,
    /// Geometry origin y.
    pub y: i32,
    /// Geometry width.
    pub width: u32,
    /// Geometry height.
    pub height: u32,
}
/// Thread-safe state model split from native handle adapters.
#[cfg_attr(
    all(feature = "serde", not(any(feature = "mini", feature = "embedded"))),
    derive(Serialize, Deserialize)
)]
pub struct BackendState<K> {
    next_id: AtomicU64,
    widgets: Mutex<HashMap<ObjectId, WidgetRecord<K>>>,
    menu_events: Mutex<VecDeque<ObjectId>>,
    widget_events: Mutex<VecDeque<WidgetTriggerEvent>>,
    clipboard_text: Mutex<String>,
    drop_events: Mutex<VecDeque<DropEvent>>,
}
impl<K> Default for BackendState<K>
where
    K: Copy + Eq + Hash,
{
    fn default() -> Self {
        Self::new()
    }
}

impl<K> BackendState<K>
where
    K: Copy + Eq + Hash,
{
    #[cfg(feature = "serde_json")]
    /// Serialize widget text snapshots without exposing synchronization primitives or id counters.
    pub fn serialize_widget_snapshot(&self) -> Result<String, serde_json::Error> {
        let texts: Vec<String> = self
            .widgets
            .lock()
            .expect("backend state widget lock poisoned")
            .values()
            .map(|record| record.text.clone())
            .collect();
        serde_json::to_string(&texts)
    }

    /// Create empty backend state.
    pub fn new() -> Self {
        Self {
            next_id: AtomicU64::new(1),
            widgets: Mutex::new(HashMap::new()),
            menu_events: Mutex::new(VecDeque::new()),
            widget_events: Mutex::new(VecDeque::new()),
            clipboard_text: Mutex::new(String::new()),
            drop_events: Mutex::new(VecDeque::new()),
        }
    }
    /// Insert one widget record and return allocated logical id.
    pub fn create_widget(
        &self,
        kind: K,
        text: &str,
        x: i32,
        y: i32,
        width: u32,
        height: u32,
    ) -> ObjectId {
        let id = self.next_id.fetch_add(1, Ordering::Relaxed);
        self.insert_widget(id, kind, text, x, y, width, height);
        id
    }

    /// Insert one widget record under a **caller-chosen** id.
    ///
    /// Used by self-drawn mounts: the id originates in
    /// [`crate::widget::runtime`], which owns the widget, so the backend state
    /// has to adopt it rather than allocate its own. Also advances the internal
    /// allocator past `id` so a later `create_widget` cannot collide with it.
    pub fn register_widget_with_id(
        &self,
        id: ObjectId,
        kind: K,
        text: &str,
        x: i32,
        y: i32,
        width: u32,
        height: u32,
    ) {
        self.insert_widget(id, kind, text, x, y, width, height);
        // Keep the allocator ahead of any externally supplied id.
        let mut next = self.next_id.load(Ordering::Relaxed);
        while next <= id {
            match self.next_id.compare_exchange(next, id + 1, Ordering::Relaxed, Ordering::Relaxed)
            {
                Ok(_) => break,
                Err(current) => next = current,
            }
        }
    }

    /// Shared insert used by both creation paths.
    fn insert_widget(
        &self,
        id: ObjectId,
        kind: K,
        text: &str,
        x: i32,
        y: i32,
        width: u32,
        height: u32,
    ) {
        self.widgets.lock().expect("backend state widget lock poisoned").insert(
            id,
            WidgetRecord {
                kind,
                text: text.to_string(),
                visible: true,
                enabled: true,
                ime_enabled: true,
                accessibility_name: text.to_string(),
                x,
                y,
                width,
                height,
            },
        );
    }
    /// Return `true` when widget exists.
    pub fn contains_widget(&self, widget_id: ObjectId) -> bool {
        self.widgets.lock().expect("backend state widget lock poisoned").contains_key(&widget_id)
    }

    /// Remove a widget record, returning `true` when it existed.
    ///
    /// This is the state-side half of widget teardown. Without it a backend's
    /// registry could only ever grow: a long-running app that rebuilds its UI
    /// (create/discard cycles) would leak one record — plus whatever native
    /// object the backend stored — per discarded widget, forever.
    pub fn destroy_widget(&self, widget_id: ObjectId) -> bool {
        self.widgets
            .lock()
            .expect("backend state widget lock poisoned")
            .remove(&widget_id)
            .is_some()
    }

    /// Number of live widget records. Used by tests and diagnostics to prove
    /// that teardown actually releases state.
    pub fn widget_count(&self) -> usize {
        self.widgets.lock().expect("backend state widget lock poisoned").len()
    }
    /// Return kind for an existing widget.
    pub fn kind_of(&self, widget_id: ObjectId) -> Option<K> {
        self.widgets
            .lock()
            .expect("backend state widget lock poisoned")
            .get(&widget_id)
            .map(|widget| widget.kind)
    }
    /// Return `true` when widget exists and kind matches.
    pub fn is_kind(&self, widget_id: ObjectId, kind: K) -> bool {
        self.kind_of(widget_id).map(|k| k == kind).unwrap_or(false)
    }
    /// Set visibility for a widget.
    pub fn set_visible(&self, widget_id: ObjectId, visible: bool) {
        if let Some(widget) =
            self.widgets.lock().expect("backend state widget lock poisoned").get_mut(&widget_id)
        {
            widget.visible = visible;
        }
    }
    /// Return visibility for a widget.
    pub fn visible(&self, widget_id: ObjectId) -> bool {
        self.widgets
            .lock()
            .expect("backend state widget lock poisoned")
            .get(&widget_id)
            .map(|widget| widget.visible)
            .unwrap_or(false)
    }
    /// Set enabled state for a widget.
    pub fn set_enabled(&self, widget_id: ObjectId, enabled: bool) {
        if let Some(widget) =
            self.widgets.lock().expect("backend state widget lock poisoned").get_mut(&widget_id)
        {
            widget.enabled = enabled;
        }
    }
    /// Return enabled state for a widget.
    pub fn enabled(&self, widget_id: ObjectId) -> bool {
        self.widgets
            .lock()
            .expect("backend state widget lock poisoned")
            .get(&widget_id)
            .map(|widget| widget.enabled)
            .unwrap_or(false)
    }
    /// Set geometry for a widget.
    pub fn set_geometry(&self, widget_id: ObjectId, x: i32, y: i32, width: u32, height: u32) {
        if let Some(widget) =
            self.widgets.lock().expect("backend state widget lock poisoned").get_mut(&widget_id)
        {
            widget.x = x;
            widget.y = y;
            widget.width = width;
            widget.height = height;
        }
    }
    /// Set text for a widget.
    pub fn set_text(&self, widget_id: ObjectId, text: &str) -> bool {
        if let Some(widget) =
            self.widgets.lock().expect("backend state widget lock poisoned").get_mut(&widget_id)
        {
            widget.text = text.to_string();
            return true;
        }
        false
    }
    /// Return text for a widget.
    pub fn text(&self, widget_id: ObjectId) -> String {
        self.widgets
            .lock()
            .expect("backend state widget lock poisoned")
            .get(&widget_id)
            .map(|widget| widget.text.clone())
            .unwrap_or_default()
    }
    /// Set IME enabled state for a widget.
    pub fn set_ime_enabled(&self, widget_id: ObjectId, enabled: bool) -> bool {
        if let Some(widget) =
            self.widgets.lock().expect("backend state widget lock poisoned").get_mut(&widget_id)
        {
            widget.ime_enabled = enabled;
            return true;
        }
        false
    }
    /// Return IME enabled state for a widget.
    pub fn ime_enabled(&self, widget_id: ObjectId) -> bool {
        self.widgets
            .lock()
            .expect("backend state widget lock poisoned")
            .get(&widget_id)
            .map(|widget| widget.ime_enabled)
            .unwrap_or(false)
    }
    /// Set accessibility label for a widget.
    pub fn set_accessibility_name(&self, widget_id: ObjectId, name: &str) -> bool {
        if let Some(widget) =
            self.widgets.lock().expect("backend state widget lock poisoned").get_mut(&widget_id)
        {
            widget.accessibility_name = name.to_string();
            return true;
        }
        false
    }
    /// Return accessibility label for a widget.
    pub fn accessibility_name(&self, widget_id: ObjectId) -> String {
        self.widgets
            .lock()
            .expect("backend state widget lock poisoned")
            .get(&widget_id)
            .map(|widget| widget.accessibility_name.clone())
            .unwrap_or_default()
    }

    // ─── Backend event methods ─────────────────────────────────────────────────
    // These methods provide event system integration for menu and widget trigger
    // dispatch. They are called by the macos, mobile, and stub platform backends.

    /// Push menu trigger event.
    /// Reserved for menu system integration (not yet wired to platform backends).
    pub fn push_menu_event(&self, item_id: ObjectId) {
        self.menu_events.lock().expect("backend state menu lock poisoned").push_back(item_id);
    }
    /// Pop menu trigger event.
    /// Reserved for menu system integration (paired with push_menu_event).
    pub fn pop_menu_event(&self) -> Option<ObjectId> {
        self.menu_events.lock().expect("backend state menu lock poisoned").pop_front()
    }
    /// Push typed widget trigger event.
    /// Reserved for event system integration (not yet wired to platform backends).
    pub fn push_widget_event(&self, event: WidgetTriggerEvent) {
        self.widget_events
            .lock()
            .expect("backend state widget-event lock poisoned")
            .push_back(event);
    }
    /// Pop typed widget trigger event.
    pub fn pop_widget_event(&self) -> Option<WidgetTriggerEvent> {
        self.widget_events.lock().expect("backend state widget-event lock poisoned").pop_front()
    }
    /// Set clipboard text.
    pub fn set_clipboard_text(&self, text: &str) -> bool {
        *self.clipboard_text.lock().expect("backend state clipboard lock poisoned") =
            text.to_string();
        true
    }
    /// Get clipboard text.
    pub fn clipboard_text(&self) -> String {
        self.clipboard_text.lock().expect("backend state clipboard lock poisoned").clone()
    }
    /// Begin drag event for existing source widget.
    pub fn begin_drag(&self, source_widget_id: ObjectId, mime: &str, payload: &[u8]) -> bool {
        if !self.contains_widget(source_widget_id) {
            return false;
        }
        self.drop_events.lock().expect("backend state drop lock poisoned").push_back(DropEvent {
            source_widget_id,
            target_widget_id: 0, // Not yet known — target is determined at drop time
            mime: mime.to_string(),
            payload: payload.to_vec(),
        });
        true
    }
    /// Pop one drop event.
    pub fn pop_drop_event(&self) -> Option<DropEvent> {
        self.drop_events.lock().expect("backend state drop lock poisoned").pop_front()
    }
    /// Inject drop event when target widget exists.
    pub fn inject_drop_event(&self, event: DropEvent) -> bool {
        if !self.contains_widget(event.target_widget_id) {
            return false;
        }
        self.drop_events.lock().expect("backend state drop lock poisoned").push_back(event);
        true
    }

    // ─── Test/programmatic event injection ─────────────────────────────────────
    // These helpers are called by the macos, mobile, and stub platform backends
    // for event system bridge functions.

    /// Inject menu trigger event.
    /// Reserved for testing and programmatic event injection.
    pub fn inject_menu_trigger(&self, menu_item_id: ObjectId) -> bool {
        if !self.contains_widget(menu_item_id) {
            return false;
        }
        self.push_menu_event(menu_item_id);
        true
    }
    /// Pop widget trigger event.
    /// Reserved for event processing in platform backends.
    pub fn pop_widget_trigger(&self) -> Option<ObjectId> {
        // Pop the widget_id from the widget_events queue (typed variant),
        // extracting just the widget_id. This is the widget-side counterpart
        // of push_widget_event / inject_widget_trigger_event.
        self.pop_widget_event().map(|e| e.widget_id)
    }
    /// Pop typed widget trigger event.
    /// Reserved for event processing in platform backends (typed variant).
    pub fn pop_widget_trigger_event(&self) -> Option<WidgetTriggerEvent> {
        self.pop_widget_event()
    }
    /// Inject widget trigger event.
    /// Reserved for testing and programmatic event injection (typed variant).
    pub fn inject_widget_trigger_event(
        &self,
        widget_id: ObjectId,
        kind: WidgetTriggerKind,
    ) -> bool {
        if !self.contains_widget(widget_id) {
            return false;
        }
        self.push_widget_event(WidgetTriggerEvent { widget_id, kind });
        true
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn is_kind_returns_true_for_matching_kind() {
        #[derive(Clone, Copy, PartialEq, Eq, Hash)]
        #[cfg_attr(
            all(feature = "serde", not(any(feature = "mini", feature = "embedded"))),
            derive(Serialize, Deserialize)
        )]
        enum TestKind {
            Button,
            Label,
        }

        let state = BackendState::<TestKind>::new();
        let id1 = state.create_widget(TestKind::Button, "Click", 0, 0, 100, 30);
        let id2 = state.create_widget(TestKind::Label, "Name:", 0, 0, 50, 20);

        assert!(state.is_kind(id1, TestKind::Button));
        assert!(!state.is_kind(id1, TestKind::Label));
        assert!(state.is_kind(id2, TestKind::Label));
        assert!(!state.is_kind(id2, TestKind::Button));
    }

    #[test]
    fn is_kind_returns_false_for_nonexistent_widget() {
        #[derive(Clone, Copy, PartialEq, Eq, Hash)]
        #[cfg_attr(
            all(feature = "serde", not(any(feature = "mini", feature = "embedded"))),
            derive(Serialize, Deserialize)
        )]
        enum TestKind {
            Widget,
        }

        let state = BackendState::<TestKind>::new();
        assert!(!state.is_kind(999, TestKind::Widget));
    }
}