hex/src/rune_hud/macos.rs

451 lines
18 KiB
Rust

//! The HUD on macOS: placed on the screen with the pointer, below the menu
//! bar, in it, or out of the notch (`hud_placement`), from `NSScreen`'s
//! metrics, and kept on every Space. The main thread's pump hands it the
//! listener's events.
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Instant;
use objc2::MainThreadMarker;
use objc2::rc::Retained;
use objc2_app_kit::{
NSApplication, NSEvent, NSScreen, NSStatusBar, NSWindow, NSWindowCollectionBehavior,
};
use objc2_foundation::{NSNumber, NSRect, NSString};
use rune::{DisplayTarget, NativeDisplayId, OverlayHandle, OverlayPlacement};
use super::{Hud, HudEvent, HudSender, LIVE_TEXT_GAP, WINDOW, rehome, set_live_text};
use crate::app_settings::IndicatorPosition;
use crate::rune_hud::hud_placement;
use crate::rune_ui::live_text::Spot;
/// `NSStatusWindowLevel`: over other apps' windows, under the menu bar.
const STATUS_LEVEL: isize = 25;
/// The screen under the pointer (else the main one) as `hud_placement`
/// reads it, the primary screen's top, which Rune's global space hangs
/// from, the screen's backing scale, and its `NSScreenNumber`, which Rune's
/// `NativeDisplayId::MacOS` pins an overlay to.
pub(crate) fn pointer_screen(
mtm: MainThreadMarker,
) -> Option<(hud_placement::Screen, f64, f64, Option<u32>)> {
let pointer = NSEvent::mouseLocation();
let screens = NSScreen::screens(mtm);
let primary = screens.iter().next()?;
// The half-open rule Rune resolves `UnderPointer` with (closed at a
// screen's top, open at its bottom), so the capsule's panel and the
// notch it hangs from pick the same display where two share an edge.
// The fallback stays the main screen: Rune's "previous display" would
// need state the HUD's placement doesn't keep.
let screen = screens
.iter()
.find(|screen| {
let frame = screen.frame();
pointer.x >= frame.origin.x
&& pointer.x < frame.origin.x + frame.size.width
&& pointer.y > frame.origin.y
&& pointer.y <= frame.origin.y + frame.size.height
})
.or_else(|| NSScreen::mainScreen(mtm))?;
let rect = |r: NSRect| hud_placement::Rect {
x: r.origin.x,
y: r.origin.y,
width: r.size.width,
height: r.size.height,
};
let metrics = hud_placement::Screen {
frame: rect(screen.frame()),
visible: rect(screen.visibleFrame()),
safe_top: screen.safeAreaInsets().top,
aux_left: screen.auxiliaryTopLeftArea().size.width,
aux_right: screen.auxiliaryTopRightArea().size.width,
bar: NSStatusBar::systemStatusBar().thickness(),
};
Some((
metrics,
primary.frame().origin.y + primary.frame().size.height,
screen.backingScaleFactor(),
screen_number(&screen),
))
}
/// The screen's `NSScreenNumber` (`CGDirectDisplayID`), the id Rune's
/// `NativeDisplayId::MacOS` matches: winit reports a monitor's native id
/// the same way (`CGDisplayGetDisplayIDFromUUID`), so a measured notch can
/// pin the panel to the display it was read on.
fn screen_number(screen: &NSScreen) -> Option<u32> {
let description = screen.deviceDescription();
let key = NSString::from_str("NSScreenNumber");
let number = description.objectForKey(&key)?;
Some(number.downcast_ref::<NSNumber>()?.unsignedIntValue())
}
/// The HUD's window and widest plate, and how far its island
/// spreads past the notch.
fn content(island_spread: f32) -> hud_placement::Content {
let (width, height) = WINDOW;
hud_placement::Content {
window: (f64::from(width), f64::from(height)),
plate: (
f64::from(width) - 24.0,
f64::from(crate::rune_hud::dot_scope::PLATE_HEIGHT),
),
island_spread: f64::from(island_spread),
}
}
/// The live text's spot just past `placed`'s plate, in Rune's global space.
fn live_text_beside(
placed: &hud_placement::Placed,
screen: &hud_placement::Screen,
content: hud_placement::Content,
primary_top: f64,
) -> Spot {
let (bottom, margin) =
hud_placement::beside_plate(placed, screen, content, f64::from(LIVE_TEXT_GAP));
let y = if bottom {
screen.frame.y + margin
} else {
screen.frame.y + screen.frame.height - margin
};
Spot::Global {
x: (placed.top_left.0 + content.window.0 / 2.0 + f64::from(placed.layout.center[0])) as f32,
y: (primary_top - y) as f32,
below: !bottom,
}
}
/// An activation-policy change is waiting for the HUD's panel: changing it
/// (the Dock icon follows Settings) can tie Rune's panel to one Space while
/// AppKit still reports every Space (#1725). It outlives the call that made
/// it, because the startup one can come before Rune makes the panel, and the
/// first pump tick after that re-asserts it.
static ACTIVATION_POLICY_CHANGED: AtomicBool = AtomicBool::new(false);
/// Records that the activation policy changed, so the pump's next tick
/// re-asserts the HUD panel's collection behaviors.
pub(crate) fn activation_policy_changed() {
ACTIVATION_POLICY_CHANGED.store(true, Ordering::Release);
}
/// Whether a change recorded by [`activation_policy_changed`] still waits for
/// a panel to repair; a caller that repairs takes it.
fn take_activation_policy_changed() -> bool {
ACTIVATION_POLICY_CHANGED.swap(false, Ordering::AcqRel)
}
/// Keeps a taken change for the next tick: there was no panel to repair yet.
fn keep_activation_policy_changed() {
ACTIVATION_POLICY_CHANGED.store(true, Ordering::Release);
}
/// The collection behaviors Rune gives the HUD's panel when it makes it
/// (`rune`'s `platform/macos.rs`): on every Space, ordered with it, out of the
/// window cycle, and over another application's full-screen Space too (#75).
fn intended_behavior() -> NSWindowCollectionBehavior {
NSWindowCollectionBehavior::CanJoinAllSpaces
| NSWindowCollectionBehavior::Stationary
| NSWindowCollectionBehavior::IgnoresCycle
| NSWindowCollectionBehavior::FullScreenAuxiliary
// macOS 13+; earlier versions ignore the bit.
| NSWindowCollectionBehavior::CanJoinAllApplications
}
/// Clears the panel's behaviors and sets the intended ones again. A read-back
/// of a broken mask can equal the intended one, and AppKit then ignores the
/// write, so the clear makes it a change again.
fn apply_behavior(panel: &NSWindow) {
panel.setCollectionBehavior(NSWindowCollectionBehavior::Default);
panel.setCollectionBehavior(intended_behavior());
}
/// Orders the panel out, applies its behaviors, and orders it back in
/// regardless, so the window server applies them to whichever Space is active.
/// This reorders the panel but leaves Rune's presence state and alpha alone.
fn rehome_panel(panel: &NSWindow) {
panel.orderOut(None);
apply_behavior(panel);
panel.orderFrontRegardless();
}
/// The pump's handle on the HUD (main thread).
pub(crate) struct DictationIndicatorUi {
hud: HudSender,
/// The HUD's panel and the window number it had when found: Rune makes a
/// new window, with a new number, when it remakes the overlay.
panel: Option<(u32, Retained<NSWindow>)>,
/// This show's re-home attempts: a stranding gets a bounded few, and a
/// panel seen on the active Space or a hide starts the budget over.
rehome: rehome::Rehome,
}
impl DictationIndicatorUi {
pub(crate) fn new(hud: HudSender) -> Self {
Self {
hud,
panel: None,
rehome: rehome::Rehome::default(),
}
}
pub(crate) fn handle(&mut self, event: HudEvent) {
self.hud.send(event);
}
/// Whether the HUD wants the display's frames: the pump ticks every
/// frame only while it does.
pub(crate) fn animating(&self) -> bool {
self.hud.animating.load(Ordering::Acquire)
}
/// Keeps a showing HUD on the pointer's screen and the active Space, and
/// hides it when the indicator is set to Hidden.
pub(crate) fn follow_pointer(&mut self) {
let animating = self.hud.animating.load(Ordering::Acquire);
let shown = self.hud.shown.load(Ordering::Acquire);
if !shown {
// Each show gets a fresh budget.
self.rehome.hide();
} else if let Some(mtm) = MainThreadMarker::new() {
self.rehome_on_active_space(mtm);
}
if !animating {
return;
}
self.hud.overlay.update_if(|hud, _| {
hud.sync_placement();
false
});
}
/// The HUD's panel, found among the app's windows once per Rune window.
fn panel(&mut self, mtm: MainThreadMarker) -> Option<(u32, Retained<NSWindow>)> {
let Some(number) = self.hud.overlay.window_number() else {
self.panel = None;
return None;
};
if let Some((cached, panel)) = &self.panel
&& *cached == number
{
return Some((number, panel.clone()));
}
let panel = NSApplication::sharedApplication(mtm)
.windows()
.iter()
.find(|window| window.windowNumber() == number as isize);
let Some(panel) = panel else {
self.panel = None;
return None;
};
self.panel = Some((number, panel.clone()));
Some((number, panel))
}
/// Re-asserts the HUD panel's collection behaviors after a Dock-icon
/// (activation policy) change, once per change. A hidden panel only gets
/// them written again, so a hide Rune has queued is not undone, and that
/// spends no repair attempt; a shown one is ordered out, written, and
/// ordered back in whatever AppKit says about the active Space, since the
/// change can leave that answer wrong (#1725). A change with no panel yet
/// waits for the first one.
pub(crate) fn reassert_after_activation_policy_change(&mut self) {
if !take_activation_policy_changed() {
return;
}
let Some(mtm) = MainThreadMarker::new() else {
keep_activation_policy_changed();
return;
};
let Some((number, panel)) = self.panel(mtm) else {
// Rune makes the panel when it first shows the overlay.
keep_activation_policy_changed();
return;
};
// A HUD on its way out stays visible until Rune applies the hide.
let visible = self.hud.shown.load(Ordering::Acquire) && panel.isVisible();
// Read before the repair: the window server applies it later, and the
// pump's next ticks log whether it took.
let active_space = panel.isOnActiveSpace();
match self.rehome.reassert(Instant::now(), visible) {
rehome::Repair::None => {}
rehome::Repair::Mask => apply_behavior(&panel),
rehome::Repair::Rehome => rehome_panel(&panel),
}
tracing::info!(
window = number,
visible,
active_space,
"re-asserted the dictation HUD's collection behaviors after a Dock icon change"
);
}
/// Puts a shown HUD back on the active Space. Changing the activation
/// policy (the Dock icon follows Settings) can tie Rune's panel to one
/// Space while AppKit still reports `CanJoinAllSpaces`, and Rune repairs
/// that only as its panel shows (#1084). Clearing the mask and setting the
/// intended one back makes the window server apply it again; the panel is
/// ordered out and back in, so this reorders the panel but leaves Rune's
/// presence state and alpha alone. The window server applies that later,
/// so an attempt is judged, and logged, only on a later tick: one that
/// still finds the panel elsewhere after [`rehome::wait`] counts it and
/// tries again with a longer wait, for at most [`rehome::MAX_REPAIRS`]
/// attempts, reset when the panel is seen on the active Space or the HUD
/// hides, so a repair that did not take cannot loop.
fn rehome_on_active_space(&mut self, mtm: MainThreadMarker) {
let Some((number, panel)) = self.panel(mtm) else {
return;
};
// Rune applies the queued show later than `shown` flips.
let located = if !panel.isVisible() {
rehome::Located::Hidden
} else if panel.isOnActiveSpace() {
rehome::Located::Active
} else {
rehome::Located::Elsewhere
};
let decision = self.rehome.decide(Instant::now(), located);
match decision.confirmed {
None if decision.repair == rehome::Repair::Rehome => tracing::info!(
window = number,
"the dictation HUD is on another Space; re-homing it"
),
None => {}
Some(rehome::Confirmed::Repaired { attempts }) => tracing::info!(
window = number,
attempts,
"the dictation HUD is on the active Space again after re-homing"
),
Some(rehome::Confirmed::Stranded {
attempts,
next: Some(next),
}) => tracing::info!(
window = number,
attempts,
next_try_ms = next.as_millis() as u64,
"the dictation HUD is still on another Space; re-homing it again"
),
Some(rehome::Confirmed::Stranded {
attempts,
next: None,
}) => tracing::warn!(
window = number,
attempts,
"the dictation HUD is still on another Space; giving up until it shows again"
),
}
if decision.repair == rehome::Repair::Rehome {
rehome_panel(&panel);
}
}
}
impl Hud {
pub(super) fn placed(&self) -> Option<hud_placement::Placed> {
match self.presence {
super::HudPresence::Shown { placed } => placed,
super::HudPresence::Hidden => None,
}
}
pub(super) fn set_placed(&mut self, next: hud_placement::Placed) {
if let super::HudPresence::Shown { placed } = &mut self.presence {
*placed = Some(next);
}
}
/// With the HUD hidden, the live text starts where its plate would sit
/// under the menu bar.
pub(super) fn place_live_text_without_hud(&self) {
let Some((screen, primary_top, _, _)) = MainThreadMarker::new().and_then(pointer_screen)
else {
return;
};
let content = content(0.0);
let placed = hud_placement::place(
Default::default(),
&screen,
content,
false,
hud_placement::BOTTOM_OFFSET,
);
let (top, _) = hud_placement::plate_span(&placed, content);
set_live_text(Spot::Global {
x: (screen.frame.x + screen.frame.width / 2.0) as f32,
y: (primary_top - top) as f32,
below: true,
});
}
pub(super) fn place_on_pointer_screen(&mut self, overlay: &OverlayHandle<Hud>) {
let Some((mut metrics, primary_top, _, display)) =
MainThreadMarker::new().and_then(pointer_screen)
else {
return;
};
let tuning = self.model.tuning();
if tuning.pretend_notch {
metrics = metrics.pretending_notch();
}
let (width, height) = WINDOW;
let content = content(tuning.island_spread);
// Labs' notch indicator takes any shown position on a notched screen;
// Hidden and flat screens leave HUD Lab's placement standing.
let ears = hud_placement::notch_placement(
crate::labs::notch_indicator(),
self.position,
&metrics,
content,
);
let placed = ears.unwrap_or_else(|| {
hud_placement::place(
tuning.placement,
&metrics,
content,
self.position == IndicatorPosition::Bottom,
crate::labs::hud_bottom_gap(),
)
});
set_live_text(live_text_beside(&placed, &metrics, content, primary_top));
// `placed` carries the display's absolute coordinates, so moving the
// pointer to another display changes it (a mirrored set is one
// NSScreen); the pinned display is re-sent with the new rect.
if self.placed() == Some(placed) {
return;
}
if self.placed().map(|old| old.over_menu_bar) != Some(placed.over_menu_bar) {
// Above the menu bar and its status items, below their menus.
overlay.set_macos_level(STATUS_LEVEL + isize::from(placed.over_menu_bar));
}
self.set_placed(placed);
self.layout = placed.layout;
self.model.set_island(placed.layout.island);
let (x, top) = placed.top_left;
match display {
// Pin the overlay to the screen the placement was measured on,
// with a rect in that screen's own top-down points. In Rune's
// AppKit path this resolves to the same frame as the global Primary
// rect; the pin keeps the request's display explicit.
Some(id) => {
let (local_x, local_y) = hud_placement::local_rect(placed.top_left, metrics.frame);
overlay.set_display(DisplayTarget::Native(NativeDisplayId::MacOS(id)));
overlay.set_placement(Some(OverlayPlacement::Rect {
x: local_x as f32,
y: local_y as f32,
width,
height,
}));
}
// No screen number: keep the old global rect against the primary,
// the only space Rune documents for a Rect there.
None => {
overlay.set_display(DisplayTarget::Primary);
overlay.set_placement(Some(OverlayPlacement::Rect {
x: x as f32,
y: (primary_top - top) as f32,
width,
height,
}));
}
}
}
}