openkit 0.1.3

A cross-platform CSS-styled UI framework for Rust
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
//! Platform abstraction layer.
//!
//! Provides a unified interface for window management and event handling
//! across Windows, macOS, Linux, and FreeBSD using winit.
//!
//! # OpenKit's Rendering Model
//!
//! OpenKit renders its own chrome (window decorations, widgets, etc.) using:
//! - **wgpu** for GPU-accelerated rendering (Direct3D 12, Metal, Vulkan, OpenGL)
//! - **tiny-skia** as a CPU fallback
//!
//! No platform-specific UI libraries are used. This ensures:
//! - Pixel-perfect consistency across all platforms
//! - Full control over styling via CSS
//! - No dependency on system UI frameworks
//!
//! # Supported Platforms
//!
//! | Platform | Window Backend | GPU Backend |
//! |----------|---------------|-------------|
//! | Windows 10+ | winit (Win32) | wgpu (DX12/Vulkan) |
//! | macOS 10.15+ | winit (Cocoa) | wgpu (Metal) |
//! | Linux | winit (X11/Wayland) | wgpu (Vulkan/GL) |
//! | FreeBSD | winit (X11) | wgpu (Vulkan/GL) |
//!
//! # Platform Submodules
//!
//! Platform-specific submodules provide detection utilities only:
//! - [`windows`] - Windows version detection
//! - [`macos`] - macOS version detection
//! - [`linux`] - Display server and DE detection
//! - [`freebsd`] - DE detection

mod window;

// Platform-specific modules
#[cfg(target_os = "windows")]
pub mod windows;

#[cfg(target_os = "macos")]
pub mod macos;

#[cfg(target_os = "linux")]
pub mod linux;

#[cfg(target_os = "freebsd")]
pub mod freebsd;

pub use window::{Window, WindowBuilder, WindowConfig};

/// Initialize platform-specific features.
/// Call this early in your application startup.
pub fn init() {
    #[cfg(target_os = "windows")]
    windows::init();

    #[cfg(target_os = "macos")]
    macos::init();

    #[cfg(target_os = "linux")]
    linux::init();

    #[cfg(target_os = "freebsd")]
    freebsd::init();
}

/// Get the current platform name.
pub fn platform_name() -> &'static str {
    #[cfg(target_os = "windows")]
    return "Windows";

    #[cfg(target_os = "macos")]
    return "macOS";

    #[cfg(target_os = "linux")]
    return "Linux";

    #[cfg(target_os = "freebsd")]
    return "FreeBSD";

    #[cfg(not(any(
        target_os = "windows",
        target_os = "macos",
        target_os = "linux",
        target_os = "freebsd"
    )))]
    return "Unknown";
}

/// Check if the current platform is a desktop platform.
pub fn is_desktop() -> bool {
    cfg!(any(
        target_os = "windows",
        target_os = "macos",
        target_os = "linux",
        target_os = "freebsd"
    ))
}

use crate::event::{Event, KeyEvent, KeyEventKind, Key, Modifiers, MouseButton, MouseEvent, MouseEventKind, WindowEvent};
use crate::geometry::Point;
use crate::theme::Theme;

use winit::application::ApplicationHandler;
use winit::dpi::{PhysicalPosition, PhysicalSize};
use winit::event::{ElementState, WindowEvent as WinitWindowEvent};
use winit::event_loop::{ActiveEventLoop, ControlFlow, EventLoop};
use winit::window::WindowId;

/// Platform abstraction for running the application.
pub struct Platform {
    event_loop: Option<EventLoop<()>>,
}

impl Platform {
    /// Create a new platform instance.
    pub fn new() -> Result<Self, PlatformError> {
        let event_loop = EventLoop::new().map_err(|e| PlatformError::EventLoopCreation(e.to_string()))?;
        event_loop.set_control_flow(ControlFlow::Wait);

        Ok(Self {
            event_loop: Some(event_loop),
        })
    }

    /// Run the application event loop.
    pub fn run<F>(mut self, handler: F) -> Result<(), PlatformError>
    where
        F: FnMut(&ActiveEventLoop, PlatformEvent) + 'static,
    {
        let event_loop = self.event_loop.take().ok_or(PlatformError::AlreadyRunning)?;

        let mut app = PlatformApp {
            handler: Box::new(handler),
        };

        event_loop
            .run_app(&mut app)
            .map_err(|e| PlatformError::EventLoopRun(e.to_string()))
    }

    /// Detect the system theme preference.
    pub fn detect_theme() -> Theme {
        // This will be called after window creation to get actual theme
        Theme::Auto
    }
}

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

/// Platform events.
#[derive(Debug)]
pub enum PlatformEvent {
    /// Event loop resumed (create windows here)
    Resumed,
    /// Window event
    Window { window_id: WindowId, event: Event },
    /// Request to redraw
    RedrawRequested { window_id: WindowId },
    /// About to wait for events
    AboutToWait,
}

/// Platform-specific application handler.
#[allow(clippy::type_complexity)]
struct PlatformApp {
    handler: Box<dyn FnMut(&ActiveEventLoop, PlatformEvent)>,
}

impl ApplicationHandler for PlatformApp {
    fn resumed(&mut self, event_loop: &ActiveEventLoop) {
        (self.handler)(event_loop, PlatformEvent::Resumed);
    }

    fn window_event(
        &mut self,
        event_loop: &ActiveEventLoop,
        window_id: WindowId,
        event: WinitWindowEvent,
    ) {
        let platform_event = match event {
            WinitWindowEvent::CloseRequested => Some(Event::Window(WindowEvent::CloseRequested)),
            WinitWindowEvent::Resized(PhysicalSize { width, height }) => {
                Some(Event::Window(WindowEvent::Resized { width, height }))
            }
            WinitWindowEvent::Moved(PhysicalPosition { x, y }) => {
                Some(Event::Window(WindowEvent::Moved { x, y }))
            }
            WinitWindowEvent::Focused(focused) => {
                if focused {
                    Some(Event::Window(WindowEvent::Focused))
                } else {
                    Some(Event::Window(WindowEvent::Unfocused))
                }
            }
            WinitWindowEvent::ScaleFactorChanged { scale_factor, .. } => {
                Some(Event::Window(WindowEvent::ScaleFactorChanged { scale_factor }))
            }
            WinitWindowEvent::ThemeChanged(theme) => {
                let dark = matches!(theme, winit::window::Theme::Dark);
                Some(Event::Window(WindowEvent::ThemeChanged { dark }))
            }
            WinitWindowEvent::CursorMoved { position, .. } => {
                Some(Event::Mouse(MouseEvent::new(
                    MouseEventKind::Move,
                    Point::new(position.x as f32, position.y as f32),
                )))
            }
            WinitWindowEvent::CursorEntered { .. } => {
                Some(Event::Mouse(MouseEvent::new(
                    MouseEventKind::Enter,
                    Point::ZERO,
                )))
            }
            WinitWindowEvent::CursorLeft { .. } => {
                Some(Event::Mouse(MouseEvent::new(
                    MouseEventKind::Leave,
                    Point::ZERO,
                )))
            }
            WinitWindowEvent::MouseInput { state, button, .. } => {
                let kind = match state {
                    ElementState::Pressed => MouseEventKind::Down,
                    ElementState::Released => MouseEventKind::Up,
                };
                let button = match button {
                    winit::event::MouseButton::Left => MouseButton::Left,
                    winit::event::MouseButton::Right => MouseButton::Right,
                    winit::event::MouseButton::Middle => MouseButton::Middle,
                    winit::event::MouseButton::Back => MouseButton::Back,
                    winit::event::MouseButton::Forward => MouseButton::Forward,
                    winit::event::MouseButton::Other(id) => MouseButton::Other(id),
                };
                Some(Event::Mouse(
                    MouseEvent::new(kind, Point::ZERO).with_button(button),
                ))
            }
            WinitWindowEvent::MouseWheel { delta, .. } => {
                let (delta_x, delta_y) = match delta {
                    winit::event::MouseScrollDelta::LineDelta(x, y) => {
                        (x as i32 * 120, y as i32 * 120)
                    }
                    winit::event::MouseScrollDelta::PixelDelta(pos) => {
                        (pos.x as i32, pos.y as i32)
                    }
                };
                Some(Event::Mouse(MouseEvent {
                    kind: MouseEventKind::Scroll { delta_x, delta_y },
                    position: Point::ZERO,
                    button: None,
                    modifiers: Modifiers::empty(),
                }))
            }
            WinitWindowEvent::KeyboardInput { event, .. } => {
                let kind = match event.state {
                    ElementState::Pressed => KeyEventKind::Down,
                    ElementState::Released => KeyEventKind::Up,
                };
                let key = convert_key(&event.logical_key);
                let text = event.text.as_ref().map(|t| t.to_string());
                Some(Event::Key(KeyEvent {
                    kind,
                    key,
                    physical_key: None,
                    text,
                    modifiers: Modifiers::empty(), // TODO: Track modifiers
                    is_repeat: event.repeat,
                }))
            }
            WinitWindowEvent::RedrawRequested => {
                (self.handler)(
                    event_loop,
                    PlatformEvent::RedrawRequested { window_id },
                );
                return;
            }
            _ => None,
        };

        if let Some(event) = platform_event {
            (self.handler)(event_loop, PlatformEvent::Window { window_id, event });
        }
    }

    fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) {
        (self.handler)(event_loop, PlatformEvent::AboutToWait);
    }
}

/// Convert winit key to OpenKit key.
fn convert_key(key: &winit::keyboard::Key) -> Key {
    use winit::keyboard::{Key as WKey, NamedKey};

    match key {
        WKey::Named(named) => match named {
            NamedKey::Enter => Key::Enter,
            NamedKey::Tab => Key::Tab,
            NamedKey::Space => Key::Space,
            NamedKey::Backspace => Key::Backspace,
            NamedKey::Delete => Key::Delete,
            NamedKey::Escape => Key::Escape,
            NamedKey::ArrowUp => Key::Up,
            NamedKey::ArrowDown => Key::Down,
            NamedKey::ArrowLeft => Key::Left,
            NamedKey::ArrowRight => Key::Right,
            NamedKey::Home => Key::Home,
            NamedKey::End => Key::End,
            NamedKey::PageUp => Key::PageUp,
            NamedKey::PageDown => Key::PageDown,
            NamedKey::Insert => Key::Insert,
            NamedKey::F1 => Key::F1,
            NamedKey::F2 => Key::F2,
            NamedKey::F3 => Key::F3,
            NamedKey::F4 => Key::F4,
            NamedKey::F5 => Key::F5,
            NamedKey::F6 => Key::F6,
            NamedKey::F7 => Key::F7,
            NamedKey::F8 => Key::F8,
            NamedKey::F9 => Key::F9,
            NamedKey::F10 => Key::F10,
            NamedKey::F11 => Key::F11,
            NamedKey::F12 => Key::F12,
            NamedKey::Shift => Key::Shift,
            NamedKey::Control => Key::Control,
            NamedKey::Alt => Key::Alt,
            NamedKey::Super => Key::Super,
            NamedKey::CapsLock => Key::CapsLock,
            NamedKey::NumLock => Key::NumLock,
            NamedKey::ScrollLock => Key::ScrollLock,
            NamedKey::PrintScreen => Key::PrintScreen,
            NamedKey::Pause => Key::Pause,
            _ => Key::Unknown,
        },
        WKey::Character(c) => {
            let c = c.to_lowercase().chars().next().unwrap_or(' ');
            match c {
                'a' => Key::A,
                'b' => Key::B,
                'c' => Key::C,
                'd' => Key::D,
                'e' => Key::E,
                'f' => Key::F,
                'g' => Key::G,
                'h' => Key::H,
                'i' => Key::I,
                'j' => Key::J,
                'k' => Key::K,
                'l' => Key::L,
                'm' => Key::M,
                'n' => Key::N,
                'o' => Key::O,
                'p' => Key::P,
                'q' => Key::Q,
                'r' => Key::R,
                's' => Key::S,
                't' => Key::T,
                'u' => Key::U,
                'v' => Key::V,
                'w' => Key::W,
                'x' => Key::X,
                'y' => Key::Y,
                'z' => Key::Z,
                '0' => Key::Num0,
                '1' => Key::Num1,
                '2' => Key::Num2,
                '3' => Key::Num3,
                '4' => Key::Num4,
                '5' => Key::Num5,
                '6' => Key::Num6,
                '7' => Key::Num7,
                '8' => Key::Num8,
                '9' => Key::Num9,
                '-' => Key::Minus,
                '=' => Key::Equal,
                '[' => Key::BracketLeft,
                ']' => Key::BracketRight,
                '\\' => Key::Backslash,
                ';' => Key::Semicolon,
                '\'' => Key::Quote,
                '`' => Key::Grave,
                ',' => Key::Comma,
                '.' => Key::Period,
                '/' => Key::Slash,
                ' ' => Key::Space,
                _ => Key::Unknown,
            }
        }
        _ => Key::Unknown,
    }
}

/// Platform error types.
#[derive(Debug, Clone)]
pub enum PlatformError {
    EventLoopCreation(String),
    EventLoopRun(String),
    WindowCreation(String),
    AlreadyRunning,
}

impl std::fmt::Display for PlatformError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            PlatformError::EventLoopCreation(e) => write!(f, "Failed to create event loop: {}", e),
            PlatformError::EventLoopRun(e) => write!(f, "Event loop error: {}", e),
            PlatformError::WindowCreation(e) => write!(f, "Failed to create window: {}", e),
            PlatformError::AlreadyRunning => write!(f, "Event loop is already running"),
        }
    }
}

impl std::error::Error for PlatformError {}