uzor-mobile 1.0.12

Mobile backend for uzor (iOS/Android)
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
//! Mobile backend for uzor supporting iOS and Android
//!
//! This crate provides the mobile platform implementation for uzor,
//! supporting iOS and Android devices with touch-first design.
//!
//! # Architecture
//!
//! The mobile backend provides:
//! - Touch input handling (multi-touch)
//! - Virtual keyboard integration (IME)
//! - Mobile-specific features (haptics, orientation, safe areas)
//! - Native clipboard integration
//! - System theme detection
//!
//! # Platform-Specific Notes
//!
//! ## iOS
//! - Uses UIKit for native UI integration
//! - Clipboard via UIPasteboard
//! - Theme detection via UITraitCollection
//! - Safe area insets for notch/home indicator
//!
//! ## Android
//! - Uses Android NDK and JNI
//! - Clipboard via ClipboardManager
//! - Theme detection via Configuration.UI_MODE_NIGHT
//! - System bars handling
//!
//! # Feature Flags
//!
//! - `android`: Enable Android-specific functionality
//! - `ios`: Enable iOS-specific functionality
//!
//! # Example
//!
//! ```ignore
//! use uzor_mobile::MobilePlatform;
//! use uzor::platform::{PlatformBackend, WindowConfig};
//!
//! fn main() {
//!     let mut platform = MobilePlatform::new().unwrap();
//!
//!     let window = platform.create_window(
//!         WindowConfig::new("My Mobile App")
//!     ).unwrap();
//!
//!     // Handle touch events
//!     while let Some(event) = platform.poll_event() {
//!         match event {
//!             PlatformEvent::TouchStart { id, x, y } => {
//!                 // Handle touch start
//!             }
//!             PlatformEvent::TouchMove { id, x, y } => {
//!                 // Handle touch move
//!             }
//!             PlatformEvent::TouchEnd { id, x, y } => {
//!                 // Handle touch end
//!             }
//!             _ => {}
//!         }
//!     }
//! }
//! ```

#![allow(dead_code)]

pub use uzor;

use std::collections::VecDeque;
use std::sync::{Arc, Mutex};

use uzor::platform::{
    backends::PlatformBackend,
    types::{PlatformError, WindowId, SystemIntegration},
    PlatformEvent, SystemTheme, WindowConfig,
};

// Platform-specific modules
#[cfg(target_os = "android")]
mod android;
#[cfg(target_os = "android")]
use android::AndroidBackend;

#[cfg(target_os = "ios")]
mod ios;
#[cfg(target_os = "ios")]
use ios::IosBackend;

mod common;

// =============================================================================
// Mobile Platform
// =============================================================================

/// Mobile platform backend for uzor
///
/// Provides a unified interface for iOS and Android platforms.
/// Uses platform-specific implementations internally based on target OS.
pub struct MobilePlatform {
    state: Arc<Mutex<MobileState>>,
}

struct MobileState {
    /// Active window (mobile apps typically have only one)
    window: Option<MobileWindow>,

    /// Platform-specific backend
    #[cfg(target_os = "android")]
    backend: AndroidBackend,
    #[cfg(target_os = "ios")]
    backend: IosBackend,
    #[cfg(not(any(target_os = "android", target_os = "ios")))]
    backend: StubBackend,

    /// Event queue
    event_queue: VecDeque<PlatformEvent>,

    /// IME state
    ime_position: (f64, f64),
    ime_allowed: bool,
}

struct MobileWindow {
    id: WindowId,
    config: WindowConfig,
    width: u32,
    height: u32,
    scale_factor: f64,
}

impl MobilePlatform {
    /// Create a new mobile platform instance
    ///
    /// # Errors
    ///
    /// Returns an error if the platform-specific backend fails to initialize.
    pub fn new() -> Result<Self, PlatformError> {
        #[cfg(target_os = "android")]
        let backend = AndroidBackend::new()
            .map_err(|e| PlatformError::CreationFailed(format!("Android backend init failed: {}", e)))?;

        #[cfg(target_os = "ios")]
        let backend = IosBackend::new()
            .map_err(|e| PlatformError::CreationFailed(format!("iOS backend init failed: {}", e)))?;

        #[cfg(not(any(target_os = "android", target_os = "ios")))]
        let backend = StubBackend::new();

        Ok(Self {
            state: Arc::new(Mutex::new(MobileState {
                window: None,
                backend,
                event_queue: VecDeque::new(),
                ime_position: (0.0, 0.0),
                ime_allowed: false,
            })),
        })
    }

    /// Get safe area insets (for notch, home indicator, etc.)
    ///
    /// Returns (top, right, bottom, left) insets in physical pixels.
    pub fn safe_area_insets(&self) -> (f64, f64, f64, f64) {
        let state = self.state.lock().unwrap();
        state.backend.safe_area_insets()
    }

    /// Get current screen orientation
    pub fn orientation(&self) -> ScreenOrientation {
        let state = self.state.lock().unwrap();
        state.backend.orientation()
    }

    /// Trigger haptic feedback
    ///
    /// # Arguments
    ///
    /// * `style` - The haptic feedback style to trigger
    pub fn haptic_feedback(&mut self, style: HapticStyle) {
        let mut state = self.state.lock().unwrap();
        state.backend.haptic_feedback(style);
    }
}

impl Default for MobilePlatform {
    fn default() -> Self {
        Self::new().expect("Failed to create mobile platform")
    }
}

// =============================================================================
// PlatformBackend Implementation
// =============================================================================

impl PlatformBackend for MobilePlatform {
    fn name(&self) -> &'static str {
        todo!("not yet implemented for this platform")
    }

    fn create_window(&mut self, config: WindowConfig) -> Result<WindowId, PlatformError> {
        let mut state = self.state.lock().unwrap();

        // Mobile apps typically have only one window
        if state.window.is_some() {
            return Err(PlatformError::CreationFailed(
                "Mobile platform supports only one window".to_string(),
            ));
        }

        let window_id = WindowId::new();

        // Get screen size from backend
        let (width, height) = state.backend.screen_size();
        let scale_factor = state.backend.scale_factor();

        let window = MobileWindow {
            id: window_id,
            config,
            width,
            height,
            scale_factor,
        };

        state.window = Some(window);
        state.event_queue.push_back(PlatformEvent::WindowCreated);

        Ok(window_id)
    }

    fn close_window(&mut self, window_id: WindowId) -> Result<(), PlatformError> {
        let mut state = self.state.lock().unwrap();

        if let Some(window) = &state.window {
            if window.id == window_id {
                state.window = None;
                state.event_queue.push_back(PlatformEvent::WindowDestroyed);
                return Ok(());
            }
        }

        Err(PlatformError::WindowNotFound)
    }

    fn primary_window(&self) -> Option<WindowId> {
        todo!("not yet implemented for this platform")
    }

    fn poll_events(&mut self) -> Vec<PlatformEvent> {
        todo!("not yet implemented for this platform")
    }

    fn request_redraw(&self, id: WindowId) {
        let _ = id;
        // No-op for now: mobile redraws are driven by the OS event loop
    }
}

// =============================================================================
// SystemIntegration Implementation
// =============================================================================

impl SystemIntegration for MobilePlatform {
    fn get_clipboard(&self) -> Option<String> {
        todo!("not yet implemented for this platform")
    }

    fn set_clipboard(&self, _text: &str) {
        todo!("not yet implemented for this platform")
    }

    fn get_system_theme(&self) -> Option<SystemTheme> {
        let state = self.state.lock().unwrap();
        state.backend.system_theme()
    }
}

// =============================================================================
// Mobile-Specific Types
// =============================================================================

/// Screen orientation
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ScreenOrientation {
    /// Portrait (vertical)
    Portrait,
    /// Landscape (horizontal)
    Landscape,
    /// Portrait upside down
    PortraitUpsideDown,
    /// Landscape right
    LandscapeRight,
}

/// Haptic feedback style
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum HapticStyle {
    /// Light impact (subtle)
    Light,
    /// Medium impact
    Medium,
    /// Heavy impact
    Heavy,
    /// Selection feedback (tick)
    Selection,
    /// Success feedback
    Success,
    /// Warning feedback
    Warning,
    /// Error feedback
    Error,
}

// =============================================================================
// Stub Backend (for non-mobile platforms during development)
// =============================================================================

#[cfg(not(any(target_os = "android", target_os = "ios")))]
struct StubBackend;

#[cfg(not(any(target_os = "android", target_os = "ios")))]
impl StubBackend {
    fn new() -> Self {
        StubBackend
    }

    fn screen_size(&self) -> (u32, u32) {
        (800, 600)
    }

    fn scale_factor(&self) -> f64 {
        1.0
    }

    fn safe_area_insets(&self) -> (f64, f64, f64, f64) {
        (0.0, 0.0, 0.0, 0.0)
    }

    fn orientation(&self) -> ScreenOrientation {
        ScreenOrientation::Portrait
    }

    fn haptic_feedback(&mut self, _style: HapticStyle) {}

    fn poll_event(&mut self) -> Option<PlatformEvent> {
        None
    }

    fn set_title(&mut self, _title: &str) {}

    fn get_clipboard_text(&self) -> Option<String> {
        None
    }

    fn set_clipboard_text(&mut self, _text: &str) -> Result<(), String> {
        Err("Clipboard not available on stub backend".to_string())
    }

    fn open_url(&self, _url: &str) -> Result<(), String> {
        Err("URL opening not available on stub backend".to_string())
    }

    fn system_theme(&self) -> Option<SystemTheme> {
        Some(SystemTheme::Light)
    }

    fn set_ime_position(&mut self, _x: f64, _y: f64) {}

    fn show_keyboard(&mut self) {}

    fn hide_keyboard(&mut self) {}
}

// =============================================================================
// Tests
// =============================================================================

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

    #[test]
    fn test_haptic_style_variants() {
        let styles = vec![
            HapticStyle::Light,
            HapticStyle::Medium,
            HapticStyle::Heavy,
            HapticStyle::Selection,
            HapticStyle::Success,
            HapticStyle::Warning,
            HapticStyle::Error,
        ];

        assert_eq!(styles.len(), 7);
    }

    #[test]
    fn test_screen_orientation_variants() {
        let orientations = vec![
            ScreenOrientation::Portrait,
            ScreenOrientation::Landscape,
            ScreenOrientation::PortraitUpsideDown,
            ScreenOrientation::LandscapeRight,
        ];

        assert_eq!(orientations.len(), 4);
    }

    #[cfg(not(any(target_os = "android", target_os = "ios")))]
    #[test]
    fn test_stub_backend() {
        let backend = StubBackend::new();

        assert_eq!(backend.screen_size(), (800, 600));
        assert_eq!(backend.scale_factor(), 1.0);
        assert_eq!(backend.safe_area_insets(), (0.0, 0.0, 0.0, 0.0));
        assert_eq!(backend.orientation(), ScreenOrientation::Portrait);
        assert_eq!(backend.get_clipboard_text(), None);
        assert_eq!(backend.system_theme(), Some(SystemTheme::Light));
    }
}