Skip to main content

aureole_runtime/
system.rs

1//! 系统集成的平台一侧:运行时用的平台后端([`backend`]),把它装进核心的注入点([`SystemBackend`]:系统设置、剪贴板、
2//! 打开网址),外观、减少动态效果、强调色变了时报告给核心;另有只在桌面上才有的服务:用默认应用打开文件、在访达里显示、系统通知。
3//!
4//! 平台相关的都从后端的服务走(三个平台各有实现:macOS 是 AppKit;Windows 是注册表、Shell、WinRT 的通知;
5//! Linux 是 D-Bus 上的 XDG 门户和通知服务),各平台的差别见各函数的说明。服务出错时带着原因(`PlatformError`),
6//! 这里把原因记进日志,对应用照旧返回 `bool`。
7//!
8//! 对应用公开的读设置、剪贴板、打开网址的函数先装上平台的实现再交给核心:在 `App::run` 之前(比如 `main` 里)调用也问得到系统
9
10use std::path::Path;
11use std::sync::Once;
12
13use platform::system::{DialogKind, DialogOptions, FileFilter};
14use platform::{LineEdgeKeys, ModifierKey, PlatformBackend, RedoKeys};
15use scene::Color;
16
17use aureole_core::host::SystemBackend;
18use aureole_core::{Appearance, Conventions, Date, DisplayInfo, FileDialogDone, FileDialogKind, FileDialogRequest, Modifiers, Time};
19use winit::raw_window_handle::HasWindowHandle;
20
21/// 运行时用的平台后端:进程里唯一的本机后端。平台相关的事(帧时钟、系统设置、剪贴板、对话框、通知、菜单托盘……)都从它走
22pub(crate) fn backend() -> &'static dyn PlatformBackend {
23    platform::native()
24}
25
26/// 平台的实现:设置、剪贴板、打开网址都问后端。剪贴板是后端里整个进程唯一的实例(X11 上最后一个实例释放时内容会没了)
27struct PlatformSystem;
28
29impl SystemBackend for PlatformSystem {
30    fn appearance(&self) -> Appearance {
31        detect()
32    }
33
34    fn is_motion_reduced(&self) -> bool {
35        backend().appearance().is_motion_reduced()
36    }
37
38    fn accent_color(&self) -> Option<Color> {
39        detect_accent()
40    }
41
42    fn read_clipboard(&self) -> Option<String> {
43        backend().clipboard().read_text().unwrap_or_else(|error| {
44            tracing::debug!("读不了剪贴板:{error}");
45            None
46        })
47    }
48
49    fn write_clipboard(&self, text: String) -> bool {
50        backend().clipboard().write_text(&text).map_err(|error| tracing::warn!("写不进剪贴板:{error}")).is_ok()
51    }
52
53    fn open_url(&self, url: &str) -> bool {
54        backend().shell().open_url(url).map_err(|error| tracing::warn!(%url, "打不开网址:{error}")).is_ok()
55    }
56
57    fn conventions(&self) -> Conventions {
58        conventions(backend().conventions())
59    }
60
61    fn file_dialog(&self, request: FileDialogRequest, done: FileDialogDone) {
62        // 父窗口:发起的窗口(macOS 上对话框是它的表单)。Windows、Linux 上从菜单栏、托盘、定时器里打开时没有发起的窗口,
63        // 用最近有焦点的(再不行最早打开的):Windows 上没有父窗口的对话框出现在屏幕左上角,窗口也不等它关掉
64        let parent = crate::window::current_window()
65            .or_else(|| if cfg!(target_os = "macos") { None } else { crate::window::front_window() })
66            .and_then(crate::window::native);
67        backend().dialog().file_dialog(dialog_options(request), parent.as_deref().map(|w| w as &dyn HasWindowHandle), done);
68    }
69
70    /// 用任意一个打开着的窗口问窗口库:每个显示器的物理坐标按它自己的缩放比例换成逻辑像素,
71    /// 和窗口的 `position()`(按窗口所在显示器的比例换算)在同一个显示器上对得上
72    fn displays(&self) -> Vec<DisplayInfo> {
73        let Some(window) = crate::window::front_window().and_then(crate::window::native) else { return Vec::new() };
74        let primary = window.primary_monitor();
75        let mut displays: Vec<DisplayInfo> = window
76            .available_monitors()
77            .map(|monitor| {
78                let scale = monitor.scale_factor();
79                let position = monitor.position().to_logical::<f32>(scale);
80                let size = monitor.size().to_logical::<f32>(scale);
81                DisplayInfo {
82                    name: monitor.name().unwrap_or_default(),
83                    position: [position.x, position.y],
84                    size: [size.width, size.height],
85                    scale_factor: scale as f32,
86                    primary: primary.as_ref() == Some(&monitor),
87                }
88            })
89            .collect();
90        displays.sort_by_key(|display| !display.primary);
91        displays
92    }
93
94    fn local_time(&self) -> Option<(Date, Time)> {
95        let [year, month, day, hour, minute, second] = platform::system::local_time()?;
96        // 闰秒可能报告 60:停在 59
97        let time = Time::checked(u8::try_from(hour).ok()?, u8::try_from(minute).ok()?, u8::try_from(second).ok()?.min(59))?;
98        Some((Date::checked(year, u8::try_from(month).ok()?, u8::try_from(day).ok()?)?, time))
99    }
100}
101
102/// 核心的请求换成平台层的设置
103pub(crate) fn dialog_options(request: FileDialogRequest) -> DialogOptions {
104    DialogOptions {
105        kind: match request.kind {
106            FileDialogKind::OpenFile => DialogKind::OpenFile,
107            FileDialogKind::OpenDirectory => DialogKind::OpenDirectory,
108            FileDialogKind::Save => DialogKind::Save,
109        },
110        multiple: request.multiple,
111        title: request.title,
112        directory: request.directory,
113        file_name: request.file_name,
114        filters: request.filters.into_iter().map(|f| FileFilter { name: f.name, extensions: f.extensions }).collect(),
115    }
116}
117
118/// 这个平台此刻能做什么(有没有菜单栏、托盘、系统通知,拖不拖得到应用外面……):
119/// 没有的时候把入口放进窗口里,而不是让用户点了没反应。关掉 `menus` 特性时菜单栏和托盘都报告没有。
120///
121/// ```no_run
122/// let can = aureole::capabilities();
123/// if !can.supports_tray {
124///     // 没有托盘:常驻的状态放在窗口里
125/// }
126/// ```
127pub fn capabilities() -> platform::Capabilities {
128    platform::with_backend(|backend| backend.capabilities())
129}
130
131/// 平台层的惯例换成核心的
132fn conventions(platform: &platform::Conventions) -> Conventions {
133    let modifier = |key| match key {
134        ModifierKey::Shift => Modifiers::SHIFT,
135        ModifierKey::Control => Modifiers::CONTROL,
136        ModifierKey::Alt => Modifiers::ALT,
137        ModifierKey::Command => Modifiers::SUPER,
138    };
139    Conventions {
140        primary_modifier: modifier(platform.primary_modifier),
141        word_modifier: modifier(platform.word_modifier),
142        uses_arrows_for_line_edges: platform.line_edge == LineEdgeKeys::PrimaryArrows,
143        accepts_y_for_redo: platform.redo == RedoKeys::YOrShiftZ,
144        wheel_line_height: platform.wheel_line_height,
145        wheel_notch: platform.wheel_notch,
146        wheel_scrolls_pages: platform.wheel_scrolls_pages,
147        fractional_wheel_is_precise: platform.fractional_wheel_is_precise,
148        shift_wheel_scrolls_horizontally: platform.shift_wheel_scrolls_horizontally,
149        control_wheel_zooms: platform.control_wheel_zooms,
150        treats_control_click_as_secondary: platform.treats_control_click_as_secondary,
151        long_press_duration: platform.long_press_duration,
152        double_click_interval: platform.double_click_interval,
153        double_click_distance: platform.double_click_distance,
154        drag_threshold: platform.drag_threshold,
155        word_forward_skips_spaces: platform.word_forward_skips_spaces,
156        accepts_insert_for_clipboard: platform.accepts_insert_for_clipboard,
157        pads_ime_area: platform.pads_ime_area,
158    }
159}
160
161/// 装上平台的实现(整个进程一次):`App` 创建时、应用第一次直接用系统设置和剪贴板时
162pub(crate) fn install() {
163    static INSTALLED: Once = Once::new();
164    INSTALLED.call_once(|| aureole_core::host::set_system_backend(PlatformSystem));
165}
166
167fn detect() -> Appearance {
168    if backend().appearance().is_dark_mode() == Some(true) { Appearance::Dark } else { Appearance::Light }
169}
170
171fn detect_accent() -> Option<Color> {
172    backend().appearance().accent_color().map(|[r, g, b]| Color::rgb(r, g, b))
173}
174
175/// 窗口库报告了外观(启动时、变化时):以平台读到的系统设置为准。应用固定了深浅时窗口库报的是窗口自己的外观,
176/// 不是系统的;平台读不到时(没有桌面门户)才用报告的
177pub(crate) fn reported_appearance(theme: winit::window::Theme) -> Appearance {
178    match backend().appearance().is_dark_mode() {
179        Some(true) => Appearance::Dark,
180        Some(false) => Appearance::Light,
181        None if theme == winit::window::Theme::Dark => Appearance::Dark,
182        None => Appearance::Light,
183    }
184}
185
186/// 重新问系统"减少动态效果"和强调色:窗口获得焦点、外观变化时调用(几次系统调用,没变时什么都不做)
187pub(crate) fn refresh_settings() {
188    // 应用固定了深浅时窗口库不再报告系统外观的变化:平台读得到就在这里补上
189    if let Some(dark) = backend().appearance().is_dark_mode() {
190        aureole_core::host::set_system_appearance(if dark { Appearance::Dark } else { Appearance::Light });
191    }
192    aureole_core::host::set_motion_reduced(backend().appearance().is_motion_reduced());
193    aureole_core::host::set_system_accent_color(detect_accent());
194}
195
196/// 后台监视到系统设置变了(Windows 的注册表、Linux 的门户):重新读外观、减少动态效果、强调色
197pub(crate) fn settings_changed() {
198    aureole_core::host::set_system_appearance(detect());
199    refresh_settings();
200}
201
202/// 系统外观(深色 / 浅色),响应式:在绑定里读,用户在系统设置里切换时界面跟着变。
203/// 全应用一个,不分窗口。测试工具里固定为浅色,用 `Harness::set_system_appearance` 模拟切换。
204///
205/// macOS、Windows 由窗口报告变化(Windows 另外监视注册表,只有托盘、没有窗口时也收得到);
206/// Linux 读 XDG 门户的 `color-scheme`,后台线程听它的变化(GNOME、KDE 都支持)
207pub fn system_appearance() -> Appearance {
208    install();
209    aureole_core::system_appearance()
210}
211
212/// 应用此刻生效的外观,响应式:固定成浅色、深色([`aureole_core::set_appearance_mode`])时是它,跟着系统时是 [`system_appearance`]。
213/// 框架自带的样子按它画;自己的颜色要跟着深浅变时在绑定里读它,或者读 `aureole::defaults::palette()`
214pub fn appearance() -> Appearance {
215    install();
216    aureole_core::appearance()
217}
218
219/// 系统打开了"减少动态效果"(辅助功能设置),响应式。应用自己的动画按它决定要不要用移动和缩放;
220/// 框架里本来就动的东西(拖动排序的行让位、共享元素的飞行)在它打开时立即到位或只淡入淡出。
221///
222/// macOS 读 `NSWorkspace` 的辅助功能设置,Windows 读"动画效果"的系统参数,Linux 读 XDG 门户的
223/// `reduced-motion`(以及 GNOME 关掉动画、KDE 把动画速度调到 0)。
224/// 启动时读一次,之后窗口重新获得焦点、系统外观变化时再读(在系统设置里改了、回到应用就生效;Linux 上改了马上生效)。
225/// 测试工具里固定为 `false`,用 `Harness::set_motion_reduced` 模拟
226pub fn is_motion_reduced() -> bool {
227    install();
228    aureole_core::is_motion_reduced()
229}
230
231/// 系统开着低电量模式(macOS:系统设置 → 电池;Windows:节电模式;Linux 总是 `false`)。每次调用问一次系统,不是响应式的。
232/// macOS 上开着时系统只把窗口画面显示到每秒 60 帧,框架的帧时钟跟着降到 60,不白画另一半;
233/// 应用可以照着少做些动画、少轮询。环境变量 `AUREOLE_LOW_POWER=1`(或 `0`)当作开着(关着),排查、测试用
234pub fn is_low_power_mode() -> bool {
235    static FORCED: std::sync::OnceLock<Option<bool>> = std::sync::OnceLock::new();
236    let forced = FORCED.get_or_init(|| match std::env::var("AUREOLE_LOW_POWER").as_deref() {
237        Ok("1") => Some(true),
238        Ok("0") => Some(false),
239        _ => None,
240    });
241    forced.unwrap_or_else(|| backend().environment().is_low_power_mode())
242}
243
244/// 系统的强调色(macOS:系统设置 → 外观;Windows:个性化 → 颜色;Linux:门户的 `accent-color`,GNOME 47+、KDE),
245/// 响应式;读不到时是 `None`。和"减少动态效果"一样在启动时、窗口获得焦点时、系统外观变化时重新读。
246///
247/// 框架自带的样子不用它(有自己固定的强调色);想跟着系统时在样式对象、绑定里读它:
248/// `move || aureole::system_accent_color().unwrap_or(默认色)`。测试工具里固定为 `None`
249pub fn system_accent_color() -> Option<Color> {
250    install();
251    aureole_core::system_accent_color()
252}
253
254/// 接着的显示器,主显示器在最前面:名字、位置、大小(逻辑像素)、缩放比例。每次调用时问系统,不是响应式的;
255/// 还没有打开过窗口时是空的。窗口在某个显示器上时,它的 [`crate::WindowHandle::position`] 和这个显示器的位置是同一套坐标,
256/// 恢复上次的窗口位置前可以先看那个点还在不在某个显示器上([`DisplayInfo::contains`])。
257/// 测试工具里是一个 1440 × 900 的主显示器(`Harness::set_displays` 换)
258pub fn displays() -> Vec<DisplayInfo> {
259    install();
260    aureole_core::displays()
261}
262
263/// 用系统默认的应用打开网址,例如 `https://…`、`mailto:…`。返回是否交给了系统。
264/// 测试工具里不真的打开,记下来(`Harness::opened_urls`)
265pub fn open_url(url: &str) -> bool {
266    install();
267    aureole_core::open_url(url)
268}
269
270/// 用默认应用打开文件,文件夹在访达(文件管理器)里打开。不存在时返回 `false`。
271/// macOS 用 NSWorkspace,Windows 用 ShellExecuteW,Linux 用 `xdg-open`
272pub fn open_path(path: impl AsRef<Path>) -> bool {
273    let path = path.as_ref();
274    backend().shell().open_path(path).map_err(|error| tracing::warn!(path = %path.display(), "打不开:{error}")).is_ok()
275}
276
277/// 在访达(文件管理器)里显示并选中文件。不存在时返回 `false`。
278/// Windows 用 SHOpenFolderAndSelectItems;Linux 用 `org.freedesktop.FileManager1`(GNOME、KDE 的文件管理器都支持),
279/// 不支持时打开所在的文件夹
280pub fn reveal_path(path: impl AsRef<Path>) -> bool {
281    let path = path.as_ref();
282    backend().shell().reveal_path(path).map_err(|error| tracing::warn!(path = %path.display(), "没能在文件管理器里显示:{error}")).is_ok()
283}
284
285/// 放一下系统的提示音(用户在系统设置里选的那一个),比如按了做不了的键、输入不合法。返回是否放了。
286/// macOS 是 `NSBeep`,Windows 是 `MessageBeep`;Linux 的桌面没有统一的提示音,返回 `false`。
287/// 测试工具里不出声,记次数(`Harness::beep_count`)
288pub fn beep() -> bool {
289    platform::with_backend(|backend| backend.notification().beep()).map_err(|error| tracing::debug!("没有提示音:{error}")).is_ok()
290}
291
292/// 发系统通知,返回是否交给了系统。系统通知不可用时把不可用的原因和通知的内容记下来(`tracing` 的 info),返回 `false`:
293///
294/// - macOS:要求应用打包成 .app(有包标识符),第一次发时系统会请求权限;没打包时(比如 `cargo run`)不可用。
295/// - Windows:要有应用标识(AppUserModelID):从带标识的开始菜单快捷方式启动(安装程序建的)、MSIX 包,
296///   或者进程自己设过;直接运行可执行文件(比如 `cargo run`)时不可用。
297/// - Linux:发给桌面的通知服务(`org.freedesktop.Notifications`),不用打包;没有通知服务时不可用
298pub fn notify(title: &str, body: &str) -> bool {
299    match platform::with_backend(|backend| backend.notification().notify(title, body)) {
300        Ok(()) => true,
301        Err(error) => {
302            // 原因由平台给:没打包成 .app、没有应用标识、没有会话总线……
303            tracing::info!(%title, %body, "系统通知不可用({}),通知的内容记在这里", error.reason());
304            false
305        }
306    }
307}