Skip to main content

kova_native_platform/
lib.rs

1//! Windowing and OS integration for Kova Native.
2//!
3//! This crate is the only place that talks to the windowing system (winit).
4//! It owns the event loop, creates windows and translates native events into
5//! [`kova_native_input::InputEvent`]s in logical pixels. Everything above it is
6//! platform independent, which is what makes Linux and macOS ports a matter
7//! of backend work rather than framework changes.
8
9mod convert;
10
11use kova_native_core::{Bounds, KovaError, KovaResult, Point, Size};
12use kova_native_input::{
13    ClickTracker, CursorStyle, ImeEvent, InputEvent, KeyDownEvent, KeyUpEvent, Keystroke,
14    Modifiers, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, PenEvent, PenPhase,
15    ScrollDelta, ScrollWheelEvent,
16};
17use std::collections::HashMap;
18use std::path::PathBuf;
19use std::sync::Arc;
20use std::time::Instant;
21use winit::application::ApplicationHandler;
22use winit::event::{ElementState, MouseScrollDelta, WindowEvent};
23use winit::event_loop::{ActiveEventLoop, ControlFlow, EventLoop, EventLoopProxy};
24use winit::raw_window_handle::{
25    DisplayHandle, HandleError, HasDisplayHandle, HasWindowHandle, WindowHandle,
26};
27
28/// Opaque identifier of a platform window.
29#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
30pub struct PlatformWindowId(winit::window::WindowId);
31
32/// Options used to create a window.
33#[derive(Clone, Debug)]
34pub struct WindowAttributes {
35    pub title: String,
36    /// Inner size in logical pixels.
37    pub size: Size,
38    pub min_size: Option<Size>,
39    pub resizable: bool,
40    pub decorations: bool,
41    pub maximized: bool,
42    /// Created hidden; the app shows it after the first frame is presented
43    /// to avoid a white flash.
44    pub visible: bool,
45}
46
47impl Default for WindowAttributes {
48    fn default() -> Self {
49        WindowAttributes {
50            title: "Kova Native".into(),
51            size: Size::new(960.0, 640.0),
52            min_size: None,
53            resizable: true,
54            decorations: true,
55            maximized: false,
56            visible: false,
57        }
58    }
59}
60
61/// A native window. Cheap to clone; implements the raw window handle traits
62/// so the renderer can create a surface for it.
63#[derive(Clone)]
64pub struct PlatformWindow {
65    inner: Arc<winit::window::Window>,
66}
67
68impl PlatformWindow {
69    pub fn id(&self) -> PlatformWindowId {
70        PlatformWindowId(self.inner.id())
71    }
72
73    /// Inner size in physical pixels.
74    pub fn physical_size(&self) -> (u32, u32) {
75        let s = self.inner.inner_size();
76        (s.width, s.height)
77    }
78
79    pub fn scale_factor(&self) -> f32 {
80        self.inner.scale_factor() as f32
81    }
82
83    /// Inner size in logical pixels.
84    pub fn logical_size(&self) -> Size {
85        let (w, h) = self.physical_size();
86        let s = self.scale_factor();
87        Size::new(w as f32 / s, h as f32 / s)
88    }
89
90    pub fn request_redraw(&self) {
91        self.inner.request_redraw();
92    }
93
94    /// Must be called right before presenting a frame (lets the compositor
95    /// schedule the next frame callback optimally on some platforms).
96    pub fn pre_present_notify(&self) {
97        self.inner.pre_present_notify();
98    }
99
100    pub fn set_title(&self, title: &str) {
101        self.inner.set_title(title);
102    }
103
104    pub fn set_visible(&self, visible: bool) {
105        self.inner.set_visible(visible);
106    }
107
108    pub fn set_cursor(&self, cursor: CursorStyle) {
109        self.inner.set_cursor(convert::cursor(cursor));
110    }
111
112    pub fn set_ime_allowed(&self, allowed: bool) {
113        self.inner.set_ime_allowed(allowed);
114    }
115
116    /// Tells the IME where the caret is (logical pixels) so candidate
117    /// windows appear next to it.
118    pub fn set_ime_cursor_area(&self, area: Bounds) {
119        self.inner.set_ime_cursor_area(
120            winit::dpi::LogicalPosition::new(area.origin.x as f64, area.origin.y as f64),
121            winit::dpi::LogicalSize::new(area.size.width as f64, area.size.height as f64),
122        );
123    }
124
125    pub fn focus(&self) {
126        self.inner.focus_window();
127    }
128
129    pub fn minimize(&self) {
130        self.inner.set_minimized(true);
131    }
132
133    pub fn set_maximized(&self, maximized: bool) {
134        self.inner.set_maximized(maximized);
135    }
136
137    pub fn is_maximized(&self) -> bool {
138        self.inner.is_maximized()
139    }
140}
141
142impl HasWindowHandle for PlatformWindow {
143    fn window_handle(&self) -> Result<WindowHandle<'_>, HandleError> {
144        self.inner.window_handle()
145    }
146}
147
148impl HasDisplayHandle for PlatformWindow {
149    fn display_handle(&self) -> Result<DisplayHandle<'_>, HandleError> {
150        self.inner.display_handle()
151    }
152}
153
154/// Window level events.
155#[derive(Clone, Debug, PartialEq)]
156pub enum PlatformEvent {
157    /// The inner size changed (physical pixels).
158    Resized {
159        width: u32,
160        height: u32,
161    },
162    ScaleFactorChanged(f32),
163    RedrawRequested,
164    CloseRequested,
165    Focused(bool),
166    Occluded(bool),
167    /// A file was dropped onto the window.
168    FileDropped(PathBuf),
169    Input(InputEvent),
170}
171
172/// Callbacks from the event loop. All run on the main thread.
173pub trait PlatformHandler {
174    /// The event loop is ready; create initial windows here.
175    fn init(&mut self, cx: &mut PlatformContext);
176    fn window_event(
177        &mut self,
178        cx: &mut PlatformContext,
179        window: PlatformWindowId,
180        event: PlatformEvent,
181    );
182    /// All pending events were processed; the loop is about to sleep.
183    fn about_to_wait(&mut self, cx: &mut PlatformContext);
184    /// A [`Waker`] was triggered from another thread.
185    fn wake(&mut self, _cx: &mut PlatformContext) {}
186}
187
188/// Access to the running event loop.
189pub struct PlatformContext<'a> {
190    event_loop: &'a ActiveEventLoop,
191    state: &'a mut LoopState,
192}
193
194impl PlatformContext<'_> {
195    pub fn create_window(&mut self, attrs: &WindowAttributes) -> KovaResult<PlatformWindow> {
196        let mut wa = winit::window::Window::default_attributes()
197            .with_title(attrs.title.clone())
198            .with_inner_size(winit::dpi::LogicalSize::new(
199                attrs.size.width as f64,
200                attrs.size.height as f64,
201            ))
202            .with_resizable(attrs.resizable)
203            .with_decorations(attrs.decorations)
204            .with_maximized(attrs.maximized)
205            .with_visible(attrs.visible);
206        if let Some(min) = attrs.min_size {
207            wa = wa.with_min_inner_size(winit::dpi::LogicalSize::new(
208                min.width as f64,
209                min.height as f64,
210            ));
211        }
212        let window = self
213            .event_loop
214            .create_window(wa)
215            .map_err(|e| KovaError::Platform(e.to_string()))?;
216        let window = PlatformWindow {
217            inner: Arc::new(window),
218        };
219        self.state.windows.insert(
220            window.inner.id(),
221            WindowInputState::new(window.scale_factor() as f64),
222        );
223        Ok(window)
224    }
225
226    /// Forgets the input state of a closed window.
227    pub fn destroy_window(&mut self, id: PlatformWindowId) {
228        self.state.windows.remove(&id.0);
229    }
230
231    /// Stops the event loop; `run` returns afterwards.
232    pub fn exit(&self) {
233        self.event_loop.set_control_flow(ControlFlow::Poll);
234        self.event_loop.exit();
235    }
236
237    /// Wake up at `deadline` even if no events arrive (timers, delayed animations).
238    pub fn wake_at(&mut self, deadline: Instant) {
239        self.state.wake_at = Some(self.state.wake_at.map_or(deadline, |d| d.min(deadline)));
240    }
241
242    pub fn waker(&self) -> Waker {
243        Waker {
244            proxy: self.state.proxy.clone(),
245        }
246    }
247}
248
249/// Wakes the event loop from any thread.
250#[derive(Clone)]
251pub struct Waker {
252    proxy: EventLoopProxy<UserEvent>,
253}
254
255impl Waker {
256    pub fn wake(&self) {
257        let _ = self.proxy.send_event(UserEvent::Wake);
258    }
259}
260
261#[derive(Debug, Clone, Copy)]
262pub enum UserEvent {
263    Wake,
264}
265
266/// Per-window input tracking (cursor position, buttons, modifiers, clicks).
267struct WindowInputState {
268    scale: f64,
269    cursor: Point,
270    modifiers: Modifiers,
271    pressed: Vec<MouseButton>,
272    clicks: ClickTracker,
273}
274
275impl WindowInputState {
276    fn new(scale: f64) -> Self {
277        WindowInputState {
278            scale,
279            cursor: Point::ZERO,
280            modifiers: Modifiers::default(),
281            pressed: Vec::new(),
282            clicks: ClickTracker::default(),
283        }
284    }
285}
286
287struct LoopState {
288    windows: HashMap<winit::window::WindowId, WindowInputState>,
289    wake_at: Option<Instant>,
290    proxy: EventLoopProxy<UserEvent>,
291    initialized: bool,
292}
293
294struct Runner<H: PlatformHandler> {
295    handler: H,
296    state: LoopState,
297}
298
299impl<H: PlatformHandler> Runner<H> {
300    fn cx<'a>(state: &'a mut LoopState, event_loop: &'a ActiveEventLoop) -> PlatformContext<'a> {
301        PlatformContext { event_loop, state }
302    }
303
304    fn translate(
305        &mut self,
306        id: winit::window::WindowId,
307        event: &WindowEvent,
308    ) -> Option<PlatformEvent> {
309        let input = self.state.windows.get_mut(&id)?;
310        Some(match event {
311            WindowEvent::Resized(size) => PlatformEvent::Resized {
312                width: size.width,
313                height: size.height,
314            },
315            WindowEvent::ScaleFactorChanged { scale_factor, .. } => {
316                input.scale = *scale_factor;
317                PlatformEvent::ScaleFactorChanged(*scale_factor as f32)
318            }
319            WindowEvent::RedrawRequested => PlatformEvent::RedrawRequested,
320            WindowEvent::CloseRequested => PlatformEvent::CloseRequested,
321            WindowEvent::Focused(focused) => {
322                if !focused {
323                    input.pressed.clear();
324                }
325                PlatformEvent::Focused(*focused)
326            }
327            WindowEvent::Occluded(occluded) => PlatformEvent::Occluded(*occluded),
328            WindowEvent::DroppedFile(path) => PlatformEvent::FileDropped(path.clone()),
329            WindowEvent::Touch(touch) => {
330                let pressure = match touch.force? {
331                    winit::event::Force::Normalized(value) => value,
332                    winit::event::Force::Calibrated {
333                        force,
334                        max_possible_force,
335                        ..
336                    } if max_possible_force > 0.0 => force / max_possible_force,
337                    winit::event::Force::Calibrated { .. } => 0.0,
338                }
339                .clamp(0.0, 1.0) as f32;
340                let phase = match touch.phase {
341                    winit::event::TouchPhase::Started => PenPhase::Started,
342                    winit::event::TouchPhase::Moved => PenPhase::Moved,
343                    winit::event::TouchPhase::Ended => PenPhase::Ended,
344                    winit::event::TouchPhase::Cancelled => PenPhase::Cancelled,
345                };
346                PlatformEvent::Input(InputEvent::Pen(PenEvent {
347                    pointer_id: touch.id,
348                    phase,
349                    position: convert::logical(touch.location, input.scale),
350                    pressure,
351                }))
352            }
353            WindowEvent::ModifiersChanged(m) => {
354                input.modifiers = convert::modifiers(m.state());
355                PlatformEvent::Input(InputEvent::ModifiersChanged(input.modifiers))
356            }
357            WindowEvent::CursorMoved { position, .. } => {
358                input.cursor = convert::logical(*position, input.scale);
359                PlatformEvent::Input(InputEvent::MouseMove(MouseMoveEvent {
360                    position: input.cursor,
361                    pressed_button: input.pressed.first().copied(),
362                    modifiers: input.modifiers,
363                }))
364            }
365            WindowEvent::CursorLeft { .. } => PlatformEvent::Input(InputEvent::MouseExit),
366            WindowEvent::MouseInput { state, button, .. } => {
367                let button = convert::mouse_button(*button);
368                match state {
369                    ElementState::Pressed => {
370                        if !input.pressed.contains(&button) {
371                            input.pressed.push(button);
372                        }
373                        let click_count = input.clicks.press(button, input.cursor, Instant::now());
374                        PlatformEvent::Input(InputEvent::MouseDown(MouseDownEvent {
375                            button,
376                            position: input.cursor,
377                            modifiers: input.modifiers,
378                            click_count,
379                        }))
380                    }
381                    ElementState::Released => {
382                        input.pressed.retain(|b| *b != button);
383                        PlatformEvent::Input(InputEvent::MouseUp(MouseUpEvent {
384                            button,
385                            position: input.cursor,
386                            modifiers: input.modifiers,
387                            click_count: input.clicks.count().max(1),
388                        }))
389                    }
390                }
391            }
392            WindowEvent::MouseWheel { delta, .. } => {
393                let delta = match delta {
394                    MouseScrollDelta::LineDelta(x, y) => ScrollDelta::Lines(Point::new(*x, *y)),
395                    MouseScrollDelta::PixelDelta(p) => ScrollDelta::Pixels(Point::new(
396                        (p.x / input.scale) as f32,
397                        (p.y / input.scale) as f32,
398                    )),
399                };
400                PlatformEvent::Input(InputEvent::ScrollWheel(ScrollWheelEvent {
401                    position: input.cursor,
402                    delta,
403                    modifiers: input.modifiers,
404                }))
405            }
406            WindowEvent::KeyboardInput { event, .. } => {
407                #[cfg(any(target_os = "windows", target_os = "macos", target_os = "linux"))]
408                let unmodified = {
409                    use winit::platform::modifier_supplement::KeyEventExtModifierSupplement;
410                    event.key_without_modifiers()
411                };
412                #[cfg(not(any(target_os = "windows", target_os = "macos", target_os = "linux")))]
413                let unmodified = event.logical_key.clone();
414                let key = match convert::key(&event.logical_key) {
415                    kova_native_input::Key::Named(n) => kova_native_input::Key::Named(n),
416                    _ => convert::key(&unmodified),
417                };
418                let keystroke = Keystroke {
419                    modifiers: input.modifiers,
420                    key,
421                    key_char: event
422                        .text
423                        .as_ref()
424                        .map(|t| t.to_string())
425                        .filter(|t| !t.chars().any(char::is_control)),
426                };
427                match event.state {
428                    ElementState::Pressed => {
429                        PlatformEvent::Input(InputEvent::KeyDown(KeyDownEvent {
430                            keystroke,
431                            is_repeat: event.repeat,
432                        }))
433                    }
434                    ElementState::Released => {
435                        PlatformEvent::Input(InputEvent::KeyUp(KeyUpEvent { keystroke }))
436                    }
437                }
438            }
439            WindowEvent::Ime(ime) => PlatformEvent::Input(InputEvent::Ime(match ime {
440                winit::event::Ime::Enabled => ImeEvent::Enabled,
441                winit::event::Ime::Preedit(text, cursor) => ImeEvent::Preedit {
442                    text: text.clone(),
443                    cursor: *cursor,
444                },
445                winit::event::Ime::Commit(text) => ImeEvent::Commit(text.clone()),
446                winit::event::Ime::Disabled => ImeEvent::Disabled,
447            })),
448            _ => return None,
449        })
450    }
451}
452
453impl<H: PlatformHandler> ApplicationHandler<UserEvent> for Runner<H> {
454    fn resumed(&mut self, event_loop: &ActiveEventLoop) {
455        if self.state.initialized {
456            return;
457        }
458        self.state.initialized = true;
459        let mut cx = Self::cx(&mut self.state, event_loop);
460        self.handler.init(&mut cx);
461    }
462
463    fn window_event(
464        &mut self,
465        event_loop: &ActiveEventLoop,
466        id: winit::window::WindowId,
467        event: WindowEvent,
468    ) {
469        if let Some(event) = self.translate(id, &event) {
470            let mut cx = Self::cx(&mut self.state, event_loop);
471            self.handler
472                .window_event(&mut cx, PlatformWindowId(id), event);
473        }
474    }
475
476    fn user_event(&mut self, event_loop: &ActiveEventLoop, event: UserEvent) {
477        match event {
478            UserEvent::Wake => {
479                let mut cx = Self::cx(&mut self.state, event_loop);
480                self.handler.wake(&mut cx);
481            }
482        }
483    }
484
485    fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) {
486        self.state.wake_at = None;
487        {
488            let mut cx = Self::cx(&mut self.state, event_loop);
489            self.handler.about_to_wait(&mut cx);
490        }
491        // On Win32, AboutToWait runs before winit enters its OS wait. A
492        // handler may request exit here; overwriting Poll with Wait would
493        // strand that exit until another unrelated native message arrives.
494        event_loop.set_control_flow(if event_loop.exiting() {
495            ControlFlow::Poll
496        } else {
497            match self.state.wake_at {
498                Some(deadline) => ControlFlow::WaitUntil(deadline),
499                None => ControlFlow::Wait,
500            }
501        });
502    }
503}
504
505/// Runs the event loop until [`PlatformContext::exit`] is called.
506pub fn run(handler: impl PlatformHandler) -> KovaResult<()> {
507    let event_loop = EventLoop::<UserEvent>::with_user_event()
508        .build()
509        .map_err(|e| KovaError::Platform(format!("cannot create event loop: {e}")))?;
510    event_loop.set_control_flow(ControlFlow::Wait);
511    let proxy = event_loop.create_proxy();
512    let mut runner = Runner {
513        handler,
514        state: LoopState {
515            windows: HashMap::new(),
516            wake_at: None,
517            proxy,
518            initialized: false,
519        },
520    };
521    let result = event_loop
522        .run_app(&mut runner)
523        .map_err(|e| KovaError::Platform(e.to_string()));
524    log::debug!("kova-native-platform: event loop returned");
525    result
526}
527
528/// System clipboard access.
529pub struct Clipboard {
530    inner: Option<arboard::Clipboard>,
531}
532
533impl Default for Clipboard {
534    fn default() -> Self {
535        Self::new()
536    }
537}
538
539impl Clipboard {
540    pub fn new() -> Self {
541        Clipboard {
542            inner: arboard::Clipboard::new().ok(),
543        }
544    }
545
546    pub fn read_text(&mut self) -> Option<String> {
547        self.inner.as_mut()?.get_text().ok()
548    }
549
550    pub fn write_text(&mut self, text: &str) {
551        if let Some(c) = self.inner.as_mut() {
552            let _ = c.set_text(text.to_owned());
553        }
554    }
555}