rightkit-tauri-shell 0.4.0

Shared Tauri desktop shell for Right Suite apps: webview hardening, window state, native menu, tray, single instance, deep links, autostart, rich clipboard, watchdog and engine wiring.
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
//! Window creation and lifecycle helpers: hardened builders, reveal / toggle, secondary windows.
//!
//! Donors: CodeRight `os_shell/windows` (bounded labels and dimensions, app-relative URLs only,
//! lifecycle event), HeardRight `hub_window` (reveal = show + unminimize + focus; macOS needs
//! `app.show()` first), ViewRight (hidden-until-first-paint).

use std::sync::Arc;

use serde::{Deserialize, Serialize};
use tauri::webview::NewWindowResponse;
use tauri::{AppHandle, Emitter, Manager, WebviewUrl, WebviewWindow, WebviewWindowBuilder, Wry};

use crate::lifecycle::{reveal_mode, RevealMode, RevealSource};
use crate::nav::WindowOpenDecision;
use crate::opener::open_checked;
use crate::{ShellState, EVENT_WINDOW};

/// App event announcing initial window placement (`phase` `"begin"` / `"done"`), so a
/// control server can hold viewport requests until placement and state restore have
/// landed instead of racing them. Same name `rightkit-qa-driver` listens on. Announcing
/// never shows, orders or focuses a window.
pub const EVENT_PLACEMENT: &str = "rk-shell:placement";

fn announce_placement(app: &AppHandle<Wry>, label: &str, phase: &str) {
    let _ = app.emit(
        EVENT_PLACEMENT,
        serde_json::json!({"label": label, "phase": phase}),
    );
}

/// Run `place` (window-state restore and any other initial placement) between the
/// `begin` and `done` announcements. `done` is queued on the main thread behind the
/// size and position calls `place` made, so it is not announced before they apply.
pub fn with_placement_announced(app: &AppHandle<Wry>, label: &str, place: impl FnOnce()) {
    announce_placement(app, label, "begin");
    place();
    let (a, l) = (app.clone(), label.to_owned());
    if app
        .run_on_main_thread(move || announce_placement(&a, &l, "done"))
        .is_err()
    {
        announce_placement(app, label, "done");
    }
}

const MIN_WIDTH: f64 = 320.0;
const MIN_HEIGHT: f64 = 240.0;

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct WindowSpec {
    pub label: String,
    pub title: Option<String>,
    /// App-relative path (e.g. `mini.html`); never an absolute or remote URL.
    pub path: Option<String>,
    pub width: Option<f64>,
    pub height: Option<f64>,
    pub focused: Option<bool>,
    /// Always on top (mini windows, pills).
    pub always_on_top: Option<bool>,
    /// Minimum inner width in logical pixels. Default 320 (unchanged); a non-finite or non-positive
    /// value is ignored. The initial width is raised to at least this.
    pub min_width: Option<f64>,
    /// Minimum inner height in logical pixels. Default 240 (unchanged).
    pub min_height: Option<f64>,
    /// Override native decorations after the shell's frameless policy (`Some(false)` for a
    /// borderless pill or onboarding window on a framed shell, `Some(true)` for the reverse).
    pub decorations: Option<bool>,
    /// Centre on the primary/current monitor. Wins over `x` / `y`.
    pub center: Option<bool>,
    /// Open fullscreen.
    pub fullscreen: Option<bool>,
    /// Keep the window out of the taskbar / Dock-switcher where the platform supports it.
    pub skip_taskbar: Option<bool>,
    /// Initial outer position in logical pixels (needs both `x` and `y`). It is corrected to a
    /// visible monitor when it would leave the window off-screen.
    pub x: Option<f64>,
    pub y: Option<f64>,
}

#[derive(Debug, Clone, Serialize)]
pub struct WindowReadback {
    pub visible: bool,
    pub focused: bool,
    pub main: bool,
    pub level: Option<i64>,
}

pub fn safe_label(raw: &str) -> Option<String> {
    let c = raw.trim();
    (!c.is_empty()
        && c.len() <= 80
        && c.chars()
            .all(|ch| ch.is_ascii_alphanumeric() || matches!(ch, '-' | '_')))
    .then(|| c.to_owned())
}

fn app_path(path: Option<&str>) -> String {
    let raw = path.unwrap_or("index.html").trim().trim_start_matches('/');
    if raw.is_empty()
        || raw.contains("..")
        || raw.contains('\\')
        || raw.contains('\0')
        || raw.contains("://")
    {
        "index.html".to_owned()
    } else {
        raw.to_owned()
    }
}

/// The effective minimum inner size of `spec`: its own values, else the shell default.
pub fn spec_min_size(spec: &WindowSpec) -> (f64, f64) {
    let pick = |v: Option<f64>, default: f64| {
        v.filter(|v| v.is_finite() && *v > 0.0)
            .map_or(default, |v| v.min(16_384.0))
    };
    (
        pick(spec.min_width, MIN_WIDTH),
        pick(spec.min_height, MIN_HEIGHT),
    )
}

/// Move a window rectangle (logical pixels) back on-screen. A rectangle whose title strip is
/// reachable on some monitor (at least `CLAMP_MARGIN_X` wide, `CLAMP_MARGIN_Y` tall inside it)
/// is returned unchanged; otherwise it is clamped onto the monitor nearest its centre. No monitors:
/// unchanged.
pub fn correct_offscreen(
    x: f64,
    y: f64,
    width: f64,
    height: f64,
    monitors: &[crate::window_state::MonitorSnapshot],
) -> (f64, f64) {
    use crate::window_state::{CLAMP_MARGIN_X, CLAMP_MARGIN_Y};
    if monitors.is_empty() || !x.is_finite() || !y.is_finite() {
        return match (monitors.first(), x.is_finite() && y.is_finite()) {
            (Some(m), false) => (m.x, m.y),
            _ => (x, y),
        };
    }
    let reachable = |m: &crate::window_state::MonitorSnapshot| {
        x + width > m.x + CLAMP_MARGIN_X
            && x < m.x + m.width - CLAMP_MARGIN_X
            && y >= m.y
            && y < m.y + m.height - CLAMP_MARGIN_Y
    };
    if monitors.iter().any(reachable) {
        return (x, y);
    }
    let (cx, cy) = (x + width / 2.0, y + height / 2.0);
    let target = monitors
        .iter()
        .min_by(|a, b| {
            let d = |m: &crate::window_state::MonitorSnapshot| {
                (m.x + m.width / 2.0 - cx).powi(2) + (m.y + m.height / 2.0 - cy).powi(2)
            };
            d(a).total_cmp(&d(b))
        })
        .expect("non-empty monitors");
    let min_x = target.x - (width - CLAMP_MARGIN_X).max(0.0);
    let max_x = target.x + target.width - CLAMP_MARGIN_X;
    let max_y = target.y + target.height - CLAMP_MARGIN_Y;
    (
        if min_x <= max_x {
            x.clamp(min_x, max_x)
        } else {
            target.x
        },
        if target.y <= max_y {
            y.clamp(target.y, max_y)
        } else {
            target.y
        },
    )
}

fn dim(v: Option<f64>, default: f64, min: f64) -> f64 {
    v.filter(|v| v.is_finite() && *v > 0.0)
        .unwrap_or(default)
        .max(min)
}

/// A `WebviewWindowBuilder` carrying the shell policy: popup handling through [`crate::nav`],
/// frameless chrome when the shell was configured for it, hidden until restored/shown.
/// Navigation, init scripts and native hardening come from the shell plugin for every webview.
pub fn builder<'a>(
    app: &'a AppHandle<Wry>,
    label: &str,
    url: WebviewUrl,
) -> WebviewWindowBuilder<'a, Wry, AppHandle<Wry>> {
    let state = app.state::<ShellState>();
    let nav = Arc::clone(&state.nav);
    let opener = Arc::clone(&state.opener);
    let (opener_app, opener_label) = (app.clone(), label.to_owned());
    let b = WebviewWindowBuilder::new(app, label, url)
        .visible(false)
        .on_new_window(move |url, features| {
            // The opening page: this window's current URL. Unknown (the window is not registered yet)
            // defers to the origin allow-list.
            let from = opener_app
                .get_webview_window(&opener_label)
                .and_then(|w| w.url().ok());
            match nav.decide_window_open(&url, features.size().is_some(), from.as_ref()) {
                WindowOpenDecision::External { url } => {
                    let _ = open_checked(opener.as_ref(), &url);
                    NewWindowResponse::Deny
                }
                WindowOpenDecision::Popup => NewWindowResponse::Allow,
                WindowOpenDecision::Deny => NewWindowResponse::Deny,
            }
        });
    // A never-show host's windows are never created focused.
    let b = if crate::lifecycle::never_show(app) {
        b.focused(false)
    } else {
        b
    };
    crate::frameless::style(b, state.frameless)
}

/// Create (or reveal) a secondary window described by `spec`.
pub fn open(app: &AppHandle<Wry>, spec: &WindowSpec) -> Result<String, String> {
    let label = safe_label(&spec.label).ok_or("invalid window label")?;
    if let Some(w) = app.get_webview_window(&label) {
        reveal_with(app, Some(&label), RevealSource::OpenWindow);
        return Ok(w.label().to_owned());
    }
    let title = spec
        .title
        .as_deref()
        .map(str::trim)
        .filter(|t| !t.is_empty())
        .unwrap_or(&app.state::<ShellState>().app_name)
        .to_owned();
    let focused = reveal_mode(app, RevealSource::OpenWindow) == RevealMode::Foreground
        && spec.focused.unwrap_or(true);
    let (min_w, min_h) = spec_min_size(spec);
    let (width, height) = (
        dim(spec.width, 900.0, min_w),
        dim(spec.height, 640.0, min_h),
    );
    let mut b = builder(
        app,
        &label,
        WebviewUrl::App(app_path(spec.path.as_deref()).into()),
    )
    .title(title)
    .inner_size(width, height)
    .min_inner_size(min_w, min_h)
    .always_on_top(spec.always_on_top.unwrap_or(false))
    .focused(focused);
    if let Some(d) = spec.decorations {
        b = b.decorations(d);
    }
    if let Some(f) = spec.fullscreen {
        b = b.fullscreen(f);
    }
    if let Some(s) = spec.skip_taskbar {
        b = b.skip_taskbar(s);
    }
    if spec.center == Some(true) {
        b = b.center();
    } else if let (Some(x), Some(y)) = (spec.x, spec.y) {
        let monitors: Vec<_> = app
            .available_monitors()
            .unwrap_or_default()
            .iter()
            .map(crate::window_state::MonitorSnapshot::from_monitor)
            .collect();
        let (x, y) = correct_offscreen(x, y, width, height, &monitors);
        b = b.position(x, y);
    }
    let window = b
        .build()
        .map_err(|e| format!("create window {label}: {e}"))?;
    let _ = app.emit(
        EVENT_WINDOW,
        serde_json::json!({"label": label, "kind": "created"}),
    );
    show_window(
        app,
        &window,
        RevealSource::OpenWindow,
        RevealStyle::ShowOnly,
    )?;
    Ok(label)
}

/// The window calls one reveal makes, so every path is testable (and recordable) without a window.
pub trait RevealTarget {
    /// Before a foreground reveal of the main window: back to a Regular app, run the host's
    /// visibility callback.
    fn prepare(&mut self);
    /// macOS `app.show()`.
    fn app_show(&mut self);
    fn unminimize(&mut self) -> Result<(), String>;
    fn show(&mut self) -> Result<(), String>;
    fn focus(&mut self) -> Result<(), String>;
    /// QA background: native order-back without activation.
    fn order_back(&mut self) -> Result<(), String>;
}

/// Which calls a foreground reveal makes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RevealStyle {
    /// prepare, app show, unminimise, show, focus (errors ignored): `reveal`, tray, reopen.
    Full,
    /// prepare, show, focus (errors returned): the `rk_shell_window` `show` command.
    ShowFocus,
    /// show only (errors returned): show-on-ready and a newly opened window.
    ShowOnly,
}

/// Do exactly what `mode` allows. `Ok(true)` when the window was brought up, `Ok(false)` when
/// nothing was (forbidden, or a `Full` order-back that failed). `Forbidden` makes no call at all.
pub fn apply_reveal<T: RevealTarget>(
    mode: RevealMode,
    style: RevealStyle,
    target: &mut T,
) -> Result<bool, String> {
    match mode {
        RevealMode::Forbidden => Ok(false),
        RevealMode::Background => match target.order_back() {
            Ok(()) => Ok(true),
            Err(_) if style == RevealStyle::Full => Ok(false),
            Err(e) => Err(e),
        },
        RevealMode::Foreground => {
            match style {
                RevealStyle::Full => {
                    target.prepare();
                    target.app_show();
                    let _ = target.unminimize();
                    let _ = target.show();
                    let _ = target.focus();
                }
                RevealStyle::ShowFocus => {
                    target.prepare();
                    target.show()?;
                    target.focus()?;
                }
                RevealStyle::ShowOnly => target.show()?,
            }
            Ok(true)
        }
    }
}

struct WindowReveal<'a> {
    app: &'a AppHandle<Wry>,
    w: &'a WebviewWindow<Wry>,
}

impl RevealTarget for WindowReveal<'_> {
    fn prepare(&mut self) {
        // Back to a Regular app first (a hide-to-background host is an Accessory app while
        // hidden), so the activation below can bring a Dock icon and menu bar with it.
        if self.w.label() == self.app.state::<ShellState>().main_label {
            crate::lifecycle::note_visibility(self.app, crate::lifecycle::Visibility::Revealed);
        }
    }
    fn app_show(&mut self) {
        #[cfg(target_os = "macos")]
        let _ = self.app.show();
    }
    fn unminimize(&mut self) -> Result<(), String> {
        self.w.unminimize().map_err(|e| e.to_string())
    }
    fn show(&mut self) -> Result<(), String> {
        self.w.show().map_err(|e| e.to_string())
    }
    fn focus(&mut self) -> Result<(), String> {
        self.w.set_focus().map_err(|e| e.to_string())
    }
    fn order_back(&mut self) -> Result<(), String> {
        // Native AppKit ordering must run on the Tauri main thread. Window commands
        // arrive on rightkit-daemon connection threads; dispatch synchronously there
        // so errors are returned to the caller after WindowServer applies the order.
        #[cfg(target_os = "macos")]
        {
            dispatch_native(self.w, order_back_native)
        }
        #[cfg(not(target_os = "macos"))]
        {
            Err("background native ordering is unimplemented on this platform".into())
        }
    }
}

/// Bring `w` up as the guard allows for `source`. The only function that touches a window for a
/// reveal; every caller reaches it through [`crate::lifecycle::reveal_mode`].
pub(crate) fn show_window(
    app: &AppHandle<Wry>,
    w: &WebviewWindow<Wry>,
    source: RevealSource,
    style: RevealStyle,
) -> Result<bool, String> {
    let mode = reveal_mode(app, source);
    apply_reveal(mode, style, &mut WindowReveal { app, w })
}

fn reveal_window(app: &AppHandle<Wry>, w: &WebviewWindow<Wry>, source: RevealSource) {
    let shown = show_window(app, w, source, RevealStyle::Full).unwrap_or(false);
    if shown && w.label() == app.state::<ShellState>().main_label {
        crate::idle::note_visible(app);
    }
}

#[cfg(target_os = "macos")]
pub(crate) fn dispatch_native<T, F>(w: &WebviewWindow<Wry>, f: F) -> Result<T, String>
where
    T: Send + 'static,
    F: FnOnce(&WebviewWindow<Wry>) -> Result<T, String> + Send + 'static,
{
    let Some(state) = w.app_handle().try_state::<ShellState>() else {
        return Err("shell state unavailable for native dispatch".into());
    };
    if state.exiting.load(std::sync::atomic::Ordering::Acquire) {
        return Err("native dispatch rejected during shutdown".into());
    }
    if std::thread::current().id() == state.main_thread_id {
        return f(w);
    }
    let (tx, rx) = std::sync::mpsc::sync_channel(1);
    let cancelled = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
    let cancelled_task = std::sync::Arc::clone(&cancelled);
    let app = w.app_handle().clone();
    let window = w.clone();
    w.run_on_main_thread(move || {
        if cancelled_task.load(std::sync::atomic::Ordering::Acquire) {
            let _ = tx.send(Err("native dispatch cancelled".into()));
            return;
        }
        let Some(state) = app.try_state::<ShellState>() else {
            let _ = tx.send(Err("shell state unavailable for native dispatch".into()));
            return;
        };
        if state.exiting.load(std::sync::atomic::Ordering::Acquire) {
            let _ = tx.send(Err("native dispatch rejected during shutdown".into()));
            return;
        }
        let _ = tx.send(f(&window));
    })
    .map_err(|e| e.to_string())?;
    match rx.recv_timeout(std::time::Duration::from_secs(5)) {
        Ok(result) => result,
        Err(e) => {
            cancelled.store(true, std::sync::atomic::Ordering::Release);
            Err(format!("main-thread native dispatch: {e}"))
        }
    }
}

// Dispatched to the main thread only on macOS.
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
fn order_back_native(w: &WebviewWindow<Wry>) -> Result<(), String> {
    #[cfg(target_os = "macos")]
    {
        use objc2_app_kit::NSWindow;
        let ptr = w.ns_window().map_err(|e| e.to_string())?;
        if ptr.is_null() {
            return Err("native window handle unavailable".into());
        }
        // SAFETY: Tauri returns the live NSWindow for this window; used synchronously.
        let native = unsafe { &*(ptr as *const NSWindow) };
        // Keep QA windows below normal user windows even if AppKit reorders them later.
        native.setLevel(-1);
        native.orderBack(None);
        Ok(())
    }
    #[cfg(not(target_os = "macos"))]
    {
        let _ = w;
        Err("background native ordering is unimplemented on this platform".into())
    }
}

/// Read native window visibility/order after a show or order operation. macOS values
/// come from NSWindow, so Tauri's logical `is_visible` cannot mask a failed native order.
pub fn readback(w: &WebviewWindow<Wry>) -> Result<WindowReadback, String> {
    #[cfg(target_os = "macos")]
    {
        dispatch_native(w, |w| {
            use objc2_app_kit::NSWindow;
            let ptr = w.ns_window().map_err(|e| e.to_string())?;
            if ptr.is_null() {
                return Err("native window handle unavailable".into());
            }
            // SAFETY: Tauri returns the live NSWindow for this window; used synchronously.
            let native = unsafe { &*(ptr as *const NSWindow) };
            Ok(WindowReadback {
                visible: native.isVisible(),
                focused: native.isKeyWindow(),
                main: native.isMainWindow(),
                level: Some(native.level() as i64),
            })
        })
    }
    #[cfg(not(target_os = "macos"))]
    Ok(WindowReadback {
        visible: w.is_visible().unwrap_or(false),
        focused: w.is_focused().unwrap_or(false),
        main: false,
        level: None,
    })
}

/// Show + unminimize + focus, as the host's visibility policy allows (never-show makes this a
/// no-op). `None` targets the main window.
pub fn reveal(app: &AppHandle<Wry>, label: Option<&str>) {
    reveal_with(app, label, RevealSource::Api);
}

/// [`reveal`] naming why, for the guard.
pub fn reveal_with(app: &AppHandle<Wry>, label: Option<&str>, source: RevealSource) {
    let main = app.state::<ShellState>().main_label.clone();
    let label = label.unwrap_or(&main);
    if let Some(w) = app.get_webview_window(label) {
        reveal_window(app, &w, source);
    }
}

/// Hide when visible and focused-or-visible, otherwise reveal (tray left-click behaviour).
pub fn toggle(app: &AppHandle<Wry>, label: &str) {
    if let Some(w) = app.get_webview_window(label) {
        if w.is_visible().unwrap_or(false) && w.is_focused().unwrap_or(false) {
            let _ = w.hide();
            if w.label() == app.state::<ShellState>().main_label {
                crate::idle::note_hidden(app, false);
                crate::lifecycle::note_visibility(app, crate::lifecycle::Visibility::Hidden);
            }
        } else {
            reveal_window(app, &w, RevealSource::Tray);
        }
    }
}