rust_widgets 1.0.0

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
//! Embedded runtime state, task queue, and shared engine internals.

#[cfg(not(feature = "mini"))]
use crate::compat::Condvar;
use crate::compat::HashMap;
#[cfg(not(feature = "mini"))]
use crate::compat::Instant;
use crate::compat::Mutex;
use crate::compat::MutexGuard;
use crate::compat::OnceLock;
use alloc::collections::VecDeque;
use alloc::sync::Arc;
use core::sync::atomic::{AtomicU64, Ordering};
#[cfg(not(feature = "mini"))]
use core::time::Duration;

const DEFAULT_EMBEDDED_TARGET_FPS: u32 = 60;
const MIN_EMBEDDED_TARGET_FPS: u32 = 1;
const MAX_EMBEDDED_TARGET_FPS: u32 = 240;

fn clamp_embedded_target_fps(fps: u32) -> u32 {
    fps.clamp(MIN_EMBEDDED_TARGET_FPS, MAX_EMBEDDED_TARGET_FPS)
}

#[cfg(not(feature = "mini"))]
fn frame_interval_for_fps(fps: u32) -> Duration {
    Duration::from_nanos(1_000_000_000 / fps as u64)
}

type EmbeddedTaskFn = Box<dyn FnOnce(u64) + Send + 'static>;

struct EmbeddedTask {
    id: u64,
    label: String,
    action: Option<EmbeddedTaskFn>,
}

impl EmbeddedTask {
    fn new(id: u64, label: String, action: EmbeddedTaskFn) -> Self {
        Self { id, label, action: Some(action) }
    }

    fn run(mut self, frame_index: u64) {
        let _ = self.id;
        let _ = self.label;
        if let Some(action) = self.action.take() {
            action(frame_index);
        }
    }
}

#[derive(Default)]
struct EmbeddedRuntimeState {
    initialized: bool,
    running: bool,
    target_fps: u32,
    windows: HashMap<u64, EmbeddedWindowRecord>,
    buttons: HashMap<u64, EmbeddedButtonRecord>,
    pending_tasks: VecDeque<EmbeddedTask>,
}

impl EmbeddedRuntimeState {
    fn new() -> Self {
        Self {
            initialized: false,
            running: false,
            target_fps: DEFAULT_EMBEDDED_TARGET_FPS,
            windows: HashMap::new(),
            buttons: HashMap::new(),
            pending_tasks: VecDeque::new(),
        }
    }
}

pub(crate) struct EmbeddedEngineShared {
    next_widget_id: AtomicU64,
    next_task_id: AtomicU64,
    frame_count: AtomicU64,
    state: Mutex<EmbeddedRuntimeState>,
    #[cfg(not(feature = "mini"))]
    wake_signal: Condvar,
}

impl EmbeddedEngineShared {
    fn new() -> Self {
        Self {
            next_widget_id: AtomicU64::new(1),
            next_task_id: AtomicU64::new(1),
            frame_count: AtomicU64::new(0),
            state: Mutex::new(EmbeddedRuntimeState::new()),
            #[cfg(not(feature = "mini"))]
            wake_signal: Condvar::new(),
        }
    }

    fn lock_state(&self) -> MutexGuard<'_, EmbeddedRuntimeState> {
        self.state.lock().unwrap_or_else(|poisoned| poisoned.into_inner())
    }

    fn set_target_fps(&self, fps: u32) -> u32 {
        let mut state = self.lock_state();
        state.target_fps = clamp_embedded_target_fps(fps);
        #[cfg(not(feature = "mini"))]
        self.wake_signal.notify_all();
        state.target_fps
    }

    fn target_fps(&self) -> u32 {
        self.lock_state().target_fps
    }

    pub(crate) fn init(&self) {
        let mut state = self.lock_state();
        if state.initialized {
            return;
        }
        state.initialized = true;
    }

    #[cfg(not(feature = "mini"))]
    pub(crate) fn run_loop(&self) {
        {
            let mut state = self.lock_state();
            if state.running {
                return;
            }
            state.running = true;
        }
        loop {
            let frame_start = Instant::now();
            let (tasks, target_fps, still_running) = {
                let mut state = self.lock_state();
                let still_running = state.running;
                let target_fps = state.target_fps;
                let tasks = state.pending_tasks.drain(..).collect::<Vec<_>>();
                (tasks, target_fps, still_running)
            };
            if !still_running {
                break;
            }
            let frame_index = self.frame_count.fetch_add(1, Ordering::SeqCst) + 1;
            for task in tasks {
                task.run(frame_index);
            }
            let frame_interval = frame_interval_for_fps(clamp_embedded_target_fps(target_fps));
            let elapsed = frame_start.elapsed();
            if elapsed < frame_interval {
                let wait_duration = frame_interval - elapsed;
                let state = self.lock_state();
                if !state.running {
                    break;
                }
                let _ = self
                    .wake_signal
                    .wait_timeout(state, wait_duration)
                    .unwrap_or_else(|poisoned| poisoned.into_inner());
            }
        }
    }

    #[cfg(feature = "mini")]
    pub(crate) fn run_loop(&self) {
        // mini: no-thread embedded loop — process tasks inline, no sleep/wait
        {
            let mut state = self.lock_state();
            if state.running {
                return;
            }
            state.running = true;
        }
        loop {
            let (tasks, still_running) = {
                let mut state = self.lock_state();
                let still_running = state.running;
                let tasks = state.pending_tasks.drain(..).collect::<Vec<_>>();
                (tasks, still_running)
            };
            if !still_running {
                break;
            }
            let frame_index = self.frame_count.fetch_add(1, Ordering::SeqCst) + 1;
            for task in tasks {
                task.run(frame_index);
            }
        }
    }

    pub(crate) fn _destroy_window(&self, window_id: u64) {
        let mut state = self.lock_state();
        state.windows.remove(&window_id);
    }

    pub(crate) fn _destroy_button(&self, button_id: u64) {
        let mut state = self.lock_state();
        state.buttons.remove(&button_id);
    }

    pub(crate) fn quit(&self) {
        let mut state = self.lock_state();
        state.running = false;
        state.windows.clear();
        state.buttons.clear();
        state.pending_tasks.clear();
        drop(state);
        #[cfg(not(feature = "mini"))]
        self.wake_signal.notify_all();
    }

    fn alloc_widget_id(&self) -> u64 {
        self.next_widget_id.fetch_add(1, Ordering::SeqCst)
    }

    pub(crate) fn register_window(
        &self,
        title: &str,
        x: i32,
        y: i32,
        width: u32,
        height: u32,
    ) -> u64 {
        let window_id = self.alloc_widget_id();
        let mut state = self.lock_state();
        state.windows.insert(
            window_id,
            EmbeddedWindowRecord { id: window_id, title: title.to_string(), x, y, width, height },
        );
        window_id
    }

    pub(crate) fn register_button(
        &self,
        parent: u64,
        text: &str,
        x: i32,
        y: i32,
        width: u32,
        height: u32,
    ) -> u64 {
        let button_id = self.alloc_widget_id();
        let mut state = self.lock_state();
        state.buttons.insert(
            button_id,
            EmbeddedButtonRecord {
                id: button_id,
                parent,
                text: text.to_string(),
                x,
                y,
                width,
                height,
            },
        );
        button_id
    }

    fn submit_task<F>(&self, label: String, action: F) -> u64
    where
        F: FnOnce(u64) + Send + 'static,
    {
        let task_id = self.next_task_id.fetch_add(1, Ordering::SeqCst);
        let mut state = self.lock_state();
        state.pending_tasks.push_back(EmbeddedTask::new(task_id, label, Box::new(action)));
        drop(state);
        #[cfg(not(feature = "mini"))]
        self.wake_signal.notify_all();
        task_id
    }

    fn stats(&self) -> EmbeddedEngineStats {
        let state = self.lock_state();
        EmbeddedEngineStats {
            initialized: state.initialized,
            running: state.running,
            frame_count: self.frame_count.load(Ordering::SeqCst),
            pending_task_count: state.pending_tasks.len(),
            window_count: state.windows.len(),
            button_count: state.buttons.len(),
            target_fps: state.target_fps,
        }
    }
}

/// Snapshot record of an embedded window handle and geometry.
#[derive(Clone, Debug)]
pub struct EmbeddedWindowRecord {
    /// Logical window id allocated by the platform backend.
    pub id: u64,
    /// Window title at creation time.
    pub title: String,
    /// Window origin X in logical pixels.
    pub x: i32,
    /// Window origin Y in logical pixels.
    pub y: i32,
    /// Window width in logical pixels.
    pub width: u32,
    /// Window height in logical pixels.
    pub height: u32,
}

/// Snapshot record of an embedded button handle and geometry.
#[derive(Clone, Debug)]
pub struct EmbeddedButtonRecord {
    /// Logical button id allocated by the platform backend.
    pub id: u64,
    /// Parent logical widget id.
    pub parent: u64,
    /// Button text at creation time.
    pub text: String,
    /// Button origin X in logical pixels.
    pub x: i32,
    /// Button origin Y in logical pixels.
    pub y: i32,
    /// Button width in logical pixels.
    pub width: u32,
    /// Button height in logical pixels.
    pub height: u32,
}

/// Runtime statistics for the embedded render-engine loop.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct EmbeddedEngineStats {
    /// Whether the embedded engine has completed initialization.
    pub initialized: bool,
    /// Whether the embedded run loop is currently active.
    pub running: bool,
    /// Number of frames processed by the embedded run loop.
    pub frame_count: u64,
    /// Number of queued tasks waiting for the next frame.
    pub pending_task_count: usize,
    /// Number of registered windows tracked by the runtime.
    pub window_count: usize,
    /// Number of registered buttons tracked by the runtime.
    pub button_count: usize,
    /// Current target FPS used by the embedded scheduler.
    pub target_fps: u32,
}

#[cfg(not(feature = "mini"))]
pub(crate) fn embedded_engine_shared() -> Arc<EmbeddedEngineShared> {
    static SHARED: OnceLock<Arc<EmbeddedEngineShared>> = OnceLock::new();
    SHARED.get_or_init(|| Arc::new(EmbeddedEngineShared::new())).clone()
}

#[cfg(feature = "mini")]
pub(crate) fn embedded_engine_shared() -> Arc<EmbeddedEngineShared> {
    static SHARED: OnceLock<Arc<EmbeddedEngineShared>> = OnceLock::new();
    SHARED.get_or_init(|| Arc::new(EmbeddedEngineShared::new())).clone()
}

/// Set embedded engine target FPS. Returns the applied clamped FPS value.
pub fn set_embedded_target_fps(fps: u32) -> u32 {
    embedded_engine_shared().set_target_fps(fps)
}

/// Read embedded engine target FPS.
pub fn embedded_target_fps() -> u32 {
    embedded_engine_shared().target_fps()
}

/// Submit a task to execute on the next embedded frame.
pub fn submit_embedded_task<F>(label: impl Into<String>, action: F) -> u64
where
    F: FnOnce(u64) + Send + 'static,
{
    embedded_engine_shared().submit_task(label.into(), action)
}

/// Return embedded engine runtime stats for diagnostics and test assertions.
pub fn embedded_engine_stats() -> EmbeddedEngineStats {
    embedded_engine_shared().stats()
}

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

    fn test_guard() -> crate::compat::MutexGuard<'static, ()> {
        static GUARD: OnceLock<Mutex<()>> = OnceLock::new();
        GUARD.get_or_init(|| Mutex::new(())).lock().unwrap_or_else(|poisoned| poisoned.into_inner())
    }

    #[test]
    fn embedded_target_fps_clamps() {
        let _guard = test_guard();
        // Reset to default first — other tests may leave the global state
        // at a non-default value since the embedded engine is a process-wide singleton.
        set_embedded_target_fps(DEFAULT_EMBEDDED_TARGET_FPS);
        assert_eq!(set_embedded_target_fps(0), MIN_EMBEDDED_TARGET_FPS);
        assert_eq!(set_embedded_target_fps(999), MAX_EMBEDDED_TARGET_FPS);
        assert_eq!(set_embedded_target_fps(72), 72);
        assert_eq!(embedded_target_fps(), 72);
        // Clean up for subsequent tests
        set_embedded_target_fps(DEFAULT_EMBEDDED_TARGET_FPS);
    }

    #[test]
    fn embedded_resource_registry_tracks_window_and_button() {
        let _guard = test_guard();
        let before = embedded_engine_stats();
        let shared = embedded_engine_shared();
        let window_id = shared.register_window("stats", 1, 2, 300, 200);
        let _button_id = shared.register_button(window_id, "ok", 10, 10, 80, 24);
        let after = embedded_engine_stats();
        assert!(after.window_count > before.window_count);
        assert!(after.button_count > before.button_count);
    }
}