app: cherry-pick rune's pause and sound fixes onto the checkout

Rune comes from app/vendor/rune now, a checkout of 63ad0209 on branch
ported, carrying the four commits of upstream issues 1320 (a pause while
a clip is layered holds the layer's picture and time) and 1325 (a video's
sound is read ahead of the clock and leads it). Both were written against
eb9f1104 and ported across the refactors since. The faults are the first
two and the third in docs/rune-upstream.md; the app's workarounds in
review.rs stay until the fixes arrive upstream.
This commit is contained in:
vhaudiquet committed 2026-11-22 22:16:30 +01:00
1 parent 80fef698ce
commit 5bf262b82b
3795 files changed
+663463 -28

No files matched your search

+15
View File
@@ -0,0 +1,15 @@
[package]
name = "rune-mac"
version = "0.0.1"
edition.workspace = true
license.workspace = true
description = "Small macOS helpers for Rune apps: a remembered window frame, full screen, quiet relaunches with scripts/mac-app, and system notifications (rune-notify)."
[dependencies]
rune-notify = { workspace = true }
[target.'cfg(target_os = "macos")'.dependencies]
objc2 = { workspace = true }
[lints]
workspace = true
+31
View File
@@ -0,0 +1,31 @@
# rune-mac
Small macOS helpers for Rune apps, with Rune's `scripts/mac-app` (see "Relaunching a Mac app"
in `crates/rune/README.md`), which relaunches a rebuilt app in place without its window
blinking or taking focus.
| Helper | What it does |
| --- | --- |
| `launch()` | Call first thing in `main`. When `scripts/mac-app` relaunched the app while it wasn't in front, it starts behind the app in front instead of taking focus. |
| `remember_frame(name) -> bool` | Has AppKit save the window frame under `name` and restore it next launch, so a rebuild's window lands over the old one. Call it from `poll` until it returns true. |
| `saved_size(name) -> Option<(f32, f32)>` | The size `remember_frame(name)` saved, to open the window at (`AppSpec::size`), so the layout doesn't animate to it at launch. |
| `toggle_full_screen()`, `is_full_screen()` | The key window's macOS full screen (the green button, ⌃⌘F). |
| `busy(on)` | Holds `scripts/mac-app`'s relaunch while on, for work a relaunch would lose. |
| `notify` | `rune-notify`, re-exported: system notifications on macOS (`UNUserNotificationCenter`) and Windows (toasts). See its README. |
Off macOS every helper is a no-op: `remember_frame` returns true, `saved_size` returns `None`,
`is_full_screen` returns false, and the rest do nothing.
```rust
fn main() {
rune_mac::launch();
let size = rune_mac::saved_size("Example").unwrap_or((900.0, 640.0));
rune::run(AppSpec::<State> {
poll: Some(|s, _, _| {
if !s.framed { s.framed = rune_mac::remember_frame("Example") }
false
}),
..AppSpec::new("Example", size, State::default, view)
});
}
```
+143
View File
@@ -0,0 +1,143 @@
//! Small macOS helpers for Rune apps. Pair them with Rune's `scripts/mac-app`, which relaunches a
//! rebuilt app without its window blinking or taking focus.
//!
//! Off macOS every helper is a no-op: `remember_frame` returns true (so a `poll` that waits on it
//! stops), `saved_size` returns `None`, `is_full_screen` returns false, and `toggle_full_screen`,
//! `launch` and `busy` do nothing. `notify` is `rune-notify`, which also posts on Windows.
pub use rune_notify as notify;
mod quiet;
pub use quiet::launch;
/// Has AppKit save the app's window frame under `name` and put the next launch's window in the
/// same place, so a rebuild's new window lands exactly over the old one. Call it every frame
/// (from `poll`) until it returns true: the window doesn't exist during `setup`.
#[allow(unsafe_code)]
pub fn remember_frame(name: &str) -> bool {
#[cfg(target_os = "macos")]
// SAFETY: AppKit calls on the main thread (`poll`); `name` is NUL-terminated UTF-8 and every
// `objectAtIndex:` index is `< count`.
unsafe {
use objc2::{class, msg_send, runtime::AnyObject};
let app: *mut AnyObject = msg_send![class!(NSApplication), sharedApplication];
let windows: *mut AnyObject = msg_send![app, windows];
let n: usize = msg_send![windows, count];
let name = std::ffi::CString::new(name).unwrap_or_default();
let name: *mut AnyObject = msg_send![class!(NSString), stringWithUTF8String: name.as_ptr()];
for i in 0..n {
let w: *mut AnyObject = msg_send![windows, objectAtIndex: i];
let _: bool = msg_send![w, setFrameAutosaveName: name];
}
n > 0
}
#[cfg(not(target_os = "macos"))]
{
let _ = name;
true
}
}
/// The key window, else the main window; null with neither.
#[cfg(target_os = "macos")]
#[allow(unsafe_code)]
unsafe fn key_window() -> *mut objc2::runtime::AnyObject {
use objc2::{class, msg_send, runtime::AnyObject};
// SAFETY: called on the AppKit main thread; `sharedApplication`, `keyWindow`, and `mainWindow`
// are standard AppKit selectors returning an `NSWindow *` or null.
unsafe {
let app: *mut AnyObject = msg_send![class!(NSApplication), sharedApplication];
let w: *mut AnyObject = msg_send![app, keyWindow];
if w.is_null() { msg_send![app, mainWindow] } else { w }
}
}
/// Takes the app's key window into macOS full screen, or back out (the green button's
/// ⌃⌘F). Headless, with no window, it does nothing.
#[allow(unsafe_code)]
pub fn toggle_full_screen() {
#[cfg(target_os = "macos")]
// SAFETY: AppKit main-thread call; `toggleFullScreen:` is only sent to a non-null `NSWindow *`
// from `key_window()`, with a null sender.
unsafe {
use objc2::{msg_send, runtime::AnyObject};
let w = key_window();
if !w.is_null() {
let _: () = msg_send![w, toggleFullScreen: std::ptr::null::<AnyObject>()];
}
}
}
/// Whether the app's key window is in macOS full screen.
#[allow(unsafe_code)]
pub fn is_full_screen() -> bool {
#[cfg(target_os = "macos")]
// SAFETY: AppKit main-thread call; `styleMask` is only sent to a non-null `NSWindow *` from
// `key_window()`.
unsafe {
use objc2::msg_send;
let w = key_window();
if !w.is_null() {
let mask: usize = msg_send![w, styleMask];
// NSWindowStyleMaskFullScreen
return mask & (1 << 14) != 0;
}
}
false
}
/// The size `remember_frame(name)` saved, in points, to open the window at. Applying the saved
/// frame after the first layout resizes it, and the layout animates to the new size at launch.
#[allow(unsafe_code)]
pub fn saved_size(name: &str) -> Option<(f32, f32)> {
#[cfg(target_os = "macos")]
// SAFETY: `key` is NUL-terminated UTF-8; `NSUserDefaults` is thread-safe, `value` is checked
// non-null, and `UTF8String` returns a NUL-terminated C string alive for `value`.
unsafe {
use objc2::{class, msg_send, runtime::AnyObject};
let key = std::ffi::CString::new(format!("NSWindow Frame {name}")).ok()?;
let key: *mut AnyObject = msg_send![class!(NSString), stringWithUTF8String: key.as_ptr()];
let defaults: *mut AnyObject = msg_send![class!(NSUserDefaults), standardUserDefaults];
let value: *mut AnyObject = msg_send![defaults, stringForKey: key];
if value.is_null() {
return None;
}
let utf8: *const std::ffi::c_char = msg_send![value, UTF8String];
parse_size(std::ffi::CStr::from_ptr(utf8).to_str().ok()?)
}
#[cfg(not(target_os = "macos"))]
{
let _ = name;
None
}
}
/// AppKit's frame string, "x y width height" then the screen's: the width and height.
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
fn parse_size(frame: &str) -> Option<(f32, f32)> {
let mut n = frame.split_whitespace().skip(2).map(str::parse::<f32>);
let (w, h) = (n.next()?.ok()?, n.next()?.ok()?);
(w >= 1.0 && h >= 1.0).then_some((w, h))
}
#[cfg(test)]
mod tests;
/// Holds `scripts/mac-app`'s relaunch while `on`, for work a relaunch would lose (a recording in
/// progress, say). The marker is this process's pid in `~/Library/Caches/mac-app/busy/`, so only
/// this process holds the swap and a crash can't hold it forever.
pub fn busy(on: bool) {
#[cfg(not(target_os = "macos"))]
let _ = on;
#[cfg(target_os = "macos")]
{
let Some(home) = std::env::var_os("HOME") else { return };
let dir = std::path::PathBuf::from(home).join("Library/Caches/mac-app/busy");
let path = dir.join(std::process::id().to_string());
if on {
std::fs::create_dir_all(&dir).ok();
std::fs::write(path, "").ok();
} else {
std::fs::remove_file(path).ok();
}
}
}
+61
View File
@@ -0,0 +1,61 @@
//! Relaunching behind the app in front. winit activates every app it starts, `open -g` or not, so
//! an unattended rebuild took focus, and a window manager that follows focus switched to the
//! app's workspace. `scripts/mac-app` launches with `MAC_APP_QUIET` set when
//! the app wasn't in front, and `launch` keeps the app from activating while it starts.
#![allow(unsafe_code)]
const VAR: &str = "MAC_APP_QUIET";
/// Call first thing in `main`, before the event loop.
pub fn launch() {
if std::env::var_os(VAR).is_none() {
return;
}
// SAFETY: called first in `main`, before the app starts any thread.
unsafe { std::env::remove_var(VAR) };
#[cfg(target_os = "macos")]
// SAFETY: called on the main thread at launch before the event loop; `sharedApplication` and
// `setActivationPolicy:` are standard AppKit selectors.
unsafe {
use objc2::{class, msg_send, runtime::AnyObject};
let app: *mut AnyObject = msg_send![class!(NSApplication), sharedApplication];
// NSApplicationActivationPolicyProhibited: winit's activation at launch does nothing.
let _: bool = msg_send![app, setActivationPolicy: 2isize];
after(0);
}
}
/// Launched that way, macOS hides the app within a few hundred milliseconds. Once it has (or
/// after 5 s), the app turns regular again and shows its window without activating, so it lands
/// behind whatever is in front.
#[cfg(target_os = "macos")]
extern "C" fn check(tries: *mut std::ffi::c_void) {
// SAFETY: dispatched onto the main queue by `after`, so AppKit main-thread calls are valid;
// `tries` is an integer count round-tripped through the context pointer, never dereferenced.
unsafe {
use objc2::{class, msg_send, runtime::AnyObject};
let app: *mut AnyObject = msg_send![class!(NSApplication), sharedApplication];
let hidden: bool = msg_send![app, isHidden];
let tries = tries as usize;
if !hidden && tries < 20 {
return after(tries + 1);
}
let _: bool = msg_send![app, setActivationPolicy: 0isize];
let _: () = msg_send![app, unhideWithoutActivation];
}
}
#[cfg(target_os = "macos")]
fn after(tries: usize) {
// SAFETY: `_dispatch_main_q` is libdispatch's static main queue; `check` matches the
// `dispatch_function_t` ABI and treats `tries` purely as an integer count.
unsafe { dispatch_after_f(dispatch_time(0, 250_000_000), &raw const _dispatch_main_q, tries as *mut std::ffi::c_void, check) };
}
#[cfg(target_os = "macos")]
unsafe extern "C" {
static _dispatch_main_q: std::ffi::c_void;
fn dispatch_time(when: u64, delta: i64) -> u64;
fn dispatch_after_f(when: u64, queue: *const std::ffi::c_void, context: *mut std::ffi::c_void, work: extern "C" fn(*mut std::ffi::c_void));
}
+21
View File
@@ -0,0 +1,21 @@
#[test]
fn parses_appkits_frame_string() {
assert_eq!(crate::parse_size("1645 0 716 1084 0 0 1728 1084 "), Some((716.0, 1084.0)));
assert_eq!(crate::parse_size("12 30"), None);
assert_eq!(crate::parse_size(""), None);
}
#[cfg(target_os = "macos")]
#[test]
#[allow(unsafe_code)]
fn busy_holds_a_marker_named_for_this_process() {
let home = std::env::temp_dir().join(format!("rune-mac-busy-{}", std::process::id()));
// SAFETY: the only test that reads or writes the environment.
unsafe { std::env::set_var("HOME", &home) };
let marker = home.join("Library/Caches/mac-app/busy").join(std::process::id().to_string());
crate::busy(true);
assert!(marker.exists());
crate::busy(false);
assert!(!marker.exists());
std::fs::remove_dir_all(home).ok();
}