ledgeline-shell 0.4.0

The desktop and local-server shell shared by Ledgeline's apps: access token and Host guard, CSP, embedded SPA serving, app directories, recents, and the wry/tao GUI boot pieces.
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
//! Windows glue for the window and its WebView2: where WebView2 keeps the
//! app's profile, the menu's keyboard shortcuts, the frame half of the
//! navigation policy, and what to say when there is no WebView2 at all.
//!
//! Nobody working on this has a Windows machine: everything below follows
//! wry 0.57's, tao 0.37's, muda 0.21's and webview2-com 0.39's source and
//! Microsoft's WebView2 reference, and is checked by cross-compiling. The
//! pure parts are unit-tested on every platform (which is why this module
//! also builds under `test`); the rest needs a real Windows box.
//!
//! # The menu's shortcuts
//!
//! muda builds a Win32 accelerator table for the menu bar, but a table does
//! nothing until the message loop calls `TranslateAcceleratorW`, and the page
//! never even gets that far: WebView2 runs the page in its own browser
//! process, so a key pressed with the page focused never reaches this
//! process's message queue. WebView2 offers the host such a key (any chord
//! with Ctrl or Alt, Esc, a function key) through the controller's
//! `AcceleratorKeyPressed` event BEFORE the page sees it; that is the route
//! [`route_menu_keys`] takes. The message-loop hook ([`msg_hook`]) covers the
//! rarer case of a key sent to our own window (wry hands focus straight back
//! to the page whenever the window is activated).
//!
//! Both routes ask the menu's own table ([`translate`]), so the menu decides
//! which chords are its own and a chord it does not bind is left to the page
//! untouched — the same contract as Linux's [`super::linux_shortcut_for`],
//! without a second copy of the bindings. A hit arrives as an ordinary menu
//! event (muda's `WM_COMMAND` handler), so each action still has exactly one
//! implementation in the app.
//!
//! The editing chords are kept away from the table ([`menu_may_take`]):
//! muda's Cut/Copy/Paste/Select All/Undo/Redo items carry Ctrl+X/C/V/A/Z/Y
//! accelerators and perform themselves by SYNTHESISING that very key press
//! (`SendInput`), which would come straight back through the same route and
//! fire again, endlessly. WebView2 edits on those keys by itself; browser
//! accelerator keys being off does not touch them (Microsoft's
//! `AreBrowserAcceleratorKeysEnabled` reference: "accelerator keys related to
//! movement and text editing" stay on).

use std::cell::Cell;
use std::path::PathBuf;

use crate::{AppDirs, AppIdentity};

/// Virtual-key codes of the editing chords muda's predefined Edit items
/// bind: Ctrl+ A, C, V, X, Y (Redo on Windows), Z. A letter's virtual-key
/// code is its upper-case ASCII value.
const EDIT_KEYS: [u32; 6] = [
    b'A' as u32,
    b'C' as u32,
    b'V' as u32,
    b'X' as u32,
    b'Y' as u32,
    b'Z' as u32,
];

/// Whether a key may be offered to the menu's accelerator table at all. Every
/// key but the editing ones (see the module docs for the loop they would
/// start). Modifiers are not looked at: the table matches them exactly, and
/// an editing key is unsafe with any of them.
#[must_use]
pub(super) fn menu_may_take(virtual_key: u32) -> bool {
    !EDIT_KEYS.contains(&virtual_key)
}

/// The folder WebView2 keeps an app's profile in (cookies, localStorage, the
/// HTTP cache, its crash dumps): `<cache dir>\webview2\<app>`, which on
/// Windows is `%LOCALAPPDATA%\ledgeline\webview2\<app>`. The temp dir stands
/// in for a missing cache dir.
///
/// Without one WebView2 writes `<exe name>.WebView2` beside the executable,
/// which fails, and with it the whole window, wherever the user may not write
/// (a per-machine install under Program Files), and elsewhere leaves state in
/// the install folder that an uninstall does not remove. Per app, because the
/// two apps are separate processes that would otherwise share one browser
/// process and one profile.
#[must_use]
pub(super) fn webview_data_dir(app: &AppIdentity, dirs: &AppDirs) -> PathBuf {
    dirs.cache_dir
        .as_ref()
        .unwrap_or(&dirs.temp_dir)
        .join("webview2")
        .join(app.log_prefix)
}

/// Which key went down last through the page's route and was taken by the
/// menu, so its auto-repeats can be swallowed too.
///
/// A held chord repeats its key-down. Firing on each repeat would open a file
/// picker per repeat for a held Ctrl+O; handing the repeats to the page would
/// give it a stray key-down for a chord it never saw start. So the first
/// press fires (or not) and every repeat of a press that fired is swallowed
/// without firing, the way Microsoft's WebView2 sample handles its own
/// shortcuts.
#[derive(Debug, Default)]
pub(super) struct HeldChord(Cell<Option<u32>>);

impl HeldChord {
    /// A key-down for `virtual_key`; `repeat` when it is an auto-repeat.
    /// `fire` offers a fresh press to the menu and answers whether the menu
    /// took it. Answers whether the page should be kept from seeing the key.
    pub(super) fn key_down(
        &self,
        virtual_key: u32,
        repeat: bool,
        fire: impl FnOnce() -> bool,
    ) -> bool {
        if repeat {
            return self.0.get() == Some(virtual_key);
        }
        let taken = fire();
        self.0.set(taken.then_some(virtual_key));
        taken
    }
}

#[cfg(target_os = "windows")]
pub(super) use platform::*;

#[cfg(target_os = "windows")]
mod platform {
    use std::cell::RefCell;
    use std::rc::Rc;

    use muda::Menu;
    use tao::window::Window;
    use webview2_com::Microsoft::Web::WebView2::Win32::{
        COREWEBVIEW2_KEY_EVENT_KIND, COREWEBVIEW2_KEY_EVENT_KIND_KEY_DOWN,
        COREWEBVIEW2_KEY_EVENT_KIND_SYSTEM_KEY_DOWN, COREWEBVIEW2_PHYSICAL_KEY_STATUS,
        ICoreWebView2AcceleratorKeyPressedEventArgs, ICoreWebView2NavigationStartingEventArgs,
    };
    use webview2_com::{
        AcceleratorKeyPressedEventHandler, NavigationStartingEventHandler, take_pwstr,
    };
    use windows_core::PWSTR;
    use windows_sys::Win32::Foundation::HWND;
    use windows_sys::Win32::UI::WindowsAndMessaging::{
        GA_ROOT, GetAncestor, HACCEL, MSG, TranslateAcceleratorW, WM_KEYDOWN, WM_SYSKEYDOWN,
    };
    use wry::WebViewExtWindows as _;

    use super::{HeldChord, menu_may_take};
    use crate::{AppDirs, AppIdentity};

    thread_local! {
        /// The app's window (its `HWND`) and the menu bar installed in it:
        /// what both keyboard routes translate against. Set by
        /// [`set_menu_target`] once the window exists.
        ///
        /// A thread-local rather than something threaded through, because
        /// the message-loop hook has to be handed to tao when the event loop
        /// is BUILT ([`super::super::build_event_loop`]), which is before
        /// either the menu or the window exists, and there is one window per
        /// process, on the main thread. A `Menu` is an `Rc` handle, so
        /// holding a clone here keeps nothing alive that the app does not.
        static MENU_TARGET: RefCell<Option<(isize, Menu)>> = const { RefCell::new(None) };
    }

    /// Record `window` and `menu` as the target of the menu's shortcuts.
    pub(in crate::gui) fn set_menu_target(window: &Window, menu: &Menu) {
        use tao::platform::windows::WindowExtWindows as _;
        MENU_TARGET.with_borrow_mut(|target| *target = Some((window.hwnd(), menu.clone())));
    }

    /// The window and its menu's current accelerator table. Read fresh each
    /// time: muda rebuilds the table (a new `HACCEL`) whenever an item with
    /// an accelerator is added or removed. `None` before the window exists
    /// or when nothing in the menu has an accelerator.
    fn menu_target() -> Option<(HWND, HACCEL)> {
        MENU_TARGET.with_borrow(|target| {
            target
                .as_ref()
                .map(|(hwnd, menu)| (*hwnd as HWND, menu.haccel() as HACCEL))
                .filter(|(_, haccel)| !haccel.is_null())
        })
    }

    /// Offer a key-down to the menu's accelerator table, as if it had been
    /// sent to the window. Answers whether the table had it, in which case
    /// muda has already raised the item's menu event.
    ///
    /// Outside the thread-local's borrow on purpose: a hit sends
    /// `WM_COMMAND` synchronously, and nothing that handler reaches should
    /// find the cell borrowed.
    fn translate(message: u32, virtual_key: u32, lparam: isize) -> bool {
        let Some((hwnd, haccel)) = menu_target() else {
            return false;
        };
        let msg = MSG {
            hwnd,
            message,
            wParam: virtual_key as usize,
            lParam: lparam,
            ..MSG::default()
        };
        // SAFETY: `hwnd` is the live top-level window (it outlives the event
        // loop that calls this), `haccel` is the menu's current table
        // (non-null, valid as long as the menu, which the thread-local
        // holds), and `msg` is a fully initialised MSG on the stack.
        unsafe { TranslateAcceleratorW(hwnd, haccel, &msg) != 0 }
    }

    /// tao's message-loop hook ([`tao::platform::windows::EventLoopBuilderExtWindows::with_msg_hook`]):
    /// a key-down sent to our window or a child of it goes through the
    /// menu's accelerator table first, as a Win32 message loop does. `true`
    /// (the table had it) keeps tao from dispatching the message as well.
    pub(in crate::gui) fn msg_hook(msg: *const std::ffi::c_void) -> bool {
        // SAFETY: tao calls the hook with a pointer to the MSG it has just
        // taken from `GetMessageW`, valid for the duration of the call; the
        // windows crate's MSG it points to has the same `repr(C)` layout as
        // windows-sys's.
        let msg = unsafe { &*msg.cast::<MSG>() };
        if !matches!(msg.message, WM_KEYDOWN | WM_SYSKEYDOWN) || !menu_may_take(msg.wParam as u32) {
            return false;
        }
        let Some((window, _)) = menu_target() else {
            return false;
        };
        // SAFETY: `GetAncestor` takes any window handle, including one that
        // has since been destroyed (it then answers null).
        let ours = unsafe { GetAncestor(msg.hwnd, GA_ROOT) } == window;
        ours && translate(msg.message, msg.wParam as u32, msg.lParam)
    }

    /// The page's route to the menu's shortcuts: WebView2's
    /// `AcceleratorKeyPressed`, raised on this thread before the page sees
    /// the key. A chord the menu takes is marked handled, so neither the
    /// page nor the browser acts on it too.
    ///
    /// Alt chords arrive as "system" key-downs (`WM_SYSKEYDOWN`), which is
    /// what an Alt accelerator matches. `TranslateAcceleratorW` reads Ctrl
    /// and Shift from this thread's key state; Microsoft's WebView2 sample
    /// reads the same state (`GetKeyState`) in this same event.
    ///
    /// # Errors
    /// When the handler cannot be registered.
    pub(in crate::gui) fn route_menu_keys(webview: &wry::WebView) -> windows_core::Result<()> {
        let held = HeldChord::default();
        let handler = AcceleratorKeyPressedEventHandler::create(Box::new(move |_, args| {
            let Some(args) = args else {
                return Ok(());
            };
            let key = read_key(&args)?;
            let message = match key.kind {
                COREWEBVIEW2_KEY_EVENT_KIND_KEY_DOWN => WM_KEYDOWN,
                COREWEBVIEW2_KEY_EVENT_KIND_SYSTEM_KEY_DOWN => WM_SYSKEYDOWN,
                _ => return Ok(()),
            };
            let taken = held.key_down(key.virtual_key, key.repeat, || {
                menu_may_take(key.virtual_key)
                    && translate(message, key.virtual_key, key.lparam as isize)
            });
            if taken {
                // SAFETY: the event's own arguments, on the UI thread, during
                // the event.
                unsafe { args.SetHandled(true)? };
            }
            Ok(())
        }));
        let mut token = 0_i64;
        // SAFETY: the controller is the live one wry created for this view,
        // used on the UI thread it was created on; WebView2 keeps its own
        // reference to the handler for the life of the view, and `token` is a
        // valid out-parameter.
        unsafe {
            webview
                .controller()
                .add_AcceleratorKeyPressed(&handler, &mut token)
        }
    }

    /// One `AcceleratorKeyPressed` event, read out.
    struct KeyEvent {
        kind: COREWEBVIEW2_KEY_EVENT_KIND,
        virtual_key: u32,
        lparam: i32,
        repeat: bool,
    }

    fn read_key(
        args: &ICoreWebView2AcceleratorKeyPressedEventArgs,
    ) -> windows_core::Result<KeyEvent> {
        let mut kind = COREWEBVIEW2_KEY_EVENT_KIND::default();
        let mut virtual_key = 0_u32;
        let mut lparam = 0_i32;
        let mut status = COREWEBVIEW2_PHYSICAL_KEY_STATUS::default();
        // SAFETY: the event's own arguments, on the UI thread, during the
        // event; every out-parameter is a valid, initialised local.
        unsafe {
            args.KeyEventKind(&mut kind)?;
            args.VirtualKey(&mut virtual_key)?;
            args.KeyEventLParam(&mut lparam)?;
            args.PhysicalKeyStatus(&mut status)?;
        }
        Ok(KeyEvent {
            kind,
            virtual_key,
            lparam,
            repeat: status.WasKeyDown.as_bool(),
        })
    }

    /// The frame half of the navigation policy. wry registers WebView2's
    /// `NavigationStarting`, which is the MAIN frame's only; a frame's own
    /// navigations raise `FrameNavigationStarting` instead, which wry leaves
    /// alone, so without this a frame (the invoicer's MBR notes and invoice
    /// pages) could go anywhere. `allowed` is the same decision the main
    /// frame's handler makes (our origin only, outside links and hand-offs
    /// offered to the user's default app), and a refused navigation is
    /// cancelled. A URL that cannot be read is refused too.
    ///
    /// # Errors
    /// When the handler cannot be registered; the caller must not show a
    /// webview whose frames are unpoliced.
    pub(in crate::gui) fn police_frames(
        webview: &wry::WebView,
        allowed: Rc<dyn Fn(&str) -> bool>,
    ) -> windows_core::Result<()> {
        let handler = NavigationStartingEventHandler::create(Box::new(move |_, args| {
            let Some(args) = args else {
                return Ok(());
            };
            let allow = navigation_uri(&args).is_ok_and(|uri| allowed(&uri));
            // SAFETY: the event's own arguments, on the UI thread, during
            // the event.
            unsafe { args.SetCancel(!allow) }
        }));
        let mut token = 0_i64;
        // SAFETY: the view wry created, on the UI thread it was created on;
        // registered before the event loop runs, so before any frame exists;
        // WebView2 keeps its own reference to the handler, and `token` is a
        // valid out-parameter.
        unsafe {
            webview
                .webview()
                .add_FrameNavigationStarting(&handler, &mut token)
        }
    }

    fn navigation_uri(
        args: &ICoreWebView2NavigationStartingEventArgs,
    ) -> windows_core::Result<String> {
        let mut uri = PWSTR::null();
        // SAFETY: the event's own arguments, during the event; `Uri` fills a
        // `CoTaskMemAlloc`ed string, which `take_pwstr` copies and frees.
        unsafe { args.Uri(&mut uri)? };
        Ok(take_pwstr(uri))
    }

    /// A [`wry::WebContext`] whose data directory is the app's own
    /// ([`super::webview_data_dir`]), created if need be. `None` (WebView2's
    /// default folder, beside the executable) when it cannot be created.
    ///
    /// Leaked, deliberately: the webview must not outlive its context (wry's
    /// `WebContext` docs), and the one webview lives as long as the process.
    /// On Windows wry only reads the folder while it creates the WebView2
    /// environment, so the leak is a guarantee, not a need — one small
    /// allocation per process.
    pub(in crate::gui) fn web_context(
        app: &AppIdentity,
        dirs: &AppDirs,
    ) -> Option<&'static mut wry::WebContext> {
        let dir = super::webview_data_dir(app, dirs);
        if let Err(error) = std::fs::create_dir_all(&dir) {
            eprintln!(
                "{}: cannot create the web view's data folder {}: {error}",
                app.log_prefix,
                dir.display()
            );
            return None;
        }
        Some(Box::leak(Box::new(wry::WebContext::new(Some(dir)))))
    }

    /// Microsoft's page for the WebView2 runtime (the Evergreen installer).
    const WEBVIEW2_DOWNLOAD: &str = "https://developer.microsoft.com/microsoft-edge/webview2/";

    /// Say why there is no window, in a dialog: the apps are GUI programs on
    /// Windows (no console), so the error the app returns would otherwise
    /// vanish with the process.
    /// Blocks on purpose (the app exits as soon as this returns).
    ///
    /// A missing runtime gets its own message and an offer to open the
    /// download page: Windows 11 ships WebView2, but Windows 10 machines
    /// and some managed images do not have it.
    pub(in crate::gui) fn report_webview_failure(app: &AppIdentity, error: &wry::Error) {
        let name = app.name;
        let dialog = rfd::MessageDialog::new()
            .set_level(rfd::MessageLevel::Error)
            .set_title(name);
        if wry::webview_version().is_ok() {
            dialog
                .set_description(format!("{name} could not create its window: {error}"))
                .set_buttons(rfd::MessageButtons::Ok)
                .show();
            return;
        }
        let answer = dialog
            .set_description(format!(
                "{name} needs the Microsoft Edge WebView2 Runtime, which is not \
                 installed on this PC.\n\nInstall the Evergreen runtime from \
                 {WEBVIEW2_DOWNLOAD} and open {name} again.\n\nOpen the download page now?"
            ))
            .set_buttons(rfd::MessageButtons::YesNo)
            .show();
        if answer == rfd::MessageDialogResult::Yes
            && let Err(error) = super::super::shell_open(WEBVIEW2_DOWNLOAD)
        {
            eprintln!(
                "{}: could not open {WEBVIEW2_DOWNLOAD}: {error}",
                app.log_prefix
            );
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{HeldChord, menu_may_take, webview_data_dir};
    use crate::{AppDirs, AppIdentity};
    use std::path::Path;

    #[test]
    fn the_editing_chords_never_reach_the_menu() {
        for key in "ACVXYZ".bytes() {
            assert!(!menu_may_take(u32::from(key)), "{}", key as char);
        }
        // The menu's own chords: N, O, R, comma (VK_OEM_COMMA), = (VK_OEM_PLUS),
        // - (VK_OEM_MINUS), 0, and the arrows Back/Forward ride on.
        for key in b"NOR0".map(u32::from).into_iter().chain([
            0xBC, // VK_OEM_COMMA
            0xBB, // VK_OEM_PLUS
            0xBD, // VK_OEM_MINUS
            0x25, // VK_LEFT
            0x27, // VK_RIGHT
        ]) {
            assert!(menu_may_take(key), "{key:#x}");
        }
    }

    #[test]
    fn a_held_chord_fires_once_and_keeps_its_repeats_from_the_page() {
        let held = HeldChord::default();
        let fired = std::cell::Cell::new(0);
        let press = |key, repeat, taken| {
            held.key_down(key, repeat, || {
                fired.set(fired.get() + 1);
                taken
            })
        };
        // Ctrl+O, held: one Open, and the repeats are swallowed unfired.
        assert!(press(0x4F, false, true));
        assert!(press(0x4F, true, true));
        assert!(press(0x4F, true, true));
        assert_eq!(fired.get(), 1);
        // A chord the menu does not take is the page's, repeats included.
        assert!(!press(0x44, false, false));
        assert!(!press(0x44, true, false));
        assert_eq!(fired.get(), 2);
        // A repeat of an earlier, taken key no longer counts once another
        // key went down in between.
        assert!(!press(0x4F, true, true));
        assert_eq!(fired.get(), 2);
    }

    const APP: AppIdentity = AppIdentity {
        name: "Ledgeline Invoicer",
        bundle_id: "com.zmre.ledgeline.invoicer",
        log_prefix: "ledgeline-invoicer",
        token_env: "X",
        token_global: "__X__",
        embedded_global: "__Y__",
        spa_base: "/app/",
        spa_frame_src: None,
    };

    #[test]
    fn each_app_keeps_its_web_view_profile_in_its_own_cache_folder() {
        let dirs = AppDirs::under("/local");
        assert_eq!(
            webview_data_dir(&APP, &dirs),
            Path::new("/local/cache/webview2/ledgeline-invoicer")
        );
        let no_cache = AppDirs {
            cache_dir: None,
            ..AppDirs::under("/local")
        };
        assert_eq!(
            webview_data_dir(&APP, &no_cache),
            Path::new("/local/tmp/webview2/ledgeline-invoicer")
        );
    }
}