feat(client): redesign native UI, themes, settings and avatars
Separate conversation drafts and voice view state, add native settings and restricted CSS themes, implement validated avatar cropping, and refresh dependencies with documented desktop compatibility backports.
This commit is contained in:
parent
44d284a568
commit
8e5ab56611
276 changed files with 53546 additions and 3399 deletions
26
patches/i-slint-backend-winit/ios/clipboard.rs
vendored
Normal file
26
patches/i-slint-backend-winit/ios/clipboard.rs
vendored
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
// Copyright © SixtyFPS GmbH <info@slint.dev>
|
||||
// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0
|
||||
|
||||
use crate::clipboard::ClipboardProvider;
|
||||
use objc2_foundation::NSString;
|
||||
use objc2_ui_kit::UIPasteboard;
|
||||
|
||||
pub(crate) struct UiPasteboardClipboard;
|
||||
|
||||
impl ClipboardProvider for UiPasteboardClipboard {
|
||||
fn get_contents(
|
||||
&mut self,
|
||||
) -> Result<String, Box<dyn std::error::Error + Send + Sync + 'static>> {
|
||||
let pasteboard = UIPasteboard::generalPasteboard();
|
||||
Ok(unsafe { pasteboard.string() }.map(|s| s.to_string()).unwrap_or_default())
|
||||
}
|
||||
|
||||
fn set_contents(
|
||||
&mut self,
|
||||
data: String,
|
||||
) -> Result<(), Box<dyn std::error::Error + Send + Sync + 'static>> {
|
||||
let pasteboard = UIPasteboard::generalPasteboard();
|
||||
unsafe { pasteboard.setString(Some(&NSString::from_str(&data))) };
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
42
patches/i-slint-backend-winit/ios/color_scheme.rs
vendored
Normal file
42
patches/i-slint-backend-winit/ios/color_scheme.rs
vendored
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
// Copyright © SixtyFPS GmbH <info@slint.dev>
|
||||
// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0
|
||||
|
||||
// Stopgap until winit ships iOS appearance support (rust-windowing/winit#4570).
|
||||
// Once that lands, `winit_window.theme()` and `WindowEvent::ThemeChanged` will
|
||||
// work on iOS and this whole module — plus the `ios_color_scheme_observer`
|
||||
// wiring in winitwindowadapter.rs — can be deleted.
|
||||
|
||||
use std::rc::Weak;
|
||||
|
||||
use objc2::ClassType;
|
||||
use objc2_ui_kit::{
|
||||
UITraitEnvironment as _, UITraitUserInterfaceStyle, UIUserInterfaceStyle, UIView,
|
||||
};
|
||||
|
||||
use i_slint_core::items::ColorScheme;
|
||||
|
||||
use super::trait_observer::{TraitChangeObserver, install_trait_change_observer};
|
||||
use crate::winitwindowadapter::WinitWindowAdapter;
|
||||
|
||||
fn style_to_color_scheme(style: UIUserInterfaceStyle) -> ColorScheme {
|
||||
match style {
|
||||
UIUserInterfaceStyle::Dark => ColorScheme::Dark,
|
||||
UIUserInterfaceStyle::Light => ColorScheme::Light,
|
||||
_ => ColorScheme::Unknown,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn current_color_scheme(view: &UIView) -> ColorScheme {
|
||||
style_to_color_scheme(unsafe { view.traitCollection().userInterfaceStyle() })
|
||||
}
|
||||
|
||||
pub(crate) fn install_color_scheme_observer(
|
||||
view: &UIView,
|
||||
adapter: Weak<WinitWindowAdapter>,
|
||||
) -> Option<TraitChangeObserver> {
|
||||
install_trait_change_observer(view, UITraitUserInterfaceStyle::class(), move |env| {
|
||||
let Some(adapter) = adapter.upgrade() else { return };
|
||||
let scheme = style_to_color_scheme(unsafe { env.traitCollection().userInterfaceStyle() });
|
||||
adapter.set_color_scheme(scheme);
|
||||
})
|
||||
}
|
||||
43
patches/i-slint-backend-winit/ios/font_size.rs
vendored
Normal file
43
patches/i-slint-backend-winit/ios/font_size.rs
vendored
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
// Copyright © SixtyFPS GmbH <info@slint.dev>
|
||||
// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0
|
||||
|
||||
// Feeds the system's preferred body text size (Dynamic Type) into the
|
||||
// SlintContext, where it serves as the default font size for windows that
|
||||
// don't set `default-font-size` themselves (and as the basis for `rem`).
|
||||
|
||||
use std::rc::Weak;
|
||||
|
||||
use objc2::ClassType;
|
||||
use objc2_ui_kit::{
|
||||
UIFont, UIFontTextStyleBody, UITraitCollection, UITraitEnvironment as _,
|
||||
UITraitPreferredContentSizeCategory, UIView,
|
||||
};
|
||||
|
||||
use i_slint_core::lengths::LogicalLength;
|
||||
|
||||
use super::trait_observer::{TraitChangeObserver, install_trait_change_observer};
|
||||
use crate::winitwindowadapter::WinitWindowAdapter;
|
||||
|
||||
/// Returns the preferred size for body text under the given trait collection's
|
||||
/// content size category. iOS points map 1:1 to Slint's logical pixels.
|
||||
fn body_font_size(traits: &UITraitCollection) -> LogicalLength {
|
||||
let font = UIFont::preferredFontForTextStyle_compatibleWithTraitCollection(
|
||||
unsafe { UIFontTextStyleBody },
|
||||
Some(traits),
|
||||
);
|
||||
LogicalLength::new(unsafe { font.pointSize() } as f32)
|
||||
}
|
||||
|
||||
pub(crate) fn current_default_font_size(view: &UIView) -> LogicalLength {
|
||||
body_font_size(&view.traitCollection())
|
||||
}
|
||||
|
||||
pub(crate) fn install_font_size_observer(
|
||||
view: &UIView,
|
||||
adapter: Weak<WinitWindowAdapter>,
|
||||
) -> Option<TraitChangeObserver> {
|
||||
install_trait_change_observer(view, UITraitPreferredContentSizeCategory::class(), move |env| {
|
||||
let Some(adapter) = adapter.upgrade() else { return };
|
||||
adapter.set_platform_default_font_size(body_font_size(&env.traitCollection()));
|
||||
})
|
||||
}
|
||||
151
patches/i-slint-backend-winit/ios/keyboard_animator.rs
vendored
Normal file
151
patches/i-slint-backend-winit/ios/keyboard_animator.rs
vendored
Normal file
|
|
@ -0,0 +1,151 @@
|
|||
// Copyright © SixtyFPS GmbH <info@slint.dev>
|
||||
// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0
|
||||
|
||||
// cSpell: ignore Subview Superview
|
||||
use std::cell::{OnceCell, RefCell};
|
||||
|
||||
use block2::RcBlock;
|
||||
use objc2::{DefinedClass, MainThreadMarker, MainThreadOnly, define_class, msg_send, rc::Retained};
|
||||
use objc2_foundation::{NSDefaultRunLoopMode, NSObject, NSObjectProtocol, NSRect, NSRunLoop};
|
||||
use objc2_quartz_core::{CADisplayLink, CATransaction};
|
||||
use objc2_ui_kit::{UIView, UIViewAnimating as _, UIViewAnimationCurve, UIViewPropertyAnimator};
|
||||
|
||||
struct DisplayLinkTargetIvars {
|
||||
view: Retained<UIView>,
|
||||
callback: Box<dyn Fn(NSRect)>,
|
||||
animator: RefCell<Option<Retained<UIViewPropertyAnimator>>>,
|
||||
display_link: OnceCell<Retained<CADisplayLink>>,
|
||||
}
|
||||
|
||||
define_class!(
|
||||
#[unsafe(super = NSObject)]
|
||||
#[thread_kind = MainThreadOnly]
|
||||
#[ivars = DisplayLinkTargetIvars]
|
||||
struct DisplayLinkTarget;
|
||||
|
||||
unsafe impl NSObjectProtocol for DisplayLinkTarget {}
|
||||
|
||||
impl DisplayLinkTarget {
|
||||
#[unsafe(method(tick:))]
|
||||
fn tick(&self, display_link: &CADisplayLink) {
|
||||
let this = self.ivars();
|
||||
if let Some(layer) = unsafe { this.view.layer().presentationLayer() } {
|
||||
(this.callback)(layer.frame());
|
||||
}
|
||||
let mut animator_ref = this.animator.borrow_mut();
|
||||
if let Some(false) = animator_ref.as_ref().map(|animator| animator.isRunning()) {
|
||||
display_link.setPaused(true);
|
||||
*animator_ref = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
impl DisplayLinkTarget {
|
||||
fn new(
|
||||
mtm: MainThreadMarker,
|
||||
view: Retained<UIView>,
|
||||
callback: impl Fn(NSRect) + 'static,
|
||||
) -> Retained<Self> {
|
||||
let this = Self::alloc(mtm).set_ivars(DisplayLinkTargetIvars {
|
||||
view,
|
||||
callback: Box::new(callback),
|
||||
animator: Default::default(),
|
||||
display_link: OnceCell::new(),
|
||||
});
|
||||
unsafe { msg_send![super(this), init] }
|
||||
}
|
||||
|
||||
fn set_display_link(&self, display_link: Retained<CADisplayLink>) {
|
||||
self.ivars().display_link.set(display_link).unwrap();
|
||||
}
|
||||
|
||||
fn stop(&self) {
|
||||
let ivars = self.ivars();
|
||||
ivars.display_link.get().unwrap().setPaused(true);
|
||||
if let Some(animator) = ivars.animator.borrow_mut().take() {
|
||||
animator.stopAnimation(true);
|
||||
}
|
||||
}
|
||||
|
||||
fn start(&self, animator: Retained<UIViewPropertyAnimator>) {
|
||||
let ivars = self.ivars();
|
||||
animator.startAnimation();
|
||||
if let Some(old_animator) = ivars.animator.borrow_mut().replace(animator) {
|
||||
old_animator.stopAnimation(true);
|
||||
}
|
||||
ivars.display_link.get().unwrap().setPaused(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// A helper to sample keyboard animation curves.
|
||||
/// Since the iOS keyboard animation is not directly accessible, we create a hidden UIView
|
||||
/// and animate its frame using the same parameters as the keyboard animation.
|
||||
/// The animation curve used by iOS is private and not documented, but using UIViewPropertyAnimator
|
||||
/// with the same duration and curve produces identical results.
|
||||
pub(crate) struct KeyboardCurveSampler {
|
||||
view: Retained<UIView>,
|
||||
target: Retained<DisplayLinkTarget>,
|
||||
mtm: MainThreadMarker,
|
||||
}
|
||||
|
||||
impl KeyboardCurveSampler {
|
||||
pub(crate) fn new(content_view: &UIView, sampler: impl Fn(NSRect) + 'static) -> Self {
|
||||
let mtm = MainThreadMarker::new().expect("Must be created on main thread");
|
||||
let view = UIView::new(mtm);
|
||||
content_view.addSubview(&view);
|
||||
|
||||
let target = DisplayLinkTarget::new(mtm, view.clone(), sampler);
|
||||
let display_link =
|
||||
unsafe { CADisplayLink::displayLinkWithTarget_selector(&target, objc2::sel!(tick:)) };
|
||||
|
||||
unsafe {
|
||||
display_link.addToRunLoop_forMode(&NSRunLoop::currentRunLoop(), NSDefaultRunLoopMode);
|
||||
}
|
||||
|
||||
display_link.setPaused(true);
|
||||
target.set_display_link(display_link);
|
||||
|
||||
Self { view, target, mtm }
|
||||
}
|
||||
|
||||
pub(crate) fn start(
|
||||
&self,
|
||||
duration: f64,
|
||||
curve: UIViewAnimationCurve,
|
||||
begin: NSRect,
|
||||
end: NSRect,
|
||||
) {
|
||||
CATransaction::begin();
|
||||
CATransaction::setDisableActions(true);
|
||||
self.target.stop();
|
||||
self.view.setFrame(begin);
|
||||
CATransaction::commit();
|
||||
|
||||
let view = self.view.clone();
|
||||
let animations = RcBlock::new(move || {
|
||||
view.setFrame(end);
|
||||
});
|
||||
|
||||
let animator = UIViewPropertyAnimator::initWithDuration_curve_animations(
|
||||
UIViewPropertyAnimator::alloc(self.mtm),
|
||||
duration, // duration is already in seconds
|
||||
curve,
|
||||
Some(&animations),
|
||||
);
|
||||
|
||||
self.target.start(animator);
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for DisplayLinkTargetIvars {
|
||||
fn drop(&mut self) {
|
||||
if let Some(display_link) = self.display_link.get() {
|
||||
display_link.invalidate();
|
||||
}
|
||||
if let Some(animator) = self.animator.borrow_mut().take() {
|
||||
animator.stopAnimation(true);
|
||||
}
|
||||
self.view.removeFromSuperview();
|
||||
}
|
||||
}
|
||||
172
patches/i-slint-backend-winit/ios/scene.rs
vendored
Normal file
172
patches/i-slint-backend-winit/ios/scene.rs
vendored
Normal file
|
|
@ -0,0 +1,172 @@
|
|||
// Copyright © SixtyFPS GmbH <info@slint.dev>
|
||||
// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0
|
||||
|
||||
// The scene delegate that apps name in their `UIApplicationSceneManifest`, so
|
||||
// that they adopt the UIScene lifecycle. iOS 27 aborts an app that connects a
|
||||
// scene without adopting it, and UIKit decides adoption from the manifest's
|
||||
// `UISceneConfigurations` alone: a delegate installed at runtime is too late.
|
||||
//
|
||||
// A window scene owns the windows drawn on its screen, so the windows winit
|
||||
// creates have to be handed to the scene. winit may create a window before or
|
||||
// after UIKit connects the scene, so both orders attach it.
|
||||
//
|
||||
// Apple's TN3187 describes the migration and the manifest keys:
|
||||
// https://developer.apple.com/documentation/technotes/tn3187-migrating-to-the-uikit-scene-based-life-cycle
|
||||
//
|
||||
// None of this is specific to Slint, so it belongs next to the windows winit
|
||||
// creates.
|
||||
// TODO: Upstream it when upgrading to the next winit version.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::collections::HashMap;
|
||||
use std::ptr::NonNull;
|
||||
use std::rc::Weak;
|
||||
|
||||
use block2::RcBlock;
|
||||
use objc2::rc::Retained;
|
||||
use objc2::runtime::ProtocolObject;
|
||||
use objc2::{ClassType as _, MainThreadMarker, MainThreadOnly, Message as _, define_class};
|
||||
use objc2_foundation::{
|
||||
NSNotification, NSNotificationCenter, NSObject, NSObjectProtocol, NSString,
|
||||
};
|
||||
use objc2_ui_kit::{
|
||||
UIApplication, UISceneDelegate, UISceneWillConnectNotification, UIView, UIWindow,
|
||||
UIWindowScene, UIWindowSceneDelegate, UIWindowSceneSessionRoleApplication,
|
||||
};
|
||||
use winit::window::WindowId;
|
||||
|
||||
use crate::winitwindowadapter::WinitWindowAdapter;
|
||||
|
||||
define_class!(
|
||||
#[unsafe(super = NSObject)]
|
||||
#[thread_kind = MainThreadOnly]
|
||||
#[name = "SlintWindowSceneDelegate"]
|
||||
struct SlintWindowSceneDelegate;
|
||||
|
||||
unsafe impl NSObjectProtocol for SlintWindowSceneDelegate {}
|
||||
|
||||
// UIKit only needs this class to exist and to conform. The windows are
|
||||
// attached from `register_scene_notifications`, which can reach them.
|
||||
unsafe impl UISceneDelegate for SlintWindowSceneDelegate {}
|
||||
|
||||
unsafe impl UIWindowSceneDelegate for SlintWindowSceneDelegate {}
|
||||
);
|
||||
|
||||
/// Attaches the window hosting `view` to the app's window scene, for windows
|
||||
/// created after the scene connected. A window created before that is attached
|
||||
/// by [`register_scene_notifications`].
|
||||
pub(crate) fn attach_window_to_scene(view: &UIView) {
|
||||
if let Some(mtm) = MainThreadMarker::new()
|
||||
&& let Some(window_scene) = window_scene(mtm)
|
||||
&& let Some(window) = view.window()
|
||||
{
|
||||
attach(&window, &window_scene);
|
||||
}
|
||||
}
|
||||
|
||||
/// The `UIView` winit renders into.
|
||||
pub(crate) fn content_view(winit_window: &winit::window::Window) -> Retained<UIView> {
|
||||
use raw_window_handle::HasWindowHandle as _;
|
||||
|
||||
let raw_window_handle::RawWindowHandle::UiKit(handle) = winit_window
|
||||
.window_handle()
|
||||
.expect("a winit window on iOS always has a window handle")
|
||||
.as_raw()
|
||||
else {
|
||||
unreachable!("winit hands out UIKit window handles on iOS")
|
||||
};
|
||||
unsafe { &*(handle.ui_view.as_ptr() as *const UIView) }.retain()
|
||||
}
|
||||
|
||||
/// Keeps the scene-connection observer alive. Dropping it stops attaching
|
||||
/// windows to the scenes that connect afterwards.
|
||||
pub(crate) struct SceneLifecycle(Retained<ProtocolObject<dyn NSObjectProtocol>>);
|
||||
|
||||
impl Drop for SceneLifecycle {
|
||||
fn drop(&mut self) {
|
||||
unsafe { NSNotificationCenter::defaultCenter().removeObserver(self.0.as_ref()) };
|
||||
}
|
||||
}
|
||||
|
||||
/// Puts everything the UIScene lifecycle needs in place: the delegate class the
|
||||
/// app's `UIApplicationSceneManifest` names, and the observer that attaches the
|
||||
/// windows winit created before the scene connected. Such a window belongs to
|
||||
/// no scene, which keeps it out of `UIApplication.windows` and so out of reach
|
||||
/// of the delegate.
|
||||
///
|
||||
/// Call this before `UIApplicationMain`, which is where UIKit looks the class up
|
||||
/// and connects the first scene.
|
||||
pub(crate) fn install_scene_lifecycle(
|
||||
active_windows: Weak<RefCell<HashMap<WindowId, Weak<WinitWindowAdapter>>>>,
|
||||
) -> SceneLifecycle {
|
||||
// UIKit looks the delegate up by the name in the manifest, so the class has
|
||||
// to be registered with the runtime by then.
|
||||
let _ = SlintWindowSceneDelegate::class();
|
||||
|
||||
let block = RcBlock::new(move |notification: NonNull<NSNotification>| {
|
||||
let Some(active_windows) = active_windows.upgrade() else { return };
|
||||
let Some(window_scene) = unsafe { notification.as_ref() }
|
||||
.object()
|
||||
.and_then(|scene| scene.downcast::<UIWindowScene>().ok())
|
||||
else {
|
||||
return;
|
||||
};
|
||||
if !is_app_scene(&window_scene) {
|
||||
return;
|
||||
}
|
||||
let active_windows = active_windows.borrow();
|
||||
for adapter in active_windows.values().filter_map(Weak::upgrade) {
|
||||
let Some(window) = adapter
|
||||
.winit_window()
|
||||
.map(|winit_window| content_view(&winit_window))
|
||||
.and_then(|view| view.window())
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
// A hidden window belongs to whoever hid it, and attaching it here
|
||||
// would put it on screen.
|
||||
if !window.isHidden() {
|
||||
attach(&window, &window_scene);
|
||||
}
|
||||
}
|
||||
});
|
||||
// Pass no queue, so that the block runs while the scene connects rather than
|
||||
// a run loop turn later. UIKit posts this on the main thread.
|
||||
SceneLifecycle(unsafe {
|
||||
NSNotificationCenter::defaultCenter().addObserverForName_object_queue_usingBlock(
|
||||
Some(UISceneWillConnectNotification),
|
||||
None,
|
||||
None,
|
||||
&block,
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
/// The scene that Slint's windows live on. A Slint app declares a single scene
|
||||
/// configuration, so the one connected application scene is it.
|
||||
fn window_scene(mtm: MainThreadMarker) -> Option<Retained<UIWindowScene>> {
|
||||
UIApplication::sharedApplication(mtm)
|
||||
.connectedScenes()
|
||||
.iter()
|
||||
.filter_map(|scene| scene.downcast_ref::<UIWindowScene>().map(UIWindowScene::retain))
|
||||
.find(|scene| is_app_scene(scene))
|
||||
}
|
||||
|
||||
/// The system connects window scenes of its own next to the app's.
|
||||
/// An iOS app running on macOS gets one with the role
|
||||
/// `FUWindowSceneSessionRoleSystemUI`, after the app's scene.
|
||||
/// A window attached to it never reaches the screen.
|
||||
fn is_app_scene(scene: &UIWindowScene) -> bool {
|
||||
let application_role: &NSString = unsafe { UIWindowSceneSessionRoleApplication };
|
||||
*scene.session().role() == *application_role
|
||||
}
|
||||
|
||||
fn attach(window: &UIWindow, window_scene: &UIWindowScene) {
|
||||
if window.windowScene().as_deref() == Some(window_scene) {
|
||||
return;
|
||||
}
|
||||
window.setWindowScene(Some(window_scene));
|
||||
// winit already made the window visible, but a window without a scene never
|
||||
// reached the screen.
|
||||
window.makeKeyAndVisible();
|
||||
}
|
||||
63
patches/i-slint-backend-winit/ios/trait_observer.rs
vendored
Normal file
63
patches/i-slint-backend-winit/ios/trait_observer.rs
vendored
Normal file
|
|
@ -0,0 +1,63 @@
|
|||
// Copyright © SixtyFPS GmbH <info@slint.dev>
|
||||
// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0
|
||||
|
||||
// Shared scaffolding for observing UIKit trait changes (color scheme, content
|
||||
// size category, ...) on a view. Callers pass the trait class to watch and a
|
||||
// plain closure; the block plumbing and (de)registration live here.
|
||||
|
||||
use std::ptr::NonNull;
|
||||
|
||||
use block2::RcBlock;
|
||||
use objc2::{
|
||||
Message, available, msg_send,
|
||||
rc::Retained,
|
||||
runtime::{AnyClass, ProtocolObject},
|
||||
};
|
||||
use objc2_foundation::NSArray;
|
||||
use objc2_ui_kit::{
|
||||
UITraitChangeObservable, UITraitChangeRegistration, UITraitCollection, UITraitEnvironment,
|
||||
UIView,
|
||||
};
|
||||
|
||||
pub(crate) struct TraitChangeObserver {
|
||||
view: Retained<UIView>,
|
||||
registration: Retained<ProtocolObject<dyn UITraitChangeRegistration>>,
|
||||
}
|
||||
|
||||
impl Drop for TraitChangeObserver {
|
||||
fn drop(&mut self) {
|
||||
self.view.unregisterForTraitChanges(&self.registration);
|
||||
}
|
||||
}
|
||||
|
||||
/// Invokes `handler` with the changed trait environment whenever `trait_class`
|
||||
/// changes on `view`. `registerForTraitChanges:withHandler:` is iOS 17+; on older
|
||||
/// iOS this returns `None` and callers fall back to their initial one-shot query.
|
||||
pub(crate) fn install_trait_change_observer(
|
||||
view: &UIView,
|
||||
trait_class: &AnyClass,
|
||||
handler: impl Fn(&ProtocolObject<dyn UITraitEnvironment>) + 'static,
|
||||
) -> Option<TraitChangeObserver> {
|
||||
if !available!(ios = 17.0) {
|
||||
return None;
|
||||
}
|
||||
|
||||
let handler = RcBlock::new(
|
||||
move |env: NonNull<ProtocolObject<dyn UITraitEnvironment>>,
|
||||
_prev: NonNull<UITraitCollection>| {
|
||||
handler(unsafe { env.as_ref() });
|
||||
},
|
||||
);
|
||||
|
||||
let traits: Retained<NSArray<AnyClass>> = NSArray::from_slice(&[trait_class]);
|
||||
|
||||
let registration: Retained<ProtocolObject<dyn UITraitChangeRegistration>> = unsafe {
|
||||
msg_send![
|
||||
view,
|
||||
registerForTraitChanges: &*traits,
|
||||
withHandler: &*handler,
|
||||
]
|
||||
};
|
||||
|
||||
Some(TraitChangeObserver { view: view.retain(), registration })
|
||||
}
|
||||
139
patches/i-slint-backend-winit/ios/virtual_keyboard.rs
vendored
Normal file
139
patches/i-slint-backend-winit/ios/virtual_keyboard.rs
vendored
Normal file
|
|
@ -0,0 +1,139 @@
|
|||
// Copyright © SixtyFPS GmbH <info@slint.dev>
|
||||
// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0
|
||||
|
||||
use std::{cell::RefCell, collections::HashMap, ptr::NonNull, rc::Weak};
|
||||
|
||||
use block2::RcBlock;
|
||||
use objc2_foundation::{
|
||||
NSNotification, NSNotificationCenter, NSNumber, NSOperationQueue, NSRect, NSValue,
|
||||
};
|
||||
use objc2_ui_kit::{UICoordinateSpace, UIScreen, UIViewAnimationCurve};
|
||||
use raw_window_handle::HasWindowHandle;
|
||||
use winit::window::WindowId;
|
||||
|
||||
use crate::winitwindowadapter::WinitWindowAdapter;
|
||||
|
||||
pub(crate) struct KeyboardNotifications(
|
||||
[objc2::rc::Retained<objc2::runtime::ProtocolObject<dyn objc2_foundation::NSObjectProtocol>>;
|
||||
3],
|
||||
);
|
||||
|
||||
impl Drop for KeyboardNotifications {
|
||||
fn drop(&mut self) {
|
||||
for notification_object in &self.0 {
|
||||
unsafe {
|
||||
objc2_foundation::NSNotificationCenter::defaultCenter()
|
||||
.removeObserver(notification_object.as_ref());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn register_keyboard_notifications(
|
||||
active_windows: Weak<RefCell<HashMap<WindowId, Weak<WinitWindowAdapter>>>>,
|
||||
) -> KeyboardNotifications {
|
||||
let event_block = RcBlock::new(move |notification: NonNull<NSNotification>| {
|
||||
if let Some(active_windows) = active_windows.upgrade() {
|
||||
handle_keyboard_notification(
|
||||
unsafe { notification.as_ref() },
|
||||
active_windows.borrow().values(),
|
||||
);
|
||||
}
|
||||
});
|
||||
let default_center = NSNotificationCenter::defaultCenter();
|
||||
let main_queue = NSOperationQueue::mainQueue();
|
||||
KeyboardNotifications(unsafe {
|
||||
[
|
||||
objc2_ui_kit::UIKeyboardWillShowNotification,
|
||||
objc2_ui_kit::UIKeyboardWillHideNotification,
|
||||
objc2_ui_kit::UIKeyboardWillChangeFrameNotification,
|
||||
]
|
||||
.map(|name| {
|
||||
default_center.addObserverForName_object_queue_usingBlock(
|
||||
Some(name),
|
||||
None,
|
||||
Some(&main_queue),
|
||||
&event_block,
|
||||
)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
fn rect_intersects(r1: NSRect, r2: NSRect) -> bool {
|
||||
r1.origin.x < r2.origin.x + r2.size.width
|
||||
&& r1.origin.x + r1.size.width > r2.origin.x
|
||||
&& r1.origin.y < r2.origin.y + r2.size.height
|
||||
&& r1.origin.y + r1.size.height > r2.origin.y
|
||||
}
|
||||
|
||||
fn handle_keyboard_notification<'a>(
|
||||
notification: &NSNotification,
|
||||
windows: impl IntoIterator<Item = &'a Weak<WinitWindowAdapter>>,
|
||||
) -> Option<()> {
|
||||
let user_info = notification.userInfo()?;
|
||||
let is_local = user_info
|
||||
.objectForKey(unsafe { objc2_ui_kit::UIKeyboardIsLocalUserInfoKey })?
|
||||
.downcast::<NSNumber>()
|
||||
.ok()?
|
||||
.as_bool();
|
||||
if !is_local {
|
||||
return Some(());
|
||||
}
|
||||
let screen = notification.object()?.downcast::<UIScreen>().ok()?;
|
||||
let coordinate_space = screen.coordinateSpace();
|
||||
|
||||
let frame_begin = unsafe {
|
||||
user_info
|
||||
.objectForKey(objc2_ui_kit::UIKeyboardFrameBeginUserInfoKey)?
|
||||
.downcast::<NSValue>()
|
||||
.ok()?
|
||||
.rectValue()
|
||||
};
|
||||
let frame_end = unsafe {
|
||||
user_info
|
||||
.objectForKey(objc2_ui_kit::UIKeyboardFrameEndUserInfoKey)?
|
||||
.downcast::<NSValue>()
|
||||
.ok()?
|
||||
.rectValue()
|
||||
};
|
||||
let animation_duration = user_info
|
||||
.objectForKey(unsafe { objc2_ui_kit::UIKeyboardAnimationDurationUserInfoKey })?
|
||||
.downcast::<NSNumber>()
|
||||
.ok()?
|
||||
.as_f64();
|
||||
let curve = UIViewAnimationCurve(
|
||||
user_info
|
||||
.objectForKey(unsafe { objc2_ui_kit::UIKeyboardAnimationCurveUserInfoKey })?
|
||||
.downcast::<NSNumber>()
|
||||
.unwrap()
|
||||
.as_isize(),
|
||||
);
|
||||
|
||||
let name = notification.name();
|
||||
if name.isEqualToString(unsafe { objc2_ui_kit::UIKeyboardWillChangeFrameNotification }) {
|
||||
for adapter in windows.into_iter() {
|
||||
let adapter = adapter.upgrade()?;
|
||||
let raw_window_handle::RawWindowHandle::UiKit(window_handle) =
|
||||
adapter.winit_window()?.window_handle().ok()?.as_raw()
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let view = unsafe { &*(window_handle.ui_view.as_ptr() as *const objc2_ui_kit::UIView) };
|
||||
let frame_begin = view.convertRect_fromCoordinateSpace(frame_begin, &coordinate_space);
|
||||
let frame_end = view.convertRect_fromCoordinateSpace(frame_end, &coordinate_space);
|
||||
|
||||
// Assumes that the keyboard animation doesn't pass over the window without
|
||||
// starting or ending while intersecting.
|
||||
// Although, in this strange edge case we should probably ignore the keyboard anyways.
|
||||
if rect_intersects(view.bounds(), frame_begin)
|
||||
|| rect_intersects(view.bounds(), frame_end)
|
||||
{
|
||||
adapter.with_keyboard_curve_sampler(|kcs| {
|
||||
kcs.start(animation_duration, curve, frame_begin, frame_end);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Some(())
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue