mkgraphic 0.4.1

A Rust port of the cycfi/elements GUI framework
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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
//! Host module for platform-specific implementations.
//!
//! This module provides the platform abstraction layer for creating windows
//! and running the application event loop.

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

#[cfg(target_os = "windows")]
mod windows;

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

#[cfg(target_os = "macos")]
pub use macos::{choose_file_to_open, choose_file_to_save, choose_folder, MacOSApp, MacOSWindow};

#[cfg(target_os = "windows")]
pub use self::windows::{WindowsApp, WindowsTimer, WindowsWindow};

#[cfg(target_os = "linux")]
pub use self::linux::{LinuxApp, LinuxTimer, LinuxWindow};

use crate::element::ElementPtr;
use crate::support::point::Extent;
use crate::view::View;

#[cfg(target_os = "macos")]
use objc2_foundation::MainThreadMarker;

/// Window position.
#[derive(Debug, Clone, Copy)]
pub struct WindowPosition {
    pub x: i32,
    pub y: i32,
}

impl WindowPosition {
    /// Creates a new window position.
    pub fn new(x: i32, y: i32) -> Self {
        Self { x, y }
    }

    /// Center the window on screen.
    pub fn center() -> Self {
        Self { x: -1, y: -1 } // Sentinel value for centering
    }
}

impl Default for WindowPosition {
    fn default() -> Self {
        Self::center()
    }
}

/// Window style flags.
#[derive(Debug, Clone, Copy)]
pub struct WindowStyle {
    pub closable: bool,
    pub miniaturizable: bool,
    pub resizable: bool,
    pub borderless: bool,
}

impl Default for WindowStyle {
    fn default() -> Self {
        Self {
            closable: true,
            miniaturizable: true,
            resizable: true,
            borderless: false,
        }
    }
}

impl WindowStyle {
    /// Creates a borderless window style.
    pub fn borderless() -> Self {
        Self {
            closable: false,
            miniaturizable: false,
            resizable: false,
            borderless: true,
        }
    }
}

/// Window handle type (platform-specific).
pub type WindowHandle = *mut std::ffi::c_void;

/// View handle type (platform-specific).
pub type ViewHandle = *mut std::ffi::c_void;

/// Window builder for creating windows with various options.
pub struct WindowBuilder {
    title: String,
    size: Extent,
    position: WindowPosition,
    style: WindowStyle,
    min_size: Option<Extent>,
    max_size: Option<Extent>,
}

impl WindowBuilder {
    /// Creates a new window builder with the given title and size.
    pub fn new(title: impl Into<String>, size: Extent) -> Self {
        Self {
            title: title.into(),
            size,
            position: WindowPosition::default(),
            style: WindowStyle::default(),
            min_size: None,
            max_size: None,
        }
    }

    /// Sets the window position.
    pub fn position(mut self, pos: WindowPosition) -> Self {
        self.position = pos;
        self
    }

    /// Sets the window style.
    pub fn style(mut self, style: WindowStyle) -> Self {
        self.style = style;
        self
    }

    /// Sets the minimum size.
    pub fn min_size(mut self, size: Extent) -> Self {
        self.min_size = Some(size);
        self
    }

    /// Sets the maximum size.
    pub fn max_size(mut self, size: Extent) -> Self {
        self.max_size = Some(size);
        self
    }

    /// Builds the window.
    pub fn build(self) -> Window {
        Window::new_with_options(self)
    }
}

/// A platform window.
pub struct Window {
    title: String,
    size: Extent,
    position: WindowPosition,
    style: WindowStyle,
    view: View,
    handle: Option<WindowHandle>,
    #[cfg(target_os = "macos")]
    macos_window: Option<MacOSWindow>,
    #[cfg(target_os = "windows")]
    windows_window: Option<WindowsWindow>,
    #[cfg(target_os = "linux")]
    linux_window: Option<LinuxWindow>,
}

impl Window {
    /// Creates a new window with the given title and size.
    pub fn new(title: impl Into<String>, size: Extent) -> Self {
        let title_str = title.into();

        #[cfg(target_os = "macos")]
        let macos_window =
            { MainThreadMarker::new().map(|mtm| MacOSWindow::new(&title_str, size, mtm)) };
        #[cfg(target_os = "windows")]
        let windows_window = WindowsWindow::new(&title_str, size);
        #[cfg(target_os = "linux")]
        let linux_window = LinuxWindow::new(&title_str, size);

        Self {
            title: title_str,
            size,
            position: WindowPosition::default(),
            style: WindowStyle::default(),
            view: View::new(size),
            handle: None,
            #[cfg(target_os = "macos")]
            macos_window,
            #[cfg(target_os = "windows")]
            windows_window,
            #[cfg(target_os = "linux")]
            linux_window,
        }
    }

    /// Creates a new window with the given options.
    fn new_with_options(builder: WindowBuilder) -> Self {
        #[cfg(target_os = "macos")]
        let macos_window = {
            MainThreadMarker::new().map(|mtm| {
                MacOSWindow::new_with_style(&builder.title, builder.size, builder.style, mtm)
            })
        };
        #[cfg(target_os = "windows")]
        let windows_window = WindowsWindow::new(&builder.title, builder.size);
        #[cfg(target_os = "linux")]
        let linux_window = LinuxWindow::new(&builder.title, builder.size);

        Self {
            title: builder.title,
            size: builder.size,
            position: builder.position,
            style: builder.style,
            view: View::new(builder.size),
            handle: None,
            #[cfg(target_os = "macos")]
            macos_window,
            #[cfg(target_os = "windows")]
            windows_window,
            #[cfg(target_os = "linux")]
            linux_window,
        }
    }

    /// Returns the window title.
    pub fn title(&self) -> &str {
        &self.title
    }

    /// Sets the window title.
    pub fn set_title(&mut self, title: impl Into<String>) {
        self.title = title.into();
        #[cfg(target_os = "macos")]
        if let Some(ref win) = self.macos_window {
            win.set_title(&self.title);
        }
        #[cfg(target_os = "windows")]
        if let Some(ref win) = self.windows_window {
            win.set_title(&self.title);
        }
        #[cfg(target_os = "linux")]
        if let Some(ref win) = self.linux_window {
            win.set_title(&self.title);
        }
    }

    /// Returns the window size.
    pub fn size(&self) -> Extent {
        self.size
    }

    /// Sets the window size.
    pub fn set_size(&mut self, size: Extent) {
        self.size = size;
        self.view.set_size(size);
        #[cfg(target_os = "macos")]
        if let Some(ref win) = self.macos_window {
            win.set_size(size);
        }
        #[cfg(target_os = "windows")]
        if let Some(ref win) = self.windows_window {
            win.set_size(size);
        }
        #[cfg(target_os = "linux")]
        if let Some(ref win) = self.linux_window {
            win.set_size(size);
        }
    }

    /// Returns the window position.
    pub fn position(&self) -> WindowPosition {
        self.position
    }

    /// Sets the window position.
    pub fn set_position(&mut self, pos: WindowPosition) {
        self.position = pos;
    }

    /// Returns a reference to the view.
    pub fn view(&self) -> &View {
        &self.view
    }

    /// Returns a mutable reference to the view.
    pub fn view_mut(&mut self) -> &mut View {
        &mut self.view
    }

    /// Sets the window content.
    pub fn set_content(&mut self, content: ElementPtr) {
        self.view.set_content(content.clone());
        #[cfg(target_os = "macos")]
        if let Some(ref win) = self.macos_window {
            win.set_content(content.clone());
        }
        #[cfg(target_os = "windows")]
        if let Some(ref win) = self.windows_window {
            win.set_content(content.clone());
        }
        #[cfg(target_os = "linux")]
        if let Some(ref win) = self.linux_window {
            win.set_content(content);
        }
    }

    /// Calls `callback` whenever this window becomes the key (frontmost)
    /// window. macOS-only for now (a silent no-op elsewhere) -- see
    /// `MacOSWindow::on_focus`.
    pub fn on_focus(&self, callback: impl Fn() + 'static) {
        #[cfg(target_os = "macos")]
        if let Some(ref win) = self.macos_window {
            win.on_focus(callback);
        }
        #[cfg(not(target_os = "macos"))]
        let _ = callback;
    }

    /// Shows the window.
    pub fn show(&mut self) {
        #[cfg(target_os = "macos")]
        if let Some(ref win) = self.macos_window {
            win.show();
        }
        #[cfg(target_os = "windows")]
        if let Some(ref win) = self.windows_window {
            win.show();
        }
        #[cfg(target_os = "linux")]
        if let Some(ref win) = self.linux_window {
            win.show();
        }
    }

    /// Hides the window.
    pub fn hide(&mut self) {
        #[cfg(target_os = "macos")]
        if let Some(ref win) = self.macos_window {
            win.hide();
        }
        #[cfg(target_os = "windows")]
        if let Some(ref win) = self.windows_window {
            win.hide();
        }
        #[cfg(target_os = "linux")]
        if let Some(ref win) = self.linux_window {
            win.hide();
        }
    }

    /// Closes the window.
    pub fn close(&mut self) {
        #[cfg(target_os = "macos")]
        if let Some(ref win) = self.macos_window {
            win.close();
        }
        #[cfg(target_os = "windows")]
        if let Some(ref win) = self.windows_window {
            win.close();
        }
        #[cfg(target_os = "linux")]
        if let Some(ref win) = self.linux_window {
            win.close();
        }
    }

    /// Returns whether the window is visible.
    pub fn is_visible(&self) -> bool {
        true // Placeholder
    }

    /// Triggers a refresh of the window.
    pub fn refresh(&self) {
        self.view.refresh();
        // `View::refresh` above is a platform-agnostic no-op stub; the
        // macOS backend's actual `setNeedsDisplay` call lives on
        // `MacOSWindow` instead, same as every other method here that
        // forwards to it. Without this, nothing calling `Window::refresh`
        // (e.g. a timer callback updating a widget's text outside of any
        // mouse/key event) ever produced a visible repaint -- confirmed by
        // running the `timer` example and observing the status bar's text
        // freeze after whatever the first incidental repaint happened to
        // catch.
        #[cfg(target_os = "macos")]
        if let Some(ref win) = self.macos_window {
            win.refresh();
        }
        #[cfg(target_os = "windows")]
        if let Some(ref win) = self.windows_window {
            win.refresh();
        }
        #[cfg(target_os = "linux")]
        if let Some(ref win) = self.linux_window {
            win.refresh();
        }
    }

    /// Returns the platform native window handle (macOS: `NSWindow*`,
    /// Windows: `HWND`, Linux: X11 window ID), for embedding
    /// externally-managed content into the window instead of using
    /// mkgraphic's own element tree for it.
    pub fn handle(&self) -> Option<WindowHandle> {
        #[cfg(target_os = "macos")]
        {
            self.macos_window
                .as_ref()
                .map(|window| window.native_window_handle())
        }
        #[cfg(target_os = "windows")]
        {
            self.windows_window
                .as_ref()
                .map(|window| window.native_window_handle())
        }
        #[cfg(target_os = "linux")]
        {
            self.linux_window
                .as_ref()
                .map(|window| window.native_window_handle())
        }
        #[cfg(not(any(target_os = "macos", target_os = "windows", target_os = "linux")))]
        {
            self.handle
        }
    }
}

/// What happens when the app's window is closed (the red button, not
/// `Window::hide`/`App::stop`).
///
/// Neither behavior was previously available at all: closing the window
/// left the app running with no window and no way to get one back (the
/// default AppKit behavior for an app with no delegate), which looked
/// exactly like a hung/broken app from the Dock -- clicking its icon did
/// nothing since there was nothing telling AppKit how to respond.
pub enum CloseBehavior {
    /// Quit the whole app, matching a typical single-window utility.
    QuitApp,
    /// Keep the app running with no visible windows. When the OS asks the
    /// app to "reopen" with none visible (e.g. the user clicks its Dock
    /// icon), `rebuild` is called to construct a fresh window, which the
    /// app then shows and keeps alive for as long as it keeps running.
    KeepRunning(Box<dyn Fn() -> Window>),
}

/// The application.
pub struct App {
    running: bool,
    #[cfg(target_os = "macos")]
    macos_app: Option<MacOSApp>,
    #[cfg(target_os = "windows")]
    windows_app: Option<WindowsApp>,
    #[cfg(target_os = "linux")]
    linux_app: Option<LinuxApp>,
}

impl App {
    /// Creates a new application.
    pub fn new() -> Self {
        #[cfg(target_os = "macos")]
        {
            Self {
                running: false,
                macos_app: MacOSApp::new(),
            }
        }
        #[cfg(target_os = "windows")]
        {
            Self {
                running: false,
                windows_app: WindowsApp::new(),
            }
        }
        #[cfg(target_os = "linux")]
        {
            Self {
                running: false,
                linux_app: LinuxApp::new(),
            }
        }
        #[cfg(not(any(target_os = "macos", target_os = "windows", target_os = "linux")))]
        {
            Self { running: false }
        }
    }

    /// Runs the application event loop.
    pub fn run(&mut self) {
        self.running = true;
        #[cfg(target_os = "macos")]
        {
            if let Some(ref app) = self.macos_app {
                app.run();
            }
        }
        #[cfg(target_os = "windows")]
        {
            if let Some(ref app) = self.windows_app {
                app.run();
            }
        }
        #[cfg(target_os = "linux")]
        {
            if let Some(ref mut app) = self.linux_app {
                app.run();
            }
        }
    }

    /// Stops the application.
    pub fn stop(&mut self) {
        self.running = false;
        #[cfg(target_os = "macos")]
        {
            if let Some(ref app) = self.macos_app {
                app.stop();
            }
        }
        #[cfg(target_os = "windows")]
        {
            if let Some(ref app) = self.windows_app {
                app.stop();
            }
        }
        #[cfg(target_os = "linux")]
        {
            if let Some(ref mut app) = self.linux_app {
                app.stop();
            }
        }
    }

    /// Returns whether the application is running.
    pub fn is_running(&self) -> bool {
        self.running
    }

    /// Returns the main thread marker (macOS only).
    #[cfg(target_os = "macos")]
    pub fn main_thread_marker(&self) -> Option<MainThreadMarker> {
        MainThreadMarker::new()
    }

    /// Configures what happens when the app's window is closed (see
    /// [`CloseBehavior`]). Call before [`Self::run`].
    ///
    /// Covers macOS, Windows, and Linux/X11, but only macOS can honor the
    /// `KeepRunning` closure's rebuild -- it's wired to
    /// `applicationShouldHandleReopen:hasVisibleWindows:`, triggered by
    /// clicking the Dock icon. Windows and Linux have no equivalent native
    /// gesture, so on those platforms `KeepRunning` only suppresses quitting
    /// when the last window closes; the rebuild closure is never invoked.
    #[cfg(any(target_os = "macos", target_os = "windows", target_os = "linux"))]
    pub fn set_close_behavior(&self, behavior: CloseBehavior) {
        #[cfg(target_os = "macos")]
        if let Some(ref app) = self.macos_app {
            app.set_close_behavior(behavior);
        }
        #[cfg(target_os = "windows")]
        if let Some(ref app) = self.windows_app {
            app.set_close_behavior(behavior);
        }
        #[cfg(target_os = "linux")]
        if let Some(ref app) = self.linux_app {
            app.set_close_behavior(behavior);
        }
    }

    /// Schedules `callback` to run repeatedly on the main thread every
    /// `interval_secs` seconds, for as long as the returned [`Timer`] is
    /// kept alive (dropping it stops the callback -- see [`Timer`]'s own
    /// docs). This is mkgraphic's first timer/idle-callback primitive:
    /// previously there was no way for an app to update UI state on a
    /// schedule rather than in direct response to an event the platform
    /// backend was already dispatching (macOS's AppKit backend in
    /// particular only repaints from inside its own mouse/key handlers),
    /// which made e.g. streaming live subprocess output or auto-polling a
    /// language server's diagnostics impossible without blocking the UI
    /// thread until the work finished.
    ///
    /// Covers macOS, Windows, and Linux/X11.
    #[cfg(any(target_os = "macos", target_os = "windows", target_os = "linux"))]
    pub fn schedule_timer(&self, interval_secs: f64, callback: impl FnMut() + 'static) -> Timer {
        #[cfg(target_os = "macos")]
        let inner = self
            .macos_app
            .as_ref()
            .expect("App::new should have created a MacOSApp")
            .schedule_timer(interval_secs, true, callback);
        #[cfg(target_os = "windows")]
        let inner = self
            .windows_app
            .as_ref()
            .expect("App::new should have created a WindowsApp")
            .schedule_timer(interval_secs, true, callback);
        #[cfg(target_os = "linux")]
        let inner = self
            .linux_app
            .as_ref()
            .expect("App::new should have created a LinuxApp")
            .schedule_timer(interval_secs, true, callback);
        Timer { inner }
    }

    /// Runs `callback` once, the next time the main run loop turns (a
    /// zero-delay, non-repeating timer -- the "idle callback" half of this
    /// primitive). Unlike [`Self::schedule_timer`], the caller doesn't need
    /// to hold on to anything: the timer invalidates itself immediately
    /// after firing once.
    #[cfg(any(target_os = "macos", target_os = "windows", target_os = "linux"))]
    pub fn schedule_once(&self, callback: impl FnOnce() + 'static) {
        // `schedule_timer` takes `FnMut`; wrap the `FnOnce` in an `Option`
        // so it can be called through a `&mut self` closure while only
        // ever actually running the inner callback the one time it fires
        // (`repeats: false`, so there's no second call to worry about, but
        // `FnMut`'s type still requires something callable more than once
        // in principle).
        let mut callback = Some(callback);
        #[cfg(target_os = "macos")]
        let inner = self
            .macos_app
            .as_ref()
            .expect("App::new should have created a MacOSApp")
            .schedule_timer(0.0, false, move || {
                if let Some(callback) = callback.take() {
                    callback();
                }
            });
        #[cfg(target_os = "windows")]
        let inner = self
            .windows_app
            .as_ref()
            .expect("App::new should have created a WindowsApp")
            .schedule_timer(0.0, false, move || {
                if let Some(callback) = callback.take() {
                    callback();
                }
            });
        #[cfg(target_os = "linux")]
        let inner = self
            .linux_app
            .as_ref()
            .expect("App::new should have created a LinuxApp")
            .schedule_timer(0.0, false, move || {
                if let Some(callback) = callback.take() {
                    callback();
                }
            });
        // Intentionally leaked: a one-shot timer has no handle for the
        // caller to hold, and it invalidates (and the run loop drops its
        // reference to it) right after firing once on its own.
        std::mem::forget(inner);
    }
}

/// A handle to a [`App::schedule_timer`] callback. Dropping this (or
/// calling [`Self::cancel`]) stops future firings -- the timer is not kept
/// alive by anything else once this handle is gone, so letting it drop
/// (e.g. a local variable going out of scope) is a real, if easy to miss,
/// way to stop a timer.
#[cfg(target_os = "macos")]
pub struct Timer {
    inner: objc2::rc::Retained<objc2_foundation::NSTimer>,
}

#[cfg(target_os = "windows")]
pub struct Timer {
    inner: WindowsTimer,
}

#[cfg(target_os = "linux")]
pub struct Timer {
    inner: LinuxTimer,
}

#[cfg(target_os = "macos")]
impl Timer {
    /// Stops future firings. Also happens automatically on drop.
    pub fn cancel(&self) {
        unsafe {
            self.inner.invalidate();
        }
    }
}

#[cfg(target_os = "windows")]
impl Timer {
    /// Stops future firings. Also happens automatically on drop.
    pub fn cancel(&self) {
        self.inner.cancel();
    }
}

#[cfg(target_os = "linux")]
impl Timer {
    /// Stops future firings. Also happens automatically on drop.
    pub fn cancel(&self) {
        self.inner.cancel();
    }
}

#[cfg(any(target_os = "macos", target_os = "windows", target_os = "linux"))]
impl Drop for Timer {
    fn drop(&mut self) {
        self.cancel();
    }
}

impl Default for App {
    fn default() -> Self {
        Self::new()
    }
}

/// Error type for platform operations.
#[derive(Debug, thiserror::Error)]
pub enum PlatformError {
    #[error("Failed to create window: {0}")]
    WindowCreation(String),

    #[error("Failed to initialize application: {0}")]
    Initialization(String),

    #[error("Platform error: {0}")]
    Other(String),
}

/// Result type for platform operations.
pub type PlatformResult<T> = Result<T, PlatformError>;