mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-26 09:08:11 +00:00
menu: a macOS menu rebuild that fails is tried again
When AppKit could not rebuild the menu bar, the old menus stayed up but nothing tried the rebuild again: NativeBar::apply returned false for a failed rebuild and for an update in place alike, and the driver had already recorded the new menus as synced. - craft-window: NativeBar::failed reports a rebuild that failed. - craft-menu: RebuildRetry tries menus whose build failed once more REBUILD_RETRY (one second) after the failure; when that fails too, they are not built again until they change. - The macOS backend keeps the menus pending after a failed rebuild and asks egui for a repaint when the retry is due, asking again on each frame before then. Carries the fix from storytold/vectorcraft#9056.
This commit is contained in:
@@ -227,7 +227,8 @@ While a menu is open, a click or Escape in the window closes it and does not rea
|
||||
canvas gesture, no tool action); pointer moves pass through. Only one click is kept this way
|
||||
until the menu reports closed, so a menu wrongly reported open costs one click. Menu updates wait
|
||||
until the menu closes; the end of tracking wakes egui, and that frame applies them. A rebuild that
|
||||
fails keeps the menus as they were.
|
||||
fails keeps the menus as they were, and the same menus are tried once more a second later, with no
|
||||
input needed (`RebuildRetry`). When that fails too, the next change to the menus tries again.
|
||||
|
||||
AppKit's `NSMenuDidBeginTracking` and `NSMenuDidEndTracking` notifications say whether a menu is
|
||||
open (`craft_window::native_menu::menu_tracking()`, safe from any thread). Each begin comes back
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
use std::borrow::Cow;
|
||||
use std::collections::HashSet;
|
||||
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use craft_keymap::{Chord, CommandRef, Key, Mods};
|
||||
use craft_ui::contract::{MemoKey, MemoProps};
|
||||
@@ -203,6 +204,67 @@ pub trait Backend {
|
||||
fn attach(&mut self, dispatch: Dispatch);
|
||||
}
|
||||
|
||||
/// How long a backend waits after a failed rebuild before it tries the same menus once more
|
||||
/// ([`RebuildRetry`]).
|
||||
pub const REBUILD_RETRY: Duration = Duration::from_secs(1);
|
||||
|
||||
/// When a backend tries again to build menus the platform could not build. New menus are always
|
||||
/// built. When their build fails, the same menus are tried once more [`REBUILD_RETRY`] after the
|
||||
/// failure; when that fails too, they are not tried again until they change.
|
||||
///
|
||||
/// The driver syncs a backend only when the menus' key, the gate or a menu event calls for it
|
||||
/// ([`NativeMenu::sync_with`]), so a backend keeps the menus it could not build and tries them
|
||||
/// again itself, for example from [`Backend::drain`], asking egui for a frame when the retry is
|
||||
/// due.
|
||||
#[derive(Debug)]
|
||||
pub struct RebuildRetry<B> {
|
||||
/// The menus whose build failed, and when to try them again (`None`: their retry failed too).
|
||||
failed: Option<(B, Option<Instant>)>,
|
||||
}
|
||||
|
||||
impl<B> Default for RebuildRetry<B> {
|
||||
fn default() -> RebuildRetry<B> {
|
||||
RebuildRetry { failed: None }
|
||||
}
|
||||
}
|
||||
|
||||
/// What [`RebuildRetry::attempt`] did.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
#[non_exhaustive]
|
||||
pub enum Attempt {
|
||||
/// The menus were built.
|
||||
Built,
|
||||
/// The menus were not built: their build failed, or their retry is not due yet. Try them again
|
||||
/// after this long.
|
||||
Retry(Duration),
|
||||
/// The build failed and so did its retry: these menus are not built again until they change.
|
||||
Failed,
|
||||
}
|
||||
|
||||
impl<B: Clone + PartialEq> RebuildRetry<B> {
|
||||
/// Build `bar` with `build` (which returns whether it succeeded) unless `bar` failed before
|
||||
/// and its retry is not due, and record the outcome. `clock` gives the time. It is read again
|
||||
/// after a failed build, so the delay starts when the build fails.
|
||||
pub fn attempt(&mut self, bar: &B, clock: impl Fn() -> Instant, build: impl FnOnce() -> bool) -> Attempt {
|
||||
let now = clock();
|
||||
let retrying = match &self.failed {
|
||||
Some((failed, at)) if failed == bar => match at {
|
||||
Some(at) if now < *at => return Attempt::Retry(at.saturating_duration_since(now)),
|
||||
Some(_) => true,
|
||||
None => return Attempt::Failed,
|
||||
},
|
||||
_ => false,
|
||||
};
|
||||
if build() {
|
||||
self.failed = None;
|
||||
return Attempt::Built;
|
||||
}
|
||||
let at = if retrying { None } else { clock().checked_add(REBUILD_RETRY) };
|
||||
self.failed = Some((bar.clone(), at));
|
||||
if at.is_some() { Attempt::Retry(REBUILD_RETRY) } else { Attempt::Failed }
|
||||
}
|
||||
}
|
||||
|
||||
/// The native menu bar, while the app uses one (its in-window menus are hidden then).
|
||||
pub struct NativeMenu {
|
||||
backend: Box<dyn Backend>,
|
||||
|
||||
@@ -126,7 +126,7 @@ pub use craft_keymap::{Chord, CommandRef};
|
||||
pub use craft_ui::menu::Alternate;
|
||||
pub use customize::Customization;
|
||||
pub use documents::DOCUMENT_COMMAND_PREFIX;
|
||||
pub use driver::{Backend, ClipboardKeys, CommandHook, Dispatch, Event, Gate, NativeMenu};
|
||||
pub use driver::{Attempt, Backend, ClipboardKeys, CommandHook, Dispatch, Event, Gate, NativeMenu, REBUILD_RETRY, RebuildRetry};
|
||||
pub use help::{HelpCommand, HelpLabels, HelpLink, HelpMenu};
|
||||
pub use keymap::{ItemState, apply_keymap, apply_state};
|
||||
pub use keytips::{KeytipControl, Keytips, KeytipsOutput};
|
||||
|
||||
+27
-5
@@ -26,16 +26,20 @@
|
||||
//! Hide Others and Minimize built-ins use the system's localized titles when the app supplies no
|
||||
//! translation, that is when the label is still the English name.
|
||||
//! - While a menu is open, changes wait until it closes.
|
||||
//! - When AppKit refuses a rebuild, the menus as they were stay up and the same menus are tried
|
||||
//! once more a second later ([`RebuildRetry`]), with no input needed; when that fails too, the
|
||||
//! next change to the menus tries again.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::mpsc::{Receiver, Sender, channel};
|
||||
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
|
||||
use std::time::Instant;
|
||||
|
||||
use craft_keymap::{Chord, CommandRef, Key, Mods};
|
||||
use craft_ui::menu::Alternate;
|
||||
use craft_window::native_menu as native;
|
||||
|
||||
use crate::driver::{Backend, Dispatch, Event, NativeMenu, native_ok};
|
||||
use crate::driver::{Attempt, Backend, Dispatch, Event, NativeMenu, RebuildRetry, native_ok};
|
||||
use crate::model::{Builtin, Item, ItemKind, Menu, MenuBar, MenuRole, Node, Standard, label_or_system, native_id, structure_key, window_key};
|
||||
|
||||
/// Install the native menu bar for `bar` (a [`crate::mac_layout`] result) and return the driver
|
||||
@@ -83,7 +87,8 @@ pub fn install_with(ctx: &egui::Context, bar: &MenuBar, options: MacOptions) ->
|
||||
});
|
||||
let installed = native::NativeBar::install(&spec, native::Options::default().window_list(options.window_list), wake)?;
|
||||
let (tx, rx) = channel();
|
||||
let backend = Native { ctx: ctx.clone(), bar: installed, targets: Arc::new(Mutex::new(targets)), tx, rx, pending: None };
|
||||
let backend =
|
||||
Native { ctx: ctx.clone(), bar: installed, targets: Arc::new(Mutex::new(targets)), tx, rx, pending: None, retry: RebuildRetry::default() };
|
||||
// `NativeMenu::new` attaches the driver's dispatch, which points the handler at this menu.
|
||||
Some(NativeMenu::new(Box::new(backend)))
|
||||
}
|
||||
@@ -135,15 +140,32 @@ struct Native {
|
||||
targets: Targets,
|
||||
tx: Sender<Event>,
|
||||
rx: Receiver<Event>,
|
||||
/// The latest menus, waiting for the open menu to close.
|
||||
/// The latest menus, waiting for the open menu to close, or for the retry of a rebuild that
|
||||
/// failed.
|
||||
pending: Option<MenuBar>,
|
||||
/// Menus AppKit could not build, and when to try them again.
|
||||
retry: RebuildRetry<native::Bar>,
|
||||
}
|
||||
|
||||
impl Native {
|
||||
/// Bring the native menus in step with `bar`. When the rebuild fails and a retry is to come,
|
||||
/// `bar` waits in `pending` and egui is asked for a frame when the retry is due: the driver
|
||||
/// does not sync the same menus again.
|
||||
fn update(&mut self, bar: &MenuBar) {
|
||||
let (spec, targets) = lower(bar);
|
||||
if self.bar.apply(&spec) {
|
||||
*lock(&self.targets) = targets;
|
||||
let (native, live) = (&mut self.bar, &self.targets);
|
||||
let attempt = self.retry.attempt(&spec, Instant::now, || {
|
||||
let rebuilt = native.apply(&spec);
|
||||
if rebuilt {
|
||||
*lock(live) = targets;
|
||||
}
|
||||
!native.failed()
|
||||
});
|
||||
// egui keeps no repaint delay from one pass to the next, so a frame before the retry is
|
||||
// due asks again.
|
||||
if let Attempt::Retry(wait) = attempt {
|
||||
self.pending = Some(bar.clone());
|
||||
self.ctx.request_repaint_after(wait);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,11 +5,12 @@
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::rc::Rc;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use craft_keymap::Mods;
|
||||
use craft_menu::{
|
||||
Alternate, Backend, Builtin, Chord, ClipboardKeys, CommandRef, Dispatch, Event, Gate, ItemState, LayoutOptions, MenuBar, NativeMenu, apply_state,
|
||||
mac_layout, structure_key,
|
||||
Alternate, Attempt, Backend, Builtin, Chord, ClipboardKeys, CommandRef, Dispatch, Event, Gate, ItemState, LayoutOptions, MenuBar, NativeMenu,
|
||||
REBUILD_RETRY, RebuildRetry, apply_state, mac_layout, structure_key,
|
||||
};
|
||||
use craft_ui::contract::{Props as _, Show as _, Tracked};
|
||||
use craft_ui::testing::focus::key_release;
|
||||
@@ -379,3 +380,56 @@ fn apply_state_with_no_change_keeps_the_revision() {
|
||||
apply_state(&mut model, |command| ItemState::default().enabled(*command != cmd("file.new")));
|
||||
assert_eq!(model.revision(), moved, "and the same changed state again does not");
|
||||
}
|
||||
|
||||
/// Menus whose build failed are not built again before their retry is due, are built once when it
|
||||
/// is due, and are not built again after that fails too; changed menus are built and get their own
|
||||
/// retry.
|
||||
#[trial]
|
||||
fn a_failed_rebuild_is_tried_once_more() {
|
||||
let (first, second) = (sample(false, true), sample(true, true));
|
||||
let mut retry = RebuildRetry::default();
|
||||
let start = Instant::now();
|
||||
let clock = Cell::new(start);
|
||||
let builds = Cell::new(0);
|
||||
let fail = || {
|
||||
builds.set(builds.get() + 1);
|
||||
false
|
||||
};
|
||||
assert_eq!(retry.attempt(&first, || clock.get(), fail), Attempt::Retry(REBUILD_RETRY), "a failed build waits for its retry");
|
||||
clock.set(start + REBUILD_RETRY / 2);
|
||||
let Attempt::Retry(left) = retry.attempt(&first, || clock.get(), fail) else { panic!("the retry is not due yet") };
|
||||
assert!(left < REBUILD_RETRY, "a sync before the retry learns the time left: {left:?}");
|
||||
assert_eq!(builds.get(), 1, "nothing is built before the retry is due");
|
||||
clock.set(start + REBUILD_RETRY);
|
||||
assert_eq!(retry.attempt(&first, || clock.get(), fail), Attempt::Failed, "the retry fails too");
|
||||
clock.set(start + REBUILD_RETRY * 10);
|
||||
assert_eq!(retry.attempt(&first, || clock.get(), fail), Attempt::Failed);
|
||||
assert_eq!(builds.get(), 2, "the same menus are tried once more, and only once");
|
||||
assert_eq!(retry.attempt(&second, || clock.get(), fail), Attempt::Retry(REBUILD_RETRY), "changed menus are built and get their own retry");
|
||||
assert_eq!(builds.get(), 3);
|
||||
clock.set(start + REBUILD_RETRY * 11);
|
||||
assert_eq!(retry.attempt(&second, || clock.get(), || true), Attempt::Built, "the retry builds them");
|
||||
assert_eq!(retry.attempt(&second, || clock.get(), || true), Attempt::Built, "built menus can be built again");
|
||||
}
|
||||
|
||||
/// A build that fails slowly gets the whole delay, counted from when it failed.
|
||||
#[trial]
|
||||
fn a_retry_waits_from_when_the_build_failed() {
|
||||
let bar = sample(false, true);
|
||||
let mut retry = RebuildRetry::default();
|
||||
let start = Instant::now();
|
||||
let clock = Cell::new(start);
|
||||
let slow = Duration::from_millis(1200);
|
||||
let slow_failure = || {
|
||||
clock.set(start + slow);
|
||||
false
|
||||
};
|
||||
assert_eq!(retry.attempt(&bar, || clock.get(), slow_failure), Attempt::Retry(REBUILD_RETRY));
|
||||
clock.set(start + REBUILD_RETRY);
|
||||
let Attempt::Retry(left) = retry.attempt(&bar, || clock.get(), || panic!("built before the retry was due")) else {
|
||||
panic!("the retry is not due a delay after the build began")
|
||||
};
|
||||
assert_eq!(left, slow, "the delay runs from the failure, not from when the build began");
|
||||
clock.set(start + slow + REBUILD_RETRY);
|
||||
assert_eq!(retry.attempt(&bar, || clock.get(), || true), Attempt::Built, "the retry runs when it is due");
|
||||
}
|
||||
|
||||
@@ -138,7 +138,8 @@ bottom. egui does not expose the OS work area, so this is an estimate, not an OS
|
||||
description: `Bar` of `Menu`s of `Node`s (`Item { id, label, enabled, checked, shortcut }`, submenus,
|
||||
separators, and the platform's own items such as Services and Zoom). `NativeBar::install` makes it the
|
||||
application's menu bar, `NativeBar::apply` keeps it in step (a changed `structure` key rebuilds, a changed
|
||||
`windows` key rebuilds only the Windows menu, anything else updates in place), and the `Handler` set with
|
||||
`windows` key rebuilds only the Windows menu, anything else updates in place; `NativeBar::failed` reports a
|
||||
rebuild that failed and left the menus as they were), and the `Handler` set with
|
||||
`NativeBar::set_handler` receives each chosen item's `id`, the modifiers held and whether a key press chose it.
|
||||
`install_app_menu` installs a minimal app menu whose Quit reports to a handler. Off macOS (and without the
|
||||
feature) every call does nothing, so callers need no platform check. craft-menu lowers its menu model to
|
||||
|
||||
@@ -15,6 +15,8 @@
|
||||
//! - A change of [`Bar::structure`] rebuilds every menu; a change of [`Bar::windows`] rebuilds only
|
||||
//! the [`MenuKind::Windows`] menu, because AppKit adds its own items there. Anything else is
|
||||
//! updated in place (label, enabled, checked).
|
||||
//! - When a rebuild fails, the menus stay as they were and [`NativeBar::failed`] reports it, so
|
||||
//! the caller can apply the same bar again later.
|
||||
//! - While a menu is open ([`NativeBar::tracking`]) the caller waits to apply changes: replacing a
|
||||
//! menu the platform is tracking can leave it stranded on screen.
|
||||
//! - Only items with a [`Shortcut`] become key equivalents; the caller decides which shortcuts
|
||||
@@ -288,6 +290,12 @@ impl NativeBar {
|
||||
self.0.apply(bar)
|
||||
}
|
||||
|
||||
/// Whether the last [`NativeBar::apply`] had to rebuild menus and could not. The menus stay as
|
||||
/// they were, and applying the same bar again tries the rebuild again.
|
||||
pub fn failed(&self) -> bool {
|
||||
self.0.failed()
|
||||
}
|
||||
|
||||
/// Whether one of the menus is open.
|
||||
pub fn tracking(&self) -> bool {
|
||||
self.0.tracking()
|
||||
|
||||
@@ -216,6 +216,8 @@ pub(super) struct Installed {
|
||||
structure: u64,
|
||||
window: Option<WindowMenu>,
|
||||
options: Options,
|
||||
/// The last [`Installed::apply`] had to rebuild menus and could not.
|
||||
failed: bool,
|
||||
}
|
||||
|
||||
impl Installed {
|
||||
@@ -224,7 +226,7 @@ impl Installed {
|
||||
if INSTALLED.swap(true, Ordering::SeqCst) {
|
||||
return None;
|
||||
}
|
||||
let mut installed = Installed { menu: None, entries: HashMap::new(), structure: 0, window: None, options };
|
||||
let mut installed = Installed { menu: None, entries: HashMap::new(), structure: 0, window: None, options, failed: false };
|
||||
if !installed.build(bar) {
|
||||
INSTALLED.store(false, Ordering::SeqCst);
|
||||
return None;
|
||||
@@ -238,7 +240,8 @@ impl Installed {
|
||||
}
|
||||
|
||||
/// Build the menu bar for `bar` and make it NSApp's. On an error or a panic in muda or AppKit
|
||||
/// the menus stay as they were (never crash for a menu) and this returns false.
|
||||
/// the menus stay as they were (never crash for a menu), [`Installed::failed`] reports it and
|
||||
/// this returns false.
|
||||
fn build(&mut self, bar: &Bar) -> bool {
|
||||
let built = catch_unwind(AssertUnwindSafe(|| -> muda::Result<(muda::Menu, Entries, Option<WindowMenu>)> {
|
||||
let mut entries = Entries::new();
|
||||
@@ -271,9 +274,11 @@ impl Installed {
|
||||
self.entries = entries;
|
||||
self.window = window;
|
||||
self.structure = bar.structure;
|
||||
self.failed = false;
|
||||
true
|
||||
}
|
||||
_ => {
|
||||
self.failed = true;
|
||||
// The new menu may have been made NSApp's before the failure.
|
||||
if let Some(old) = &self.menu {
|
||||
let _ = catch_unwind(AssertUnwindSafe(|| {
|
||||
@@ -326,6 +331,8 @@ impl Installed {
|
||||
}
|
||||
|
||||
pub(super) fn apply(&mut self, bar: &Bar) -> bool {
|
||||
// An update in place has nothing to fail; a rebuild below sets it again.
|
||||
self.failed = false;
|
||||
if self.menu.is_none() || bar.structure != self.structure {
|
||||
return self.build(bar);
|
||||
}
|
||||
@@ -362,6 +369,10 @@ impl Installed {
|
||||
rebuilt
|
||||
}
|
||||
|
||||
pub(super) fn failed(&self) -> bool {
|
||||
self.failed
|
||||
}
|
||||
|
||||
pub(super) fn tracking(&self) -> bool {
|
||||
menu_tracking()
|
||||
}
|
||||
|
||||
@@ -30,6 +30,10 @@ impl Installed {
|
||||
match self.0 {}
|
||||
}
|
||||
|
||||
pub(super) fn failed(&self) -> bool {
|
||||
match self.0 {}
|
||||
}
|
||||
|
||||
pub(super) fn tracking(&self) -> bool {
|
||||
match self.0 {}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user