diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c0d2239d..64bf0226 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -70,6 +70,7 @@ jobs: - { name: 'Redox OS', target: x86_64-unknown-redox, os: ubuntu-latest, } - { name: 'macOS x86_64', target: x86_64-apple-darwin, os: macos-latest, } - { name: 'macOS Aarch64', target: aarch64-apple-darwin, os: macos-latest, } + - { name: 'macOS Private APIs', target: aarch64-apple-darwin, os: macos-latest, options: '--package winit --features=private-apple-apis' } - { name: 'iOS x86_64', target: x86_64-apple-ios, os: macos-latest, } - { name: 'iOS Aarch64', target: aarch64-apple-ios, os: macos-latest, } - { name: 'Web', target: wasm32-unknown-unknown, os: ubuntu-latest, } diff --git a/winit-appkit/Cargo.toml b/winit-appkit/Cargo.toml index 5aa1802a..0f6a1bd9 100644 --- a/winit-appkit/Cargo.toml +++ b/winit-appkit/Cargo.toml @@ -58,6 +58,7 @@ objc2-app-kit = { workspace = true, features = [ "NSTrackingArea", "NSToolbar", "NSView", + "NSVisualEffectView", "NSWindow", "NSWindowScripting", "NSWindowTabGroup", @@ -122,5 +123,5 @@ winit-common = { workspace = true, features = [ winit.workspace = true [package.metadata.docs.rs] -all-features = true +features = ["serde"] targets = ["aarch64-apple-darwin", "x86_64-apple-darwin"] diff --git a/winit-appkit/src/lib.rs b/winit-appkit/src/lib.rs index e8319143..29c96dbf 100644 --- a/winit-appkit/src/lib.rs +++ b/winit-appkit/src/lib.rs @@ -208,6 +208,17 @@ pub trait WindowExtMacOS { /// Getter for the [`WindowExtMacOS::set_fullscreen_auxiliary`]. fn fullscreen_auxiliary(&self) -> bool; + + /// Sets the material drawn behind the window when it is blurred. + /// + /// Takes effect the next time the window is blurred, and immediately if it already is. See + /// [`Window::set_blur`]. + /// + /// [`Window::set_blur`]: winit_core::window::Window::set_blur + fn set_blur_material(&self, blur_material: BlurMaterial); + + /// Getter for the [`WindowExtMacOS::set_blur_material`]. + fn blur_material(&self) -> BlurMaterial; } impl WindowExtMacOS for dyn Window + '_ { @@ -330,6 +341,18 @@ impl WindowExtMacOS for dyn Window + '_ { let window = self.cast_ref::().unwrap(); window.maybe_wait_on_main(|w| w.fullscreen_auxiliary()) } + + #[inline] + fn set_blur_material(&self, blur_material: BlurMaterial) { + let window = self.cast_ref::().unwrap(); + window.maybe_wait_on_main(move |w| w.set_blur_material(blur_material)) + } + + #[inline] + fn blur_material(&self) -> BlurMaterial { + let window = self.cast_ref::().unwrap(); + window.maybe_wait_on_main(|w| w.blur_material()) + } } /// Corresponds to `NSApplicationActivationPolicy`. @@ -375,6 +398,7 @@ pub struct WindowAttributesMacOS { pub(crate) unified_titlebar: bool, pub(crate) panel: bool, pub(crate) fullscreen_auxiliary: bool, + pub(crate) blur_material: BlurMaterial, } impl WindowAttributesMacOS { @@ -385,6 +409,17 @@ impl WindowAttributesMacOS { self } + /// Sets the material drawn behind the window when it is blurred. + /// + /// Has no effect unless the window is blurred, see [`Window::set_blur`]. + /// + /// [`Window::set_blur`]: winit_core::window::Window::set_blur + #[inline] + pub fn with_blur_material(mut self, blur_material: BlurMaterial) -> Self { + self.blur_material = blur_material; + self + } + /// Makes the titlebar transparent and allows the content to appear behind it. #[inline] pub fn with_titlebar_transparent(mut self, titlebar_transparent: bool) -> Self { @@ -506,6 +541,7 @@ impl Default for WindowAttributesMacOS { unified_titlebar: false, panel: false, fullscreen_auxiliary: false, + blur_material: Default::default(), } } } @@ -648,3 +684,59 @@ pub enum OptionAsAlt { #[default] None, } + +/// The material drawn behind a blurred window, corresponding to `NSVisualEffectMaterial`. +/// +/// Only the materials that AppKit renders behind the window are listed. The remaining +/// `NSVisualEffectMaterial` values are meant for opaque backgrounds, and draw a placeholder +/// rather than a blur when used this way. +/// +/// The material determines the tint and translucency of the blur, so the result is not an +/// untinted blur of a chosen radius; AppKit exposes no public API for that. Enable the +/// `private-apple-apis` Cargo feature for the private one, which this setting then no longer +/// affects. +/// +/// See [`Window::set_blur`] for the blur itself. +/// +/// [`Window::set_blur`]: winit_core::window::Window::set_blur +#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] +#[non_exhaustive] +pub enum BlurMaterial { + /// Corresponds to `NSVisualEffectMaterialFullScreenUI`. + /// + /// Tints the least of the available materials, making it the closest to a plain backdrop + /// blur. This is the default. + #[default] + FullScreenUI, + + /// Corresponds to `NSVisualEffectMaterialHUDWindow`. + HudWindow, + + /// Corresponds to `NSVisualEffectMaterialMenu`. + Menu, + + /// Corresponds to `NSVisualEffectMaterialPopover`. + Popover, + + /// Corresponds to `NSVisualEffectMaterialSidebar`. + Sidebar, + + /// Corresponds to `NSVisualEffectMaterialSelection`. + Selection, + + /// Corresponds to `NSVisualEffectMaterialTitlebar`. + Titlebar, + + /// Corresponds to `NSVisualEffectMaterialHeaderView`. + HeaderView, + + /// Corresponds to `NSVisualEffectMaterialToolTip`. + ToolTip, + + /// Corresponds to `NSVisualEffectMaterialUnderWindowBackground`. + /// + /// Tints heavily towards the window's background colour, which can leave the blur barely + /// visible over light content. + UnderWindowBackground, +} diff --git a/winit-appkit/src/view.rs b/winit-appkit/src/view.rs index b97b59ba..64dc7080 100644 --- a/winit-appkit/src/view.rs +++ b/winit-appkit/src/view.rs @@ -154,6 +154,7 @@ define_class!( #[unsafe(super(NSView, NSResponder, NSObject))] #[ivars = ViewState] #[name = "WinitView"] + #[derive(Debug)] pub(super) struct WinitView; /// This documentation attribute makes rustfmt work for some reason? diff --git a/winit-appkit/src/window_delegate.rs b/winit-appkit/src/window_delegate.rs index a7cc2aef..30d61abf 100644 --- a/winit-appkit/src/window_delegate.rs +++ b/winit-appkit/src/window_delegate.rs @@ -19,14 +19,19 @@ use objc2::{ }; use objc2_app_kit::{ NSAppKitVersionNumber, NSAppKitVersionNumber10_12, NSAppearance, NSAppearanceCustomization, - NSAppearanceNameAqua, NSApplication, NSApplicationPresentationOptions, NSBackingStoreType, - NSColor, NSDragOperation, NSDraggingContext, NSDraggingDestination, NSDraggingInfo, - NSDraggingSession, NSDraggingSource, NSPasteboardTypeFileURL, NSPasteboardTypeHTML, - NSPasteboardTypePNG, NSPasteboardTypeSound, NSPasteboardTypeString, NSPasteboardTypeTIFF, - NSRequestUserAttentionType, NSScreen, NSToolbar, NSView, NSViewFrameDidChangeNotification, - NSWindow, NSWindowButton, NSWindowCollectionBehavior, NSWindowDelegate, NSWindowLevel, - NSWindowOcclusionState, NSWindowOrderingMode, NSWindowSharingType, NSWindowStyleMask, - NSWindowTabbingMode, NSWindowTitleVisibility, NSWindowToolbarStyle, + NSAppearanceNameAqua, NSApplication, NSApplicationPresentationOptions, + NSAutoresizingMaskOptions, NSBackingStoreType, NSColor, NSDragOperation, NSDraggingContext, + NSDraggingDestination, NSDraggingInfo, NSDraggingSession, NSDraggingSource, + NSPasteboardTypeFileURL, NSPasteboardTypeHTML, NSPasteboardTypePNG, NSPasteboardTypeSound, + NSPasteboardTypeString, NSPasteboardTypeTIFF, NSRequestUserAttentionType, NSScreen, NSToolbar, + NSView, NSViewFrameDidChangeNotification, NSWindow, NSWindowButton, NSWindowCollectionBehavior, + NSWindowDelegate, NSWindowLevel, NSWindowOcclusionState, NSWindowOrderingMode, + NSWindowSharingType, NSWindowStyleMask, NSWindowTabbingMode, NSWindowTitleVisibility, + NSWindowToolbarStyle, +}; +#[cfg(not(feature = "private-apple-apis"))] +use objc2_app_kit::{ + NSVisualEffectBlendingMode, NSVisualEffectMaterial, NSVisualEffectState, NSVisualEffectView, }; use objc2_core_foundation::{CGFloat, CGPoint}; use objc2_core_graphics::{ @@ -67,7 +72,7 @@ use crate::app_state::DragState; use crate::dnd::{ dnd_action_to_ns_drag_operation, ns_drag_operation_to_dnd_action, preferred_drag_operation, }; -use crate::{OptionAsAlt, WindowAttributesMacOS, WindowExtMacOS}; +use crate::{BlurMaterial, OptionAsAlt, WindowAttributesMacOS, WindowExtMacOS}; #[derive(Debug)] pub(crate) struct State { @@ -76,6 +81,13 @@ pub(crate) struct State { window: Retained, + view: Retained, + + #[cfg(not(feature = "private-apple-apis"))] + blur_view: RefCell>>, + + blur_material: Cell, + // During `windowDidResize`, we use this to only send Moved if the position changed. // // This is expressed in desktop coordinates, and flipped to match Winit's coordinate system. @@ -674,7 +686,7 @@ fn new_window( macos_attrs: &WindowAttributesMacOS, anchored: bool, mtm: MainThreadMarker, -) -> Option> { +) -> Option<(Retained, Retained)> { autoreleasepool(|_| { let screen = match attrs.fullscreen.clone() { Some(Fullscreen::Borderless(Some(monitor))) @@ -878,13 +890,22 @@ fn new_window( view.setWantsLayer(true); } + let content_view = NSView::new(mtm); + window.setContentView(Some(&content_view)); + + view.setFrame(content_view.bounds()); + view.setAutoresizingMask( + NSAutoresizingMaskOptions::ViewWidthSizable + | NSAutoresizingMaskOptions::ViewHeightSizable, + ); + content_view.addSubview(&view); + // Configure the new view as the "key view" for the window - window.setContentView(Some(&view)); window.setInitialFirstResponder(Some(&view)); // Configure the view to send notifications whenever its frame rectangle changes. // - // We explicitly do this _after_ setting the view as the content view of the window, to + // We explicitly do this _after_ adding the view to the window, to // avoid a resize event when creating the window. view.setPostsFrameChangedNotifications(true); // `setPostsFrameChangedNotifications` posts the notification immediately, so register the @@ -905,7 +926,7 @@ fn new_window( window.setBackgroundColor(Some(&NSColor::clearColor())); } - Some(window) + Some((window, view)) }) } @@ -937,7 +958,7 @@ impl WindowDelegate { } } - let window = new_window(app_state, &attrs, &macos_attrs, anchored, mtm) + let (window, view) = new_window(app_state, &attrs, &macos_attrs, anchored, mtm) .ok_or_else(|| os_error!("couldn't create `NSWindow`"))?; match attrs.parent_window() { @@ -983,6 +1004,10 @@ impl WindowDelegate { let delegate = mtm.alloc().set_ivars(State { app_state: Rc::clone(app_state), window: window.retain(), + view, + #[cfg(not(feature = "private-apple-apis"))] + blur_view: RefCell::new(None), + blur_material: Cell::new(macos_attrs.blur_material), previous_position: Cell::new(flip_window_screen_coordinates(window.frame())), previous_scale_factor: Cell::new(scale_factor), surface_resize_increments: Cell::new(surface_resize_increments), @@ -1079,10 +1104,8 @@ impl WindowDelegate { Ok(delegate) } - #[track_caller] pub(super) fn view(&self) -> Retained { - // The view inside WinitWindow should always be set and be `WinitView`. - self.window().contentView().unwrap().downcast().unwrap() + self.ivars().view.clone() } #[track_caller] @@ -1199,8 +1222,44 @@ impl WindowDelegate { }; } - // TODO: Implement blur using public methods somehow? - let _ = blur; + #[cfg(not(feature = "private-apple-apis"))] + { + if !blur { + let installed = self.ivars().blur_view.borrow_mut().take(); + if let Some(installed) = installed { + installed.removeFromSuperview(); + } + return; + } + + if self.ivars().blur_view.borrow().is_some() { + return; + } + + let mtm = MainThreadMarker::from(self); + let view = self.view(); + let content_view = + self.window().contentView().expect("window always has a content view"); + + let new_blur_view = NSVisualEffectView::new(mtm); + new_blur_view.setBlendingMode(NSVisualEffectBlendingMode::BehindWindow); + new_blur_view.setState(NSVisualEffectState::Active); + if let Some(material) = ns_visual_effect_material(self.ivars().blur_material.get()) { + new_blur_view.setMaterial(material); + } + new_blur_view.setFrame(content_view.bounds()); + new_blur_view.setAutoresizingMask( + NSAutoresizingMaskOptions::ViewWidthSizable + | NSAutoresizingMaskOptions::ViewHeightSizable, + ); + content_view.addSubview_positioned_relativeTo( + &new_blur_view, + NSWindowOrderingMode::Below, + Some(&view), + ); + + *self.ivars().blur_view.borrow_mut() = Some(new_blur_view); + } } pub fn set_visible(&self, visible: bool) { @@ -2219,6 +2278,36 @@ fn restore_and_release_display(monitor: &MonitorHandle) { } } +#[cfg(not(feature = "private-apple-apis"))] +fn ns_visual_effect_material(material: BlurMaterial) -> Option { + match material { + BlurMaterial::Titlebar => Some(NSVisualEffectMaterial::Titlebar), + BlurMaterial::Selection => Some(NSVisualEffectMaterial::Selection), + BlurMaterial::Menu => available!(macos = 10.11).then_some(NSVisualEffectMaterial::Menu), + BlurMaterial::Popover => { + available!(macos = 10.11).then_some(NSVisualEffectMaterial::Popover) + }, + BlurMaterial::Sidebar => { + available!(macos = 10.11).then_some(NSVisualEffectMaterial::Sidebar) + }, + BlurMaterial::HeaderView => { + available!(macos = 10.14).then_some(NSVisualEffectMaterial::HeaderView) + }, + BlurMaterial::FullScreenUI => { + available!(macos = 10.14).then_some(NSVisualEffectMaterial::FullScreenUI) + }, + BlurMaterial::HudWindow => { + available!(macos = 10.14).then_some(NSVisualEffectMaterial::HUDWindow) + }, + BlurMaterial::ToolTip => { + available!(macos = 10.14).then_some(NSVisualEffectMaterial::ToolTip) + }, + BlurMaterial::UnderWindowBackground => { + available!(macos = 10.14).then_some(NSVisualEffectMaterial::UnderWindowBackground) + }, + } +} + impl WindowExtMacOS for WindowDelegate { #[inline] fn simple_fullscreen(&self) -> bool { @@ -2369,6 +2458,21 @@ impl WindowExtMacOS for WindowDelegate { self.view().set_option_as_alt(option_as_alt); } + fn set_blur_material(&self, blur_material: BlurMaterial) { + self.ivars().blur_material.set(blur_material); + + #[cfg(not(feature = "private-apple-apis"))] + if let Some(blur_view) = self.ivars().blur_view.borrow().as_ref() { + if let Some(material) = ns_visual_effect_material(blur_material) { + blur_view.setMaterial(material); + } + } + } + + fn blur_material(&self) -> BlurMaterial { + self.ivars().blur_material.get() + } + fn option_as_alt(&self) -> OptionAsAlt { self.view().option_as_alt() } diff --git a/winit-core/src/window.rs b/winit-core/src/window.rs index 455d8f79..0808b76e 100644 --- a/winit-core/src/window.rs +++ b/winit-core/src/window.rs @@ -1073,7 +1073,15 @@ pub trait Window: Any + Send + Sync + fmt::Debug { /// /// ## Platform-specific /// - /// - **macOS**: Must enable the `private-apple-apis` Cargo feature. + /// - **macOS:** Renders a translucent system material behind the window's contents, which is + /// tinted and follows the window's appearance, rather than a blur of a specific radius. Which + /// material is used can be chosen with `WindowAttributesMacOS::with_blur_material` and + /// `WindowExtMacOS::set_blur_material`. The window's `contentView` is a container holding the + /// view returned by `raw-window-handle`, and the material is a sibling behind it. With the + /// `private-apple-apis` Cargo feature enabled, a private API is used instead to apply an + /// untinted backdrop blur of a fixed radius; this can cause App Store rejection. On macOS + /// 10.12 and older, enabling blur makes the window's views layer-backed, which may break the + /// association with an attached `NSOpenGLContext`. /// - **Android / iOS / X11 / Web / Windows:** Unsupported. /// - **Wayland:** Only works with `org_kde_kwin_blur_manager` or /// `ext_background_effect_manager_v1` protocol. diff --git a/winit/src/changelog/unreleased.md b/winit/src/changelog/unreleased.md index 390a69d4..2557176e 100644 --- a/winit/src/changelog/unreleased.md +++ b/winit/src/changelog/unreleased.md @@ -101,6 +101,11 @@ changelog entry. - Updated `windows-sys` to `v0.61`. - On older macOS versions (tested up to 12.7.6), applications now receive mouse movement events for unfocused windows, matching the behavior on other platforms. - On macOS, using the private API `CGSSetWindowBackgroundBlurRadius` for `Window::set_blur` is now disabled by default. It can be re-enabled using the Cargo feature `private-apple-apis`. +- On macOS, `Window::set_blur` is now implemented with the public `NSVisualEffectView` when `private-apple-apis` is disabled, so binaries no longer link `_CGSSetWindowBackgroundBlurRadius`, which the Mac App Store rejects under Guideline 2.5.1. +- On macOS, blurred windows now render a translucent system material rather than an untinted backdrop blur at a fixed radius of 80, and the radius is no longer configurable; enable the `private-apple-apis` Cargo feature to keep the previous implementation, which `--all-features` also enables. +- On macOS, added `BlurMaterial`, `WindowAttributesMacOS::with_blur_material` and `WindowExtMacOS::set_blur_material` to choose which material is drawn behind a blurred window. +- On macOS, the window's `contentView` is now a plain container `NSView` holding winit's view, rather than being winit's view itself; the handle returned by `raw-window-handle` is unchanged. +- On macOS 10.12 and older, enabling blur now makes the window's views layer-backed, which may break the association with an attached `NSOpenGLContext`. ### Removed diff --git a/winit/src/lib.rs b/winit/src/lib.rs index de1ccb5c..c02f2977 100644 --- a/winit/src/lib.rs +++ b/winit/src/lib.rs @@ -196,8 +196,9 @@ //! * `serde`: Enables serialization/deserialization of certain types with [Serde](https://crates.io/crates/serde). //! * `mint`: Enables mint (math interoperability standard types) conversions. //! * `private-apple-apis`: Enables private APIs whose usage might cause rejections from the App -//! Store. Currently enables the use of `CGSSetWindowBackgroundBlurRadius`, commonly used for -//! terminal emulators. +//! Store. Currently switches `Window::set_blur` on macOS to use +//! `CGSSetWindowBackgroundBlurRadius`, which applies an untinted blur of a fixed radius and is +//! commonly used by terminal emulators, instead of the default `NSVisualEffectView` material. //! //! See the [`platform`] module for documentation on platform-specific cargo //! features.