rust_widgets 2.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
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
// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Li/Mikewolfli/Wei Li(mikewolfli@163.com)
// SPDX-License-Identifier: MIT

//! CameraPreview widget — self-drawn simulated camera viewfinder preview.
//!
//! This is a simulated preview component: it never opens or reads from a real
//! camera device. It draws a stylized viewfinder (resolution label, camera id,
//! zoom/mirror indicators, crosshair, control overlay) and manages a local
//! active state. There is no video feed behind the widget; all visuals are
//! generated by the widget itself.

use crate::core::{Color, Font, HorizontalAlignment, Point, Rect};
use crate::event::{Event, EventHandler};
use crate::impl_widget_property_hooks;
use crate::property_names_of;
use crate::render::RenderContext;
use crate::widget::capability::coercion::expect_bool;
use crate::widget::capability::properties_trait::{base_property_get, base_property_set};
use crate::widget::capability::types::{CapabilityAccessError, CapabilityValue};
use crate::widget::capability::WidgetProperties;
use crate::widget::{BaseWidget, Draw, Widget, WidgetKind};

/// Camera preview widget — draws a simulated camera viewfinder area with controls.
///
/// Renders a self-drawn camera viewfinder and optional control overlay buttons.
/// Zoom, mirror/flip and preview start/stop only change local widget state and
/// redrawing; no real camera device is opened and no frames are captured.
pub struct CameraPreview {
    base: BaseWidget,
    /// Whether the camera preview is currently active.
    is_active: bool,
    /// Camera resolution as (width, height).
    resolution: (u32, u32),
    /// Camera device identifier.
    camera_id: u32,
    /// Whether the preview is mirrored (horizontally flipped).
    mirror_mode: bool,
    /// Whether control buttons are shown overlaid on the preview.
    show_controls: bool,
    /// Current zoom level (1.0 = normal).
    zoom_level: f32,
}

impl CameraPreview {
    /// Creates a new CameraPreview widget with the given geometry.
    pub fn new(geometry: Rect) -> Self {
        Self {
            base: BaseWidget::new(WidgetKind::CameraPreview, geometry, "CameraPreview"),
            is_active: false,
            resolution: (640, 480),
            camera_id: 0,
            mirror_mode: false,
            show_controls: true,
            zoom_level: 1.0,
        }
    }

    /// Starts the simulated camera preview.
    ///
    /// Only flips the local active flag and requests a redraw. No camera device
    /// is opened and no frames are captured; the "preview" shown is drawn by
    /// this widget itself.
    pub fn start_preview(&mut self) {
        self.is_active = true;
        self.base.request_redraw();
    }

    /// Stops the simulated camera preview (local state and redraw only).
    pub fn stop_preview(&mut self) {
        self.is_active = false;
        self.base.request_redraw();
    }

    /// Returns whether the camera preview is active.
    pub fn is_active(&self) -> bool {
        self.is_active
    }

    /// Toggles the simulated preview on/off (local state only).
    pub fn toggle_preview(&mut self) {
        if self.is_active {
            self.stop_preview();
        } else {
            self.start_preview();
        }
    }

    /// Sets the camera device identifier shown in the preview overlay.
    ///
    /// Display-only: no device with this id is opened or streamed from.
    pub fn set_camera_id(&mut self, id: u32) {
        self.camera_id = id;
    }

    /// Returns the current camera device ID.
    pub fn camera_id(&self) -> u32 {
        self.camera_id
    }

    /// Sets the resolution label used by the simulated preview.
    ///
    /// Used for the on-screen "WxH" text; no capture pipeline exists.
    pub fn set_resolution(&mut self, w: u32, h: u32) {
        self.resolution = (w.max(1), h.max(1));
        self.base.request_redraw();
    }

    /// Returns the current camera resolution.
    pub fn resolution(&self) -> (u32, u32) {
        self.resolution
    }

    /// Enables or disables mirror mode (horizontal flip).
    pub fn set_mirror_mode(&mut self, mirrored: bool) {
        self.mirror_mode = mirrored;
        self.base.request_redraw();
    }

    /// Returns whether mirror mode is enabled.
    pub fn is_mirror_mode(&self) -> bool {
        self.mirror_mode
    }

    /// Sets the zoom level (1.0 = normal, 2.0 = 2x, etc.).
    pub fn set_zoom(&mut self, level: f32) {
        self.zoom_level = level.clamp(1.0, 10.0);
        self.base.request_redraw();
    }

    /// Returns the current zoom level.
    pub fn zoom_level(&self) -> f32 {
        self.zoom_level
    }

    /// Zooms in by one step.
    pub fn zoom_in(&mut self) {
        self.set_zoom(self.zoom_level + 0.5);
    }

    /// Zooms out by one step.
    pub fn zoom_out(&mut self) {
        self.set_zoom(self.zoom_level - 0.5);
    }

    /// Makes the control overlay visible.
    pub fn show_controls(&mut self) {
        self.show_controls = true;
        self.base.request_redraw();
    }

    /// Hides the control overlay.
    pub fn hide_controls(&mut self) {
        self.show_controls = false;
        self.base.request_redraw();
    }

    /// Returns whether controls are currently visible.
    pub fn controls_visible(&self) -> bool {
        self.show_controls
    }
}

impl Widget for CameraPreview {
    fn base(&self) -> &BaseWidget {
        &self.base
    }
    fn base_mut(&mut self) -> &mut BaseWidget {
        &mut self.base
    }

    fn size_hint(&self) -> crate::core::Size {
        crate::core::Size::new(320, 240)
    }

    /// Reports this widget as the object that paints it.
    ///
    /// `CameraPreview` implements `Draw`, so `Some(self)` is total and cannot be
    /// wrong.
    fn as_draw_mut(&mut self) -> Option<&mut dyn crate::widget::Draw> {
        Some(self)
    }

    impl_widget_property_hooks!();
}

/// `CameraPreview`'s property contract.
///
/// Read/write semantics are carried over unchanged from the centralised
/// `access_read_media.in.rs` / `access_write_media.in.rs` dispatch: `is_active`
/// maps onto `start_preview` / `stop_preview`.
impl WidgetProperties for CameraPreview {
    fn get(&self, name: &str) -> Result<CapabilityValue, CapabilityAccessError> {
        match name {
            "is_active" => Ok(CapabilityValue::Bool(self.is_active())),
            _ => base_property_get(self, name),
        }
    }

    fn set(&mut self, name: &str, value: CapabilityValue) -> Result<(), CapabilityAccessError> {
        match name {
            "is_active" => {
                if expect_bool(value)? {
                    self.start_preview();
                } else {
                    self.stop_preview();
                }
                Ok(())
            }
            _ => base_property_set(self, name, value),
        }
    }

    fn property_names(&self) -> &'static [&'static str] {
        property_names_of!["is_active", BASE_PROPERTY_NAMES]
    }
}

impl Draw for CameraPreview {
    fn draw(&mut self, context: &mut RenderContext) {
        let rect = self.geometry();
        let w = rect.width as i32;
        let h = rect.height as i32;

        if w <= 0 || h <= 0 {
            return;
        }

        // Create default fonts for text rendering
        let small_font = Font::new("sans-serif", 11.0, false, false);
        let normal_font = Font::new("sans-serif", 13.0, false, false);

        if self.is_active {
            // Draw active camera view — dark viewfinder area
            let viewfinder_color = Color::rgba(30, 30, 40, 255);
            context.fill_rect(rect, viewfinder_color);

            // Draw resolution info text
            let res_text = format!("{}x{}", self.resolution.0, self.resolution.1);
            context.draw_text(
                Point::new(rect.x + 6, rect.y + 14),
                &res_text,
                &small_font,
                Color::rgba(200, 200, 200, 200),
                HorizontalAlignment::Left,
            );

            // Draw camera ID
            let id_text = format!("Camera #{}", self.camera_id);
            context.draw_text(
                Point::new(rect.x + 6, rect.y + h - 10),
                &id_text,
                &small_font,
                Color::rgba(200, 200, 200, 200),
                HorizontalAlignment::Left,
            );

            // Draw zoom level indicator
            let zoom_text = format!("{:.1}x", self.zoom_level);
            context.draw_text(
                Point::new(rect.x + w - 40, rect.y + 14),
                &zoom_text,
                &normal_font,
                Color::rgba(255, 255, 255, 220),
                HorizontalAlignment::Left,
            );

            // Draw mirror indicator
            if self.mirror_mode {
                context.draw_text(
                    Point::new(rect.x + w / 2 - 20, rect.y + h - 10),
                    "MIRROR",
                    &small_font,
                    Color::rgba(100, 200, 255, 200),
                    HorizontalAlignment::Left,
                );
            }

            // Draw a subtle crosshair
            let cx = rect.x + w / 2;
            let cy = rect.y + h / 2;
            let crosshair_color = Color::rgba(100, 100, 100, 100);
            context.draw_line(Point::new(cx, cy - 15), Point::new(cx, cy + 15), crosshair_color);
            context.draw_line(Point::new(cx - 15, cy), Point::new(cx + 15, cy), crosshair_color);

            // Draw border indicating active preview
            let border_color = Color::rgba(0, 200, 50, 200);
            context.draw_rect_stroke(rect, border_color, 2);

            // Draw control overlay if visible
            if self.show_controls {
                // Top-right corner controls background
                let control_bg = Rect::new(rect.x + w - 44, rect.y + 4, 40, 80);
                context.fill_rect(control_bg, Color::rgba(0, 0, 0, 120));

                // Draw zoom +/- buttons as simple colored rects
                let zoom_in_btn = Rect::new(rect.x + w - 42, rect.y + 6, 36, 36);
                context.fill_rect(zoom_in_btn, Color::rgba(255, 255, 255, 80));

                let zoom_out_btn = Rect::new(rect.x + w - 42, rect.y + 46, 36, 36);
                context.fill_rect(zoom_out_btn, Color::rgba(255, 255, 255, 80));
            }

            // Draw a green "recording" dot indicator
            let dot_size = 8;
            let dot_rect = Rect::new(rect.x + 6, rect.y + 6, dot_size, dot_size);
            context.fill_rect(dot_rect, Color::rgba(0, 255, 0, 255));
        } else {
            // Draw inactive camera view — dark gray with camera icon placeholder
            context.fill_rect(rect, Color::rgba(50, 50, 60, 255));

            // Draw a simple camera icon placeholder (rounded rectangle shape)
            let icon_w = 48u32;
            let icon_h = 36u32;
            let icon_x = rect.x + (w - icon_w as i32) / 2;
            let icon_y = rect.y + (h - icon_h as i32) / 2 - 10;
            let icon_rect = Rect::new(icon_x, icon_y, icon_w, icon_h);
            context.fill_rounded_rect(icon_rect, 6, Color::rgba(100, 100, 120, 200));

            // Lens circle
            let lens_center_x = icon_x + icon_w as i32 / 2;
            let lens_center_y = icon_y + icon_h as i32 / 2;
            let lens_rect = Rect::new(lens_center_x - 8, lens_center_y - 8, 16, 16);
            context.fill_rounded_rect(lens_rect, 8, Color::rgba(70, 70, 90, 255));

            // Flash dot
            let flash_rect = Rect::new(icon_x + icon_w as i32 - 10, icon_y + 4, 6, 6);
            context.fill_rounded_rect(flash_rect, 3, Color::rgba(200, 200, 200, 150));

            // "Camera Off" label
            context.draw_text(
                Point::new(rect.x + w / 2 - 30, rect.y + h / 2 + 20),
                "Camera Off",
                &normal_font,
                Color::rgba(150, 150, 160, 200),
                HorizontalAlignment::Left,
            );

            // Border
            context.draw_rect_stroke(rect, Color::rgba(100, 100, 110, 200), 1);
        }
    }
}

impl EventHandler for CameraPreview {
    fn handle_event(&mut self, event: &Event) {
        if !self.base.is_enabled() {
            return;
        }
        match event {
            Event::MousePress { pos: _, button } => {
                if *button == 1 {
                    // Left-click toggles preview
                    self.toggle_preview();
                }
            }
            _ => {
                self.base.handle_event(event);
            }
        }
    }
}

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

    #[test]
    fn camera_preview_default_state() {
        let cp = CameraPreview::new(Rect::new(0, 0, 320, 240));
        assert!(!cp.is_active());
        assert_eq!(cp.camera_id(), 0);
        assert_eq!(cp.resolution(), (640, 480));
        assert!(!cp.is_mirror_mode());
        assert!(cp.controls_visible());
        assert!((cp.zoom_level() - 1.0).abs() < f32::EPSILON);
        assert_eq!(cp.kind(), WidgetKind::CameraPreview);
    }

    #[test]
    fn camera_preview_toggle() {
        let mut cp = CameraPreview::new(Rect::new(0, 0, 320, 240));
        assert!(!cp.is_active());
        cp.start_preview();
        assert!(cp.is_active());
        cp.stop_preview();
        assert!(!cp.is_active());
        cp.toggle_preview();
        assert!(cp.is_active());
        cp.toggle_preview();
        assert!(!cp.is_active());
    }

    #[test]
    fn camera_preview_zoom() {
        let mut cp = CameraPreview::new(Rect::new(0, 0, 320, 240));
        assert!((cp.zoom_level() - 1.0).abs() < f32::EPSILON);
        cp.zoom_in();
        assert!((cp.zoom_level() - 1.5).abs() < f32::EPSILON);
        cp.zoom_in();
        assert!((cp.zoom_level() - 2.0).abs() < f32::EPSILON);
        cp.zoom_out();
        assert!((cp.zoom_level() - 1.5).abs() < f32::EPSILON);
        cp.set_zoom(5.0);
        assert!((cp.zoom_level() - 5.0).abs() < f32::EPSILON);
    }

    #[test]
    fn camera_preview_camera_id_and_resolution() {
        let mut cp = CameraPreview::new(Rect::new(0, 0, 320, 240));
        cp.set_camera_id(2);
        assert_eq!(cp.camera_id(), 2);
        cp.set_resolution(1920, 1080);
        assert_eq!(cp.resolution(), (1920, 1080));
    }

    #[test]
    fn camera_preview_mirror_and_controls() {
        let mut cp = CameraPreview::new(Rect::new(0, 0, 320, 240));
        assert!(!cp.is_mirror_mode());
        cp.set_mirror_mode(true);
        assert!(cp.is_mirror_mode());
        assert!(cp.controls_visible());
        cp.hide_controls();
        assert!(!cp.controls_visible());
        cp.show_controls();
        assert!(cp.controls_visible());
    }

    #[test]
    fn camera_preview_click_toggles() {
        let mut cp = CameraPreview::new(Rect::new(0, 0, 320, 240));
        assert!(!cp.is_active());
        cp.handle_event(&Event::MousePress { pos: Point::new(10, 10), button: 1 });
        assert!(cp.is_active());
        cp.handle_event(&Event::MousePress { pos: Point::new(10, 10), button: 1 });
        assert!(!cp.is_active());
    }
}