Skip to main content

rgpui/
platform.rs

1//! 平台抽象层:定义 `Platform` trait 和 `PlatformWindow` trait,供各平台 crate 实现。
2
3mod app_menu;
4mod keyboard;
5mod keystroke;
6
7/// 用于配置父窗口锚定弹出窗口的类型,如下拉菜单、弹出菜单和工具提示。
8pub mod popup;
9
10#[cfg(all(
11    any(test, feature = "test-support"),
12    any(
13        target_os = "windows",
14        target_os = "linux",
15        target_os = "macos",
16        target_family = "wasm"
17    )
18))]
19mod threaded_dispatcher;
20
21/// Linux 面板窗口的参数 —— Wayland 直接映射成 layer-shell 请求,
22/// X11 映射成 DOCK 窗口 + EWMH strut,所以两个后端都要能用这些类型。
23#[cfg(target_os = "linux")]
24pub mod layer_shell;
25
26#[cfg(any(test, feature = "test-support"))]
27#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
28// 测试支撑模块:断言失败就该炸(同 clippy.toml 的 allow-*-in-tests 口径)
29mod test;
30
31#[cfg(all(target_os = "macos", any(test, feature = "test-support")))]
32#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
33// 测试支撑模块:断言失败就该炸(同 clippy.toml 的 allow-*-in-tests 口径)
34mod visual_test;
35
36#[cfg(all(
37    feature = "screen-capture",
38    any(target_os = "windows", target_os = "linux", target_os = "freebsd",)
39))]
40pub mod scap_screen_capture;
41
42#[cfg(all(
43    any(target_os = "windows", target_os = "linux"),
44    feature = "screen-capture"
45))]
46pub(crate) type PlatformScreenCaptureFrame = scap::frame::Frame;
47#[cfg(not(feature = "screen-capture"))]
48pub(crate) type PlatformScreenCaptureFrame = ();
49#[cfg(all(target_os = "macos", feature = "screen-capture"))]
50pub(crate) type PlatformScreenCaptureFrame = core_video::image_buffer::CVImageBuffer;
51
52use crate::menu::NativeMenu;
53use crate::rgpui_util;
54use crate::scheduler::Instant;
55pub use crate::scheduler::RunnableMeta;
56use crate::{
57    Action, AnyWindowHandle, App, AsyncWindowContext, BackgroundExecutor, Bounds,
58    DEFAULT_WINDOW_SIZE, DevicePixels, DispatchEventResult, Font, FontId, FontMetrics, FontRun,
59    ForegroundExecutor, GlyphId, GpuSpecs, Hsla, ImageSource, Keymap, LineLayout, Pixels,
60    PlatformInput, Point, Priority, RenderGlyphParams, RenderImage, RenderImageParams,
61    RenderSvgParams, Scene, ShapedGlyph, ShapedRun, SharedString, Size, SvgRenderer,
62    SystemWindowTab, Task, Window, WindowControlArea, hash, point, px, size,
63};
64use crate::{Tray, TrayIconEvent, TrayMenuItem};
65use anyhow::Result;
66#[cfg(any(target_os = "linux", target_os = "freebsd"))]
67use anyhow::bail;
68use async_task::Runnable;
69use futures::channel::oneshot;
70#[cfg(any(test, feature = "test-support"))]
71use image::RgbaImage;
72use image::codecs::gif::GifDecoder;
73use image::{AnimationDecoder as _, Frame};
74use raw_window_handle::{HasDisplayHandle, HasWindowHandle};
75use schemars::JsonSchema;
76use seahash::SeaHasher;
77use serde::{Deserialize, Serialize};
78use smallvec::SmallVec;
79use std::borrow::Cow;
80use std::hash::{Hash, Hasher};
81use std::io::Cursor;
82use std::ops;
83use std::time::Duration;
84use std::{
85    fmt::{self, Debug},
86    ops::Range,
87    path::{Path, PathBuf},
88    rc::Rc,
89    sync::Arc,
90};
91use strum::EnumIter;
92use uuid::Uuid;
93
94/// 内部不变量:值为 `None` 说明前提被破坏(类型不符、状态缺失等),必须立刻暴露。
95///
96/// 统一走这里而不是散落的 `unwrap`:语义与原先一致(同样 panic),但把「这是不变量
97/// 断言」的意图写进调用点,模块级 `deny` 仍能拦住随手写的 unwrap。
98#[inline]
99#[allow(clippy::panic)] // 不变量断言:前提被破坏必须立刻暴露
100fn invariant<T>(value: Option<T>, message: &str) -> T {
101    match value {
102        Some(value) => value,
103        None => panic!("{message}"),
104    }
105}
106
107/// 内部不变量:结果为 `Err` 说明前提被破坏(恒成功的调用失败等),必须立刻暴露。
108#[inline]
109#[allow(clippy::panic)] // 不变量断言:前提被破坏必须立刻暴露
110fn invariant_result<T, E>(result: Result<T, E>, message: &str) -> T {
111    match result {
112        Ok(value) => value,
113        Err(_) => panic!("{message}"),
114    }
115}
116
117pub use app_menu::*;
118pub use keyboard::*;
119pub use keystroke::*;
120
121#[cfg(any(test, feature = "test-support"))]
122pub(crate) use test::*;
123
124#[cfg(any(test, feature = "test-support"))]
125pub use test::{TestDispatcher, TestScreenCaptureSource, TestScreenCaptureStream};
126
127#[cfg(all(
128    any(test, feature = "test-support"),
129    any(
130        target_os = "windows",
131        target_os = "linux",
132        target_os = "macos",
133        target_family = "wasm"
134    )
135))]
136pub use threaded_dispatcher::ThreadedDispatcher;
137
138#[cfg(all(target_os = "macos", any(test, feature = "test-support")))]
139pub use visual_test::VisualTestPlatform;
140
141// TODO(jk): return an enum instead of a string
142/// 返回当前使用的合成器名称(猜测),
143/// 不会尝试连接到指定的合成器。
144#[cfg(any(target_os = "linux", target_os = "freebsd"))]
145#[inline]
146pub fn guess_compositor() -> &'static str {
147    if std::env::var_os("ZED_HEADLESS").is_some() {
148        return "Headless";
149    }
150
151    #[cfg(feature = "wayland")]
152    let wayland_display = std::env::var_os("WAYLAND_DISPLAY");
153    #[cfg(not(feature = "wayland"))]
154    let wayland_display: Option<std::ffi::OsString> = None;
155
156    #[cfg(feature = "x11")]
157    let x11_display = std::env::var_os("DISPLAY");
158    #[cfg(not(feature = "x11"))]
159    let x11_display: Option<std::ffi::OsString> = None;
160
161    let use_wayland = wayland_display.is_some_and(|display| !display.is_empty());
162    let use_x11 = x11_display.is_some_and(|display| !display.is_empty());
163
164    if use_wayland {
165        "Wayland"
166    } else if use_x11 {
167        "X11"
168    } else {
169        "Headless"
170    }
171}
172
173// ============================================================================
174// 缺失的系统类型定义
175// ============================================================================
176
177/// 系统电源事件
178#[derive(Debug, Clone, Copy, PartialEq, Eq)]
179pub enum SystemPowerEvent {
180    /// 系统即将进入睡眠
181    Sleep,
182    /// 系统已从睡眠唤醒
183    WakeUp,
184}
185
186/// 电源阻止器类型
187#[derive(Debug, Clone, Copy, PartialEq, Eq)]
188pub enum PowerSaveBlockerKind {
189    /// 阻止系统休眠
190    PreventSleep,
191    /// 阻止屏幕关闭
192    PreventDisplaySleep,
193}
194
195/// 电源阻止器句柄:由平台实现,内部持有系统资源,`Drop` 即取消抑制。
196///
197/// 见 [`Platform::start_power_save_blocker`]:留着返回值抑制就在,丢弃它立刻恢复
198/// 系统的省电策略。刻意不给 `stop()` / 阻止器 ID —— 平台按 ID 保存句柄正是泄漏的源头。
199pub trait PowerSaveBlocker: Send {}
200
201/// 操作系统信息
202#[derive(Debug, Clone)]
203pub struct OsInfo {
204    /// 操作系统名称
205    pub name: String,
206    /// 操作系统版本
207    pub version: String,
208}
209
210/// 权限状态
211#[derive(Debug, Clone, Copy, PartialEq, Eq)]
212pub enum PermissionStatus {
213    /// 未确定
214    NotDetermined,
215    /// 已授权
216    Granted,
217    /// 已拒绝
218    Denied,
219    /// 不可用
220    Unavailable,
221}
222
223/// 权限类型(用于描述应用在系统中申请的权限类别)
224///
225/// 通常用于 macOS / Windows 等系统能力访问控制,例如辅助功能、屏幕录制、输入监控等。
226#[derive(Debug, Clone, Copy, PartialEq, Eq)]
227pub enum PermissionType {
228    /// 辅助功能权限(Accessibility)
229    ///
230    /// 用于允许应用模拟用户操作、读取 UI 元素、控制系统界面等能力。
231    Accessibility,
232
233    /// 屏幕录制/屏幕捕获权限(Screen Capture)
234    ///
235    /// 用于获取屏幕内容,例如截图、录屏或远程桌面功能。
236    ScreenCapture,
237
238    /// 输入监控权限(Input Monitoring)
239    ///
240    /// 用于监听键盘和鼠标输入事件(如全局快捷键、输入记录等)。
241    InputMonitoring,
242}
243
244/// 网络状态
245#[derive(Debug, Clone, Copy, PartialEq, Eq)]
246pub enum NetworkStatus {
247    /// 无法连接网络
248    Disconnected,
249    /// 已连接但不满足服务要求
250    ConnectedBelowRequired,
251    /// 已连接且满足服务要求
252    Connected,
253}
254
255/// 聚焦窗口信息
256#[derive(Debug, Clone)]
257pub struct FocusedWindowInfo {
258    /// 窗口所属应用名称
259    pub app_name: String,
260    /// 窗口标题
261    pub window_title: String,
262    /// Bundle ID(macOS 特有)
263    pub bundle_id: Option<String>,
264    /// 进程 ID
265    pub pid: Option<u32>,
266}
267
268/// 语义化窗口位置,用于计算窗口的屏幕位置
269#[derive(Debug, Clone, Copy, PartialEq)]
270pub enum WindowPosition {
271    /// 在主显示区域居中
272    Center,
273    /// 在指定显示区域居中
274    CenterOnDisplay(DisplayId),
275    /// 在托盘图标上方居中
276    TrayCenter(Bounds<Pixels>),
277    /// 屏幕右上角(带边距)
278    TopRight {
279        /// 与屏幕边缘的距离
280        margin: Pixels,
281    },
282    /// 屏幕右下角(带边距)
283    BottomRight {
284        /// 与屏幕边缘的距离
285        margin: Pixels,
286    },
287    /// 屏幕左上角(带边距)
288    TopLeft {
289        /// 与屏幕边缘的距离
290        margin: Pixels,
291    },
292    /// 屏幕左下角(带边距)
293    BottomLeft {
294        /// 与屏幕边缘的距离
295        margin: Pixels,
296    },
297}
298
299/// 跨平台应用抽象层,由各平台 crate(rgpui-windows、rgpui-macos、rgpui-linux、rgpui-web)实现。
300///
301/// 提供应用生命周期、窗口管理、系统集成(托盘、快捷键、通知、电源等)的统一接口。
302/// 应用通过 [`rgpui_platform::application()`] 获取实现此 trait 的实例。
303pub trait Platform: 'static {
304    /// 返回后台线程执行器,用于调度异步任务。
305    fn background_executor(&self) -> BackgroundExecutor;
306    /// 返回主线程执行器,用于调度需要在 UI 线程运行的任务。
307    fn foreground_executor(&self) -> ForegroundExecutor;
308    /// 返回文本渲染系统实例,负责字体加载、文本布局和渲染。
309    fn text_system(&self) -> Arc<dyn PlatformTextSystem>;
310
311    /// 启动应用主循环,`on_finish_launching` 在启动完成后回调。
312    fn run(&self, on_finish_launching: Box<dyn 'static + FnOnce()>);
313    /// 退出应用进程。
314    fn quit(&self);
315    /// 重启应用,可选指定新的二进制路径。
316    fn restart(&self, binary_path: Option<PathBuf>);
317    /// 激活应用(将窗口置于前台),`ignoring_other_apps` 在 macOS 下是否忽略其他应用。
318    fn activate(&self, ignoring_other_apps: bool);
319    /// 隐藏应用(macOS 下隐藏所有窗口,其他平台最小化)。
320    fn hide(&self);
321    /// 隐藏当前应用以外的所有其他应用的窗口。
322    fn hide_other_apps(&self);
323    /// 取消隐藏所有被 `hide_other_apps` 隐藏的应用。
324    fn unhide_other_apps(&self);
325
326    /// 返回所有可用显示器的列表。
327    fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>>;
328    /// 返回主显示器(包含任务栏/菜单栏的显示器)。
329    fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>>;
330    /// 返回当前获得焦点的窗口句柄。
331    fn active_window(&self) -> Option<AnyWindowHandle>;
332    /// 返回窗口栈(Z-order),从最顶层到最底层。
333    fn window_stack(&self) -> Option<Vec<AnyWindowHandle>> {
334        None
335    }
336
337    /// 当前平台是否支持屏幕捕获功能。
338    fn is_screen_capture_supported(&self) -> bool {
339        false
340    }
341
342    /// 获取可用的屏幕捕获源列表(屏幕/窗口),通过 oneshot channel 异步返回。
343    fn screen_capture_sources(
344        &self,
345    ) -> oneshot::Receiver<anyhow::Result<Vec<Rc<dyn ScreenCaptureSource>>>> {
346        let (sources_tx, sources_rx) = oneshot::channel();
347        sources_tx
348            .send(Err(anyhow::anyhow!(
349                "rgpui was compiled without the screen-capture feature"
350            )))
351            .ok();
352        sources_rx
353    }
354
355    /// 根据窗口参数创建平台原生窗口,返回 `PlatformWindow` 实例。
356    fn open_window(
357        &self,
358        handle: AnyWindowHandle,
359        options: WindowParams,
360    ) -> anyhow::Result<Box<dyn PlatformWindow>>;
361
362    /// 返回应用窗口的外观模式(亮色/暗色)。
363    fn window_appearance(&self) -> WindowAppearance;
364
365    /// 返回系统是否开启了「减少动态效果」无障碍设置。
366    ///
367    /// 默认 `false`,即未覆写的平台保持动画开启;核心层由
368    /// [`App::reduce_motion`](crate::App::reduce_motion) 消费此值。
369    fn reduce_motion_enabled(&self) -> bool {
370        false
371    }
372
373    /// 返回窗口按钮布局配置(如 macOS 红绿灯位置、Windows 按钮顺序)。
374    fn button_layout(&self) -> Option<WindowButtonLayout> {
375        None
376    }
377
378    /// 在系统默认浏览器中打开 URL。
379    ///
380    /// 这是 fire-and-forget 调用:各平台异步启动外部程序,失败只记日志,
381    /// 调用方无法从此方法得知是否成功(部分平台会回退到门户 API)。
382    fn open_url(&self, url: &str);
383    /// 注册 URL scheme 回调,当应用通过自定义 URL scheme 打开时触发。
384    ///
385    /// 各平台从各自的系统入口派发:macOS 由 AppKit 的 `application:openURLs:` 调用;
386    /// Linux 在回调注册时重放本次启动命令行里由桌面入口 `%u` 传入的 URL;
387    /// Windows 当前只保存回调、没有派发点。
388    fn on_open_urls(&self, callback: Box<dyn FnMut(Vec<String>)>);
389    /// 注册自定义 URL scheme(如 `myapp://`),使系统将该 scheme 的 URL 分发到本应用。
390    fn register_url_scheme(&self, url: &str) -> Task<Result<()>>;
391
392    /// 打开文件选择对话框,返回用户选择的文件路径列表。
393    fn prompt_for_paths(
394        &self,
395        options: PathPromptOptions,
396    ) -> oneshot::Receiver<Result<Option<Vec<PathBuf>>>>;
397    /// 打开文件保存对话框,返回用户指定的保存路径。
398    fn prompt_for_new_path(
399        &self,
400        directory: &Path,
401        suggested_name: Option<&str>,
402    ) -> oneshot::Receiver<Result<Option<PathBuf>>>;
403    /// 文件选择对话框是否支持同时选择文件和目录。
404    fn can_select_mixed_files_and_dirs(&self) -> bool;
405    /// 在系统文件管理器中显示(reveal)指定路径。
406    ///
407    /// 同 `open_url`:fire-and-forget,失败只记日志,调用方无从判断结果。
408    fn reveal_path(&self, path: &Path);
409    /// 使用系统默认应用打开指定路径。
410    fn open_with_system(&self, path: &Path);
411
412    /// 注册应用退出时的回调。
413    fn on_quit(&self, callback: Box<dyn FnMut()>);
414    /// 注册应用从后台恢复(macOS Dock 图标点击)时的回调。
415    fn on_reopen(&self, callback: Box<dyn FnMut()>);
416
417    /// 设置应用菜单栏(macOS 为全局菜单栏,其他平台为窗口菜单)。
418    fn set_menus(&self, menus: Vec<Menu>, keymap: &Keymap);
419    /// 获取当前应用菜单的副本。
420    fn get_menus(&self) -> Option<Vec<OwnedMenu>> {
421        None
422    }
423
424    /// 设置 macOS Dock 栏右键菜单。
425    fn set_dock_menu(&self, menu: Vec<MenuItem>, keymap: &Keymap);
426    /// 执行 Dock 菜单中的操作。
427    fn perform_dock_menu_action(&self, _action: usize) {}
428    /// 将路径添加到最近打开文档列表。
429    fn add_recent_document(&self, _path: &Path) {}
430    /// 更新 Windows 跳转列表(任务栏右键菜单中的最近文档)。
431    fn update_jump_list(
432        &self,
433        _menus: Vec<MenuItem>,
434        _entries: Vec<SmallVec<[PathBuf; 2]>>,
435    ) -> Task<Vec<SmallVec<[PathBuf; 2]>>> {
436        Task::ready(Vec::new())
437    }
438    /// 注册应用菜单操作回调,当用户点击菜单项时触发。
439    fn on_app_menu_action(&self, callback: Box<dyn FnMut(&dyn Action)>);
440    /// 注册菜单即将打开时的回调(可用于动态更新菜单项状态)。
441    fn on_will_open_app_menu(&self, callback: Box<dyn FnMut()>);
442    /// 注册菜单命令验证回调,返回 `false` 可禁用菜单项。
443    fn on_validate_app_menu_command(&self, callback: Box<dyn FnMut(&dyn Action) -> bool>);
444
445    /// 返回系统热状态(正常、警告、临界)。
446    fn thermal_state(&self) -> ThermalState;
447    /// 注册系统热状态变化回调。
448    fn on_thermal_state_change(&self, callback: Box<dyn FnMut()>);
449
450    /// 返回合成器名称(如 "dwm"、"mutter"),用于诊断。
451    fn compositor_name(&self) -> &'static str {
452        ""
453    }
454    /// 返回应用自身可执行文件的路径。
455    fn app_path(&self) -> Result<PathBuf>;
456    /// 返回辅助可执行文件的路径(如子进程、插件)。
457    fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf>;
458
459    /// 设置鼠标光标样式(箭头、手型、文本光标等)。
460    fn set_cursor_style(&self, style: CursorStyle);
461
462    /// 隐藏鼠标光标,直到用户移动鼠标时自动恢复显示。
463    fn hide_cursor_until_mouse_moves(&self);
464
465    /// 返回鼠标光标当前是否可见。
466    fn is_cursor_visible(&self) -> bool;
467
468    /// 是否自动隐藏滚动条(鼠标靠近时才显示)。
469    fn should_auto_hide_scrollbars(&self) -> bool;
470
471    /// 从系统剪贴板读取内容。
472    fn read_from_clipboard(&self) -> Option<ClipboardItem>;
473    /// 写入内容到系统剪贴板。
474    fn write_to_clipboard(&self, item: ClipboardItem);
475
476    /// 从 Linux/X11 主选择区(Primary Selection)读取内容。
477    #[cfg(any(target_os = "linux", target_os = "freebsd"))]
478    fn read_from_primary(&self) -> Option<ClipboardItem>;
479    /// 写入内容到 Linux/X11 主选择区。
480    #[cfg(any(target_os = "linux", target_os = "freebsd"))]
481    fn write_to_primary(&self, item: ClipboardItem);
482
483    /// 从 macOS 查找粘贴板(Find Pasteboard)读取内容。
484    #[cfg(target_os = "macos")]
485    fn read_from_find_pasteboard(&self) -> Option<ClipboardItem>;
486    /// 写入内容到 macOS 查找粘贴板。
487    #[cfg(target_os = "macos")]
488    fn write_to_find_pasteboard(&self, item: ClipboardItem);
489
490    /// 将凭据(URL、用户名、密码)写入系统密钥链。
491    fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>>;
492    /// 从系统密钥链读取指定 URL 的凭据。
493    fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>>;
494    /// 从系统密钥链删除指定 URL 的凭据。
495    fn delete_credentials(&self, url: &str) -> Task<Result<()>>;
496
497    /// 返回当前键盘布局信息。
498    fn keyboard_layout(&self) -> Box<dyn PlatformKeyboardLayout>;
499    /// 返回键盘映射器,用于将原始按键事件转换为字符输入。
500    fn keyboard_mapper(&self) -> Rc<dyn PlatformKeyboardMapper>;
501    /// 注册键盘布局变化回调(用户切换输入法/布局时触发)。
502    fn on_keyboard_layout_change(&self, callback: Box<dyn FnMut()>);
503
504    /// 设置系统托盘图标、菜单和按键绑定。
505    fn set_tray(&self, _tray: Tray, _menus: Option<Vec<MenuItem>>, _keymap: &Keymap) {}
506    /// 更新系统托盘图标,`None` 表示移除图标。
507    fn set_tray_icon(&self, _icon: Option<&[u8]>) {}
508    /// 更新系统托盘右键菜单。
509    fn set_tray_menu(&self, _menu: Vec<TrayMenuItem>) {}
510    /// 设置鼠标悬停在托盘图标上时显示的工具提示文本。
511    fn set_tray_tooltip(&self, _tooltip: &str) {}
512    /// 设置托盘面板模式(Windows 下影响图标的显示行为)。
513    fn set_tray_panel_mode(&self, _enabled: bool) {}
514    /// 返回系统托盘图标在屏幕上的边界矩形。
515    fn get_tray_icon_bounds(&self) -> Option<Bounds<Pixels>> {
516        None
517    }
518    /// 注册托盘图标事件回调(单击、双击、右键等)。
519    fn on_tray_icon_event(&self, _callback: Box<dyn FnMut(TrayIconEvent)>) {}
520    /// 注册托盘菜单项操作回调。
521    fn on_tray_menu_action(&self, _callback: Box<dyn FnMut(SharedString)>) {}
522
523    /// 注册全局系统快捷键,`id` 用于标识快捷键,`keystroke` 定义按键组合。
524    ///
525    /// 注意:trait 默认实现返回 `Ok(())` 但什么都不做。未覆盖此方法的后端会
526    /// 「注册成功」却永远收不到按键;Wayland 会如实返回不支持的错误。
527    fn register_global_hotkey(&self, _id: u32, _keystroke: &Keystroke) -> Result<()> {
528        Ok(())
529    }
530    /// 取消注册全局系统快捷键。
531    fn unregister_global_hotkey(&self, _id: u32) {}
532    /// 注册全局快捷键触发回调,`id` 对应注册时的标识。
533    fn on_global_hotkey(&self, _callback: Box<dyn FnMut(u32)>) {}
534
535    /// 显示系统通知,返回 `Ok(())` 表示通知已发送。
536    ///
537    /// trait 默认实现返回 `Ok(())` 但什么都不做(1.4.1 批量修过一批这类
538    /// 「假实现」)。Linux 无头构建会如实报错;调用方不能只看 `Ok` 判断送达。
539    fn show_notification(&self, _title: &str, _body: &str) -> Result<()> {
540        Ok(())
541    }
542
543    /// 设置开机自启动,`app_id` 为应用唯一标识。
544    ///
545    /// trait 默认实现返回 `Ok(())` 但什么都不做;`is_auto_launch_enabled` 同理
546    /// 恒返回 `false`。未覆盖的后端上不要据此判断自启已生效。
547    fn set_auto_launch(&self, _app_id: &str, _enabled: bool) -> Result<()> {
548        Ok(())
549    }
550    /// 查询开机自启动是否已启用。
551    fn is_auto_launch_enabled(&self, _app_id: &str) -> bool {
552        false
553    }
554
555    /// 返回当前系统中获得焦点的窗口信息(标题、进程名等)。
556    ///
557    /// Wayland 原生会话恒为 `None`(没有读取其它客户端窗口信息的协议),
558    /// 调用方无法区分「不支持」与「当前没有焦点窗口」。macOS 当前只提供
559    /// app_name / bundle_id / pid,`window_title` 为空。
560    fn focused_window_info(&self) -> Option<FocusedWindowInfo> {
561        None
562    }
563
564    /// 查询指定类别的系统权限状态。
565    ///
566    /// 这是权限类别的统一入口:`PermissionType` 里的每一项都要能问,
567    /// 不要再为单个类别增设 `xxx_status` 特例方法 —— 特例只会让某一平台
568    /// 已经做好的判定逻辑在应用层根本没有调用点。
569    /// 无法判定(系统没有这个概念、或总线/服务不可达)时返回
570    /// [`PermissionStatus::Unavailable`],不要返回 `Granted` 假装可用。
571    fn check_permission(&self, _kind: PermissionType) -> PermissionStatus {
572        PermissionStatus::Unavailable
573    }
574    /// 请求指定类别的系统权限:有系统授权弹窗的就弹窗,没有的会输出可操作的引导日志。
575    fn request_permission(&self, _kind: PermissionType) {}
576
577    /// 注册系统电源事件回调(系统即将睡眠 / 已从睡眠唤醒)。
578    fn on_system_power_event(&self, _callback: Box<dyn FnMut(SystemPowerEvent)>) {}
579
580    /// 注册系统唤醒时的回调函数。
581    fn on_system_wake(&self, _callback: Box<dyn FnMut()>) {}
582
583    /// 启动电源阻止器:阻止系统休眠或息屏。
584    ///
585    /// 返回的句柄**持有即生效、`Drop` 即释放**,所以没有配套的
586    /// `stop_power_save_blocker(id)` —— 「返回 ID、再按 ID 停止」的形状会把底层
587    /// 资源(Linux 上是 logind `Inhibit` 返回的 fifo fd)泄漏在平台内部,
588    /// 进程退出前抑制一直挂着,应用忘没忘停都无人知晓。
589    /// 平台不支持或判定通道不可达时返回 `None`,不要假装阻止成功。
590    fn start_power_save_blocker(
591        &self,
592        _kind: PowerSaveBlockerKind,
593    ) -> Option<Box<dyn PowerSaveBlocker>> {
594        None
595    }
596
597    /// 返回系统空闲时间(自上次用户输入以来的时长)。
598    fn system_idle_time(&self) -> Option<Duration> {
599        None
600    }
601
602    /// 返回当前网络连接状态。
603    fn network_status(&self) -> NetworkStatus {
604        NetworkStatus::Connected
605    }
606
607    /// 返回操作系统信息(名称、版本号)。
608    fn os_info(&self) -> OsInfo {
609        OsInfo {
610            name: String::new(),
611            version: String::new(),
612        }
613    }
614}
615
616/// 平台显示器句柄,代表一个物理显示器或笔记本屏幕。
617pub trait PlatformDisplay: Debug {
618    /// 获取显示器 ID。
619    fn id(&self) -> DisplayId;
620
621    /// 返回显示器的持久化唯一标识符,可在系统重启后继续使用。
622    fn uuid(&self) -> Result<Uuid>;
623
624    /// 获取显示器的边界区域(包含任务栏/Dock 区域)。
625    fn bounds(&self) -> Bounds<Pixels>;
626
627    /// 获取显示器的可见边界区域(排除任务栏/Dock 区域)。
628    /// 这是可放置窗口且不会被遮挡的可用区域。
629    /// 未覆盖时默认返回完整显示器边界。
630    fn visible_bounds(&self) -> Bounds<Pixels> {
631        self.bounds()
632    }
633
634    /// 获取显示器的默认窗口放置区域。
635    fn default_bounds(&self) -> Bounds<Pixels> {
636        let bounds = self.bounds();
637        let center = bounds.center();
638        let clipped_window_size = DEFAULT_WINDOW_SIZE.min(&bounds.size);
639
640        let offset = clipped_window_size / 2.0;
641        let origin = point(center.x - offset.width, center.y - offset.height);
642        Bounds::new(origin, clipped_window_size)
643    }
644}
645
646/// 系统热状态
647#[derive(Debug, Clone, Copy, PartialEq, Eq)]
648pub enum ThermalState {
649    /// 系统无热限制
650    Nominal,
651    /// 系统轻微受限,应减少非必要工作
652    Fair,
653    /// 系统中度受限,应减少 CPU/GPU 密集型工作
654    Serious,
655    /// 系统严重受限,应最小化所有资源使用
656    Critical,
657}
658
659/// 屏幕捕获源的元数据
660#[derive(Clone)]
661pub struct SourceMetadata {
662    /// 屏幕的不透明标识符。
663    pub id: u64,
664    /// 人类可读的源标签。
665    pub label: Option<SharedString>,
666    /// 该源是否为主显示器。
667    pub is_main: Option<bool>,
668    /// 该源的视频分辨率。
669    pub resolution: Size<DevicePixels>,
670}
671
672/// 可被捕获的屏幕视频内容源。
673pub trait ScreenCaptureSource {
674    /// 返回该源的元数据。
675    fn metadata(&self) -> Result<SourceMetadata>;
676
677    /// 开始从该源捕获视频,每帧调用给定的回调函数。
678    fn stream(
679        &self,
680        foreground_executor: &ForegroundExecutor,
681        frame_callback: Box<dyn Fn(ScreenCaptureFrame) + Send>,
682    ) -> oneshot::Receiver<Result<Box<dyn ScreenCaptureStream>>>;
683}
684
685/// 从屏幕捕获的视频流。
686pub trait ScreenCaptureStream {
687    /// 返回该源的元数据。
688    fn metadata(&self) -> Result<SourceMetadata>;
689}
690
691/// 从屏幕捕获的视频帧。
692pub struct ScreenCaptureFrame(pub PlatformScreenCaptureFrame);
693
694#[cfg(all(
695    any(target_os = "windows", target_os = "linux"),
696    feature = "screen-capture"
697))]
698impl ScreenCaptureFrame {
699    /// 获取帧宽度(像素)
700    pub fn width(&self) -> u32 {
701        match &self.0 {
702            scap::frame::Frame::YUVFrame(f) => f.width as u32,
703            scap::frame::Frame::RGB(f) => f.width as u32,
704            scap::frame::Frame::RGBx(f) => f.width as u32,
705            scap::frame::Frame::XBGR(f) => f.width as u32,
706            scap::frame::Frame::BGRx(f) => f.width as u32,
707            scap::frame::Frame::BGR0(f) => f.width as u32,
708            scap::frame::Frame::BGRA(f) => f.width as u32,
709        }
710    }
711
712    /// 获取帧高度(像素)
713    pub fn height(&self) -> u32 {
714        match &self.0 {
715            scap::frame::Frame::YUVFrame(f) => f.height as u32,
716            scap::frame::Frame::RGB(f) => f.height as u32,
717            scap::frame::Frame::RGBx(f) => f.height as u32,
718            scap::frame::Frame::XBGR(f) => f.height as u32,
719            scap::frame::Frame::BGRx(f) => f.height as u32,
720            scap::frame::Frame::BGR0(f) => f.height as u32,
721            scap::frame::Frame::BGRA(f) => f.height as u32,
722        }
723    }
724
725    /// 将帧转换为 RGBA 图像
726    ///
727    /// 支持所有 scap 输出格式:BGRA、BGR0、BGRx、XBGR、RGB、RGBx、YUV(NV12)。
728    /// YUV 格式使用 BT.601 标准进行色彩空间转换。
729    pub fn to_rgba(&self) -> Option<image::RgbaImage> {
730        match &self.0 {
731            scap::frame::Frame::BGRA(f) => {
732                let w = f.width as u32;
733                let h = f.height as u32;
734                let mut rgba = Vec::with_capacity((w * h * 4) as usize);
735                for chunk in f.data.chunks_exact(4) {
736                    rgba.push(chunk[2]); // R
737                    rgba.push(chunk[1]); // G
738                    rgba.push(chunk[0]); // B
739                    rgba.push(chunk[3]); // A
740                }
741                image::RgbaImage::from_raw(w, h, rgba)
742            }
743            scap::frame::Frame::BGR0(f) => {
744                let w = f.width as u32;
745                let h = f.height as u32;
746                let mut rgba = Vec::with_capacity((w * h * 4) as usize);
747                for chunk in f.data.chunks_exact(4) {
748                    rgba.push(chunk[2]); // R
749                    rgba.push(chunk[1]); // G
750                    rgba.push(chunk[0]); // B
751                    rgba.push(255); // A (不透明)
752                }
753                image::RgbaImage::from_raw(w, h, rgba)
754            }
755            scap::frame::Frame::BGRx(f) => {
756                let w = f.width as u32;
757                let h = f.height as u32;
758                let mut rgba = Vec::with_capacity((w * h * 4) as usize);
759                for chunk in f.data.chunks_exact(4) {
760                    rgba.push(chunk[2]); // R
761                    rgba.push(chunk[1]); // G
762                    rgba.push(chunk[0]); // B
763                    rgba.push(255); // A (不透明)
764                }
765                image::RgbaImage::from_raw(w, h, rgba)
766            }
767            scap::frame::Frame::XBGR(f) => {
768                let w = f.width as u32;
769                let h = f.height as u32;
770                let mut rgba = Vec::with_capacity((w * h * 4) as usize);
771                for chunk in f.data.chunks_exact(4) {
772                    rgba.push(chunk[3]); // R
773                    rgba.push(chunk[2]); // G
774                    rgba.push(chunk[1]); // B
775                    rgba.push(255); // A (不透明)
776                }
777                image::RgbaImage::from_raw(w, h, rgba)
778            }
779            scap::frame::Frame::RGB(f) => {
780                let w = f.width as u32;
781                let h = f.height as u32;
782                let mut rgba = Vec::with_capacity((w * h * 4) as usize);
783                for chunk in f.data.chunks_exact(3) {
784                    rgba.push(chunk[0]); // R
785                    rgba.push(chunk[1]); // G
786                    rgba.push(chunk[2]); // B
787                    rgba.push(255); // A (不透明)
788                }
789                image::RgbaImage::from_raw(w, h, rgba)
790            }
791            scap::frame::Frame::RGBx(f) => {
792                let w = f.width as u32;
793                let h = f.height as u32;
794                let mut rgba = Vec::with_capacity((w * h * 4) as usize);
795                for chunk in f.data.chunks_exact(4) {
796                    rgba.push(chunk[0]); // R
797                    rgba.push(chunk[1]); // G
798                    rgba.push(chunk[2]); // B
799                    rgba.push(255); // A (不透明)
800                }
801                image::RgbaImage::from_raw(w, h, rgba)
802            }
803            scap::frame::Frame::YUVFrame(f) => {
804                let w = f.width as u32;
805                let h = f.height as u32;
806                let mut rgba = Vec::with_capacity((w * h * 4) as usize);
807
808                // NV12 格式:Y 平面 + 交错 UV 平面
809                let y_plane = &f.luminance_bytes;
810                let uv_plane = &f.chrominance_bytes;
811                let y_stride = f.luminance_stride as usize;
812                let uv_stride = f.chrominance_stride as usize;
813
814                for row in 0..h as usize {
815                    for col in 0..w as usize {
816                        // 读取 Y 值(考虑步长)
817                        let y_idx = row * y_stride + col;
818                        let y = if y_idx < y_plane.len() {
819                            y_plane[y_idx] as i32
820                        } else {
821                            0
822                        };
823
824                        // 读取 U、V 值(UV 交错,每两个像素共享)
825                        let uv_row = row / 2;
826                        let uv_col = (col / 2) * 2;
827                        let uv_idx = uv_row * uv_stride + uv_col;
828                        let u = if uv_idx < uv_plane.len() {
829                            uv_plane[uv_idx] as i32
830                        } else {
831                            128
832                        };
833                        let v = if uv_idx + 1 < uv_plane.len() {
834                            uv_plane[uv_idx + 1] as i32
835                        } else {
836                            128
837                        };
838
839                        // BT.601 YUV → RGB 转换
840                        let c = 298 * (y - 16);
841                        let r = ((c + 409 * (v - 128) + 128) >> 8).clamp(0, 255) as u8;
842                        let g = ((c - 100 * (u - 128) - 208 * (v - 128) + 128) >> 8).clamp(0, 255)
843                            as u8;
844                        let b = ((c + 516 * (u - 128) + 128) >> 8).clamp(0, 255) as u8;
845
846                        rgba.push(r);
847                        rgba.push(g);
848                        rgba.push(b);
849                        rgba.push(255); // A (不透明)
850                    }
851                }
852                image::RgbaImage::from_raw(w, h, rgba)
853            }
854        }
855    }
856}
857
858#[cfg(all(target_os = "macos", feature = "screen-capture"))]
859impl ScreenCaptureFrame {
860    /// 获取帧宽度(像素)
861    pub fn width(&self) -> u32 {
862        0
863    }
864
865    /// 获取帧高度(像素)
866    pub fn height(&self) -> u32 {
867        0
868    }
869
870    /// 将帧转换为 RGBA 图像
871    pub fn to_rgba(&self) -> Option<image::RgbaImage> {
872        None
873    }
874}
875
876/// 硬件显示器的不透明标识符
877#[derive(PartialEq, Eq, Hash, Copy, Clone)]
878pub struct DisplayId(pub(crate) u64);
879
880impl DisplayId {
881    /// 从原始平台显示器标识符创建新的 `DisplayId`。
882    pub fn new(id: u64) -> Self {
883        Self(id)
884    }
885}
886
887impl From<u64> for DisplayId {
888    fn from(id: u64) -> Self {
889        Self(id)
890    }
891}
892
893impl From<DisplayId> for u64 {
894    fn from(id: DisplayId) -> Self {
895        id.0
896    }
897}
898
899impl Debug for DisplayId {
900    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
901        write!(f, "DisplayId({})", self.0)
902    }
903}
904
905/// 窗口调整大小的边缘方向
906#[derive(Debug, Clone, Copy, PartialEq, Eq)]
907pub enum ResizeEdge {
908    /// 上边缘
909    Top,
910    /// 右上角
911    TopRight,
912    /// 右边缘
913    Right,
914    /// 右下角
915    BottomRight,
916    /// 下边缘
917    Bottom,
918    /// 左下角
919    BottomLeft,
920    /// 左边缘
921    Left,
922    /// 左上角
923    TopLeft,
924}
925
926/// 描述窗口外观类型的枚举
927#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Default)]
928pub enum WindowDecorations {
929    #[default]
930    /// 服务端装饰
931    Server,
932    /// 客户端装饰
933    Client,
934}
935
936/// 描述窗口当前装饰配置的类型
937#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Default)]
938pub enum Decorations {
939    /// 窗口配置为使用服务端装饰
940    #[default]
941    Server,
942    /// 窗口配置为使用客户端装饰
943    Client {
944        /// 边缘平铺状态
945        tiling: Tiling,
946    },
947}
948
949/// 平台支持的窗口控件
950#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
951pub struct WindowControls {
952    /// 该平台是否支持全屏
953    pub fullscreen: bool,
954    /// 该平台是否支持最大化
955    pub maximize: bool,
956    /// 该平台是否支持最小化
957    pub minimize: bool,
958    /// 该平台是否支持窗口菜单
959    pub window_menu: bool,
960}
961
962impl Default for WindowControls {
963    fn default() -> Self {
964        // 默认假设所有功能都可用,除非另有说明
965        Self {
966            fullscreen: true,
967            maximize: true,
968            minimize: true,
969            window_menu: true,
970        }
971    }
972}
973
974/// [`WindowButtonLayout`] 中使用的窗口控制按钮类型。
975#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
976pub enum WindowButton {
977    /// 最小化按钮
978    Minimize,
979    /// 最大化按钮
980    Maximize,
981    /// 关闭按钮
982    Close,
983}
984
985impl WindowButton {
986    /// 返回该按钮渲染时使用的稳定元素 ID。
987    pub fn id(&self) -> &'static str {
988        match self {
989            WindowButton::Minimize => "minimize",
990            WindowButton::Maximize => "maximize",
991            WindowButton::Close => "close",
992        }
993    }
994
995    #[cfg(any(target_os = "linux", target_os = "freebsd"))]
996    fn index(&self) -> usize {
997        match self {
998            WindowButton::Minimize => 0,
999            WindowButton::Maximize => 1,
1000            WindowButton::Close => 2,
1001        }
1002    }
1003}
1004
1005/// 标题栏每侧最大的 [`WindowButton`] 数量。
1006pub const MAX_BUTTONS_PER_SIDE: usize = 3;
1007
1008/// 描述标题栏每侧出现的 [`WindowButton`]。
1009///
1010/// 在 Linux 上,此配置从桌面环境的配置中读取
1011/// (例如 GNOME 的 `gtk-decoration-layout` gsetting),通过 [`WindowButtonLayout::parse`] 解析。
1012#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1013pub struct WindowButtonLayout {
1014    /// 标题栏左侧的按钮。
1015    pub left: [Option<WindowButton>; MAX_BUTTONS_PER_SIDE],
1016    /// 标题栏右侧的按钮。
1017    pub right: [Option<WindowButton>; MAX_BUTTONS_PER_SIDE],
1018}
1019
1020#[cfg(any(target_os = "linux", target_os = "freebsd"))]
1021impl WindowButtonLayout {
1022    /// 返回 Zed 内置的 Linux 标题栏回退按钮布局。
1023    pub fn linux_default() -> Self {
1024        Self {
1025            left: [None; MAX_BUTTONS_PER_SIDE],
1026            right: [
1027                Some(WindowButton::Minimize),
1028                Some(WindowButton::Maximize),
1029                Some(WindowButton::Close),
1030            ],
1031        }
1032    }
1033
1034    /// 解析 GNOME 风格的 `button-layout` 字符串(如 `"close,minimize:maximize"`)。
1035    pub fn parse(layout_string: &str) -> Result<Self> {
1036        fn parse_side(
1037            s: &str,
1038            seen_buttons: &mut [bool; MAX_BUTTONS_PER_SIDE],
1039            unrecognized: &mut Vec<String>,
1040        ) -> [Option<WindowButton>; MAX_BUTTONS_PER_SIDE] {
1041            let mut result = [None; MAX_BUTTONS_PER_SIDE];
1042            let mut i = 0;
1043            for name in s.split(',') {
1044                let trimmed = name.trim();
1045                if trimmed.is_empty() {
1046                    continue;
1047                }
1048                let button = match trimmed {
1049                    "minimize" => Some(WindowButton::Minimize),
1050                    "maximize" => Some(WindowButton::Maximize),
1051                    "close" => Some(WindowButton::Close),
1052                    other => {
1053                        unrecognized.push(other.to_string());
1054                        None
1055                    }
1056                };
1057                if let Some(button) = button {
1058                    if seen_buttons[button.index()] {
1059                        continue;
1060                    }
1061                    if let Some(slot) = result.get_mut(i) {
1062                        *slot = Some(button);
1063                        seen_buttons[button.index()] = true;
1064                        i += 1;
1065                    }
1066                }
1067            }
1068            result
1069        }
1070
1071        let (left_str, right_str) = layout_string.split_once(':').unwrap_or(("", layout_string));
1072        let mut unrecognized = Vec::new();
1073        let mut seen_buttons = [false; MAX_BUTTONS_PER_SIDE];
1074        let layout = Self {
1075            left: parse_side(left_str, &mut seen_buttons, &mut unrecognized),
1076            right: parse_side(right_str, &mut seen_buttons, &mut unrecognized),
1077        };
1078
1079        if !unrecognized.is_empty()
1080            && layout.left.iter().all(Option::is_none)
1081            && layout.right.iter().all(Option::is_none)
1082        {
1083            bail!(
1084                "button layout string {:?} contains no valid buttons (unrecognized: {})",
1085                layout_string,
1086                unrecognized.join(", ")
1087            );
1088        }
1089
1090        Ok(layout)
1091    }
1092
1093    /// 将布局格式化为 GNOME 风格的 `button-layout` 字符串。
1094    #[cfg(test)]
1095    pub fn format(&self) -> String {
1096        fn format_side(buttons: &[Option<WindowButton>; MAX_BUTTONS_PER_SIDE]) -> String {
1097            buttons
1098                .iter()
1099                .flatten()
1100                .map(|button| match button {
1101                    WindowButton::Minimize => "minimize",
1102                    WindowButton::Maximize => "maximize",
1103                    WindowButton::Close => "close",
1104                })
1105                .collect::<Vec<_>>()
1106                .join(",")
1107        }
1108
1109        format!("{}:{}", format_side(&self.left), format_side(&self.right))
1110    }
1111}
1112
1113/// 描述窗口各边当前的平铺状态
1114#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Default)]
1115pub struct Tiling {
1116    /// 上边缘是否平铺
1117    pub top: bool,
1118    /// 左边缘是否平铺
1119    pub left: bool,
1120    /// 右边缘是否平铺
1121    pub right: bool,
1122    /// 下边缘是否平铺
1123    pub bottom: bool,
1124}
1125
1126impl Tiling {
1127    /// 创建一个所有边都平铺的 [`Tiling`] 实例。
1128    pub fn tiled() -> Self {
1129        Self {
1130            top: true,
1131            left: true,
1132            right: true,
1133            bottom: true,
1134        }
1135    }
1136
1137    /// 是否有任何边缘处于平铺状态
1138    pub fn is_tiled(&self) -> bool {
1139        self.top || self.left || self.right || self.bottom
1140    }
1141}
1142
1143/// 辅助功能适配器的回调函数。
1144pub struct A11yCallbacks {
1145    /// 适配器被激活时调用(屏幕阅读器连接)。
1146    pub activation: Box<dyn Fn() -> Option<accesskit::TreeUpdate> + Send + 'static>,
1147    /// 屏幕阅读器请求操作时调用。
1148    pub action: Box<dyn Fn(accesskit::ActionRequest) + Send + 'static>,
1149    /// 适配器被停用时调用(屏幕阅读器断开连接)。
1150    pub deactivation: Box<dyn Fn() + Send + 'static>,
1151}
1152
1153/// 帧请求选项,控制平台何时请求重绘。
1154#[derive(Debug, Copy, Clone, Eq, PartialEq, Default)]
1155pub struct RequestFrameOptions {
1156    /// 是否需要呈现帧(提交到屏幕)。
1157    pub require_presentation: bool,
1158    /// 为 `true` 时强制刷新所有渲染状态。
1159    pub force_render: bool,
1160}
1161
1162/// 平台原生窗口抽象,由各平台 crate 实现,提供窗口管理、输入、渲染等能力。
1163///
1164/// 通过 [`Platform::open_window`] 创建实例,通过 [`PlatformWindow`] trait 与窗口交互。
1165pub trait PlatformWindow: HasWindowHandle + HasDisplayHandle {
1166    /// 返回窗口在屏幕上的边界矩形(包含标题栏和边框)。
1167    fn bounds(&self) -> Bounds<Pixels>;
1168    /// 窗口是否处于最大化状态。
1169    fn is_maximized(&self) -> bool;
1170    /// 返回窗口当前边界状态(窗口化/最大化/全屏)。
1171    fn window_bounds(&self) -> WindowBounds;
1172    /// 返回窗口内容区域的尺寸(不含标题栏和边框)。
1173    fn content_size(&self) -> Size<Pixels>;
1174    /// 调整窗口内容区域的尺寸。
1175    fn resize(&mut self, size: Size<Pixels>);
1176    /// 返回窗口的显示缩放因子(如 1.0、1.5、2.0)。
1177    fn scale_factor(&self) -> f32;
1178    /// 返回窗口当前的外观模式(亮色/暗色)。
1179    fn appearance(&self) -> WindowAppearance;
1180    /// 返回窗口所在的显示器。
1181    fn display(&self) -> Option<Rc<dyn PlatformDisplay>>;
1182    /// 返回鼠标光标在窗口内的位置。
1183    fn mouse_position(&self) -> Point<Pixels>;
1184    /// 返回当前修饰键状态(Ctrl/Shift/Alt/Command)。
1185    fn modifiers(&self) -> Modifiers;
1186    /// 返回 Caps Lock 锁定状态。
1187    fn capslock(&self) -> Capslock;
1188    /// 设置输入处理器,用于处理 IME(输入法)组合文本。
1189    fn set_input_handler(&mut self, input_handler: PlatformInputHandler);
1190    /// 取出并返回当前输入处理器(take 语义)。
1191    fn take_input_handler(&mut self) -> Option<PlatformInputHandler>;
1192    /// 显示模态提示对话框,返回用户选择的按钮索引。
1193    fn prompt(
1194        &self,
1195        level: PromptLevel,
1196        msg: &str,
1197        detail: Option<&str>,
1198        answers: &[PromptButton],
1199    ) -> Option<oneshot::Receiver<usize>>;
1200    /// 在窗口的指定位置弹出 OS 原生菜单(Windows `TrackPopupMenuEx`、macOS `NSMenu`)。
1201    ///
1202    /// 菜单模态地跑在自己的事件循环里,所以选中结果只能异步回传:返回的通道在用户
1203    /// 点中某项时送出该项的 `id`,用户直接关掉菜单则通道被丢弃。
1204    ///
1205    /// 默认实现返回 `None` —— 表示该平台没有原生弹出菜单能力(Linux 的窗口菜单只能由
1206    /// 窗管自己画,装不下应用提供的项),调用方据此回退到框架自绘的菜单。
1207    fn show_native_menu(
1208        &self,
1209        _position: Point<Pixels>,
1210        _menu: NativeMenu,
1211    ) -> Option<oneshot::Receiver<SharedString>> {
1212        None
1213    }
1214    /// 将窗口置于前台并获得焦点。
1215    fn activate(&self);
1216    /// 窗口是否当前处于活动(获得焦点)状态。
1217    fn is_active(&self) -> bool;
1218    /// 鼠标光标是否悬停在窗口上方。
1219    fn is_hovered(&self) -> bool;
1220    /// 返回窗口背景外观(透明/不透明/毛玻璃)。
1221    fn background_appearance(&self) -> WindowBackgroundAppearance;
1222    /// 设置窗口标题文本。
1223    fn set_title(&mut self, title: &str);
1224    /// 设置窗口背景外观模式。
1225    fn set_background_appearance(&self, background_appearance: WindowBackgroundAppearance);
1226    /// 最小化窗口。
1227    fn minimize(&self);
1228    /// 最大化窗口(macOS 下为缩放/zoom)。
1229    fn zoom(&self);
1230    /// 切换全屏状态。
1231    fn toggle_fullscreen(&self);
1232    /// 窗口是否处于全屏状态。
1233    fn is_fullscreen(&self) -> bool;
1234    /// 注册帧请求回调,平台在需要重绘时调用。
1235    fn on_request_frame(&self, callback: Box<dyn FnMut(RequestFrameOptions)>);
1236    /// 注册输入事件回调,处理键盘、鼠标、触摸等事件。
1237    fn on_input(&self, callback: Box<dyn FnMut(PlatformInput) -> DispatchEventResult>);
1238    /// 注册窗口活动状态变化回调(获得/失去焦点时触发)。
1239    fn on_active_status_change(&self, callback: Box<dyn FnMut(bool)>);
1240    /// 注册鼠标悬停状态变化回调(进入/离开窗口时触发)。
1241    fn on_hover_status_change(&self, callback: Box<dyn FnMut(bool)>);
1242    /// 注册窗口尺寸变化回调,参数为新尺寸和缩放因子。
1243    fn on_resize(&self, callback: Box<dyn FnMut(Size<Pixels>, f32)>);
1244    /// 注册窗口位置变化回调。
1245    fn on_moved(&self, callback: Box<dyn FnMut()>);
1246    /// 注册窗口关闭请求回调,返回 `false` 可阻止关闭。
1247    fn on_should_close(&self, callback: Box<dyn FnMut() -> bool>);
1248    /// 注册窗口控件区域命中测试回调(用于自定义标题栏拖拽区域)。
1249    ///
1250    /// 只有 Windows / Web 后端会在命中测试时调用该回调;Linux 与 macOS 后端当前
1251    /// 不读取它。跨平台标题栏应改用显式鼠标事件 + `Window::start_window_move` /
1252    /// `zoom_window` / `minimize_window`,或直接使用 [`crate::title_bar::TitleBar`]。
1253    fn on_hit_test_window_control(&self, callback: Box<dyn FnMut() -> Option<WindowControlArea>>);
1254    /// 注册窗口关闭回调,窗口关闭时调用。
1255    fn on_close(&self, callback: Box<dyn FnOnce()>);
1256    /// 注册窗口外观变化回调(系统切换亮色/暗色主题时触发)。
1257    fn on_appearance_changed(&self, callback: Box<dyn FnMut()>);
1258    /// 注册窗口按钮布局变化回调(macOS 全屏按钮位置变化等)。
1259    fn on_button_layout_changed(&self, _callback: Box<dyn FnMut()>) {}
1260    /// 将渲染场景提交到窗口进行绘制。
1261    fn draw(&self, scene: &Scene);
1262    /// 通知平台当前帧已完成渲染。
1263    fn completed_frame(&self) {}
1264    /// 返回精灵图集(用于图标、表情符号等位图渲染)。
1265    fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas>;
1266    /// 是否支持亚像素渲染(ClearType 文本渲染)。
1267    fn is_subpixel_rendering_supported(&self) -> bool;
1268
1269    /// 该平台窗口是否支持 Web DOM 后端。
1270    ///
1271    /// 返回 `true` 时,核心会在每帧构建 DOM 树并通过 [`Self::dom_tree_update`] 交付,
1272    /// 桌面平台默认 `false` 以保持零开销。
1273    #[cfg(feature = "dom-backend")]
1274    fn supports_dom(&self) -> bool {
1275        false
1276    }
1277
1278    /// 交付当前帧的 DOM 树(每帧一次,仅当 `supports_dom()` 为真)。
1279    ///
1280    /// DOM 层渲染在 canvas 之上的覆盖层中(v1 接受双重绘制),
1281    /// 平台侧负责增量对账(见 `rgpui-dom` crate 的 reconcile)。
1282    #[cfg(feature = "dom-backend")]
1283    fn dom_tree_update(&self, _tree: &crate::dom::DomTree) {}
1284
1285    /// 注册 Web DOM 事件委托回调。
1286    ///
1287    /// 点击 DOM 覆盖层上的元素时,平台按 `data-gpui-id` 反查 DOM key 链并回调,
1288    /// 由核心按 key 链直接命中 hitbox(绕过坐标 hit-test)。桌面平台默认空实现。
1289    #[cfg(feature = "dom-backend")]
1290    fn on_dom_event(
1291        &self,
1292        _callback: Box<dyn FnMut(Vec<crate::DomNodeKey>, PlatformInput) -> DispatchEventResult>,
1293    ) {
1294    }
1295
1296    /// 由 DOM 后端在可滚动容器发生浏览器原生滚动(`scroll` 事件)后回调,
1297    /// 参数为事件链与滚动视口的 `scrollLeft`/`scrollTop`(向下/向右为正)。
1298    /// 默认空实现:仅 Web DOM 后端使用。
1299    #[cfg(feature = "dom-backend")]
1300    fn on_dom_scroll(&self, _callback: Box<dyn FnMut(Vec<crate::DomNodeKey>, f64, f64)>) {}
1301
1302    // macOS specific methods
1303    /// 返回窗口标题文本。
1304    fn get_title(&self) -> String {
1305        String::new()
1306    }
1307    /// 返回当前窗口的标签页组(macOS 标签页功能)。
1308    fn tabbed_windows(&self) -> Option<Vec<SystemWindowTab>> {
1309        None
1310    }
1311    /// 标签页栏是否可见。
1312    fn tab_bar_visible(&self) -> bool {
1313        false
1314    }
1315    /// 标记文档是否已编辑(macOS 窗口标题栏红点标记)。
1316    fn set_edited(&mut self, _edited: bool) {}
1317    /// 设置文档路径(macOS 标题栏显示文件名)。
1318    fn set_document_path(&self, _path: Option<&std::path::Path>) {}
1319    /// 设置 macOS 红绿灯按钮位置。
1320    #[cfg(target_os = "macos")]
1321    fn set_traffic_light_position(&self, _position: Point<Pixels>) {}
1322    /// 显示系统字符面板(emoji、特殊符号)。
1323    fn show_character_palette(&self) {}
1324    /// 处理标题栏双击事件(可自定义行为,如最大化/缩放)。
1325    fn titlebar_double_click(&self, _is_resizable: bool, _is_minimizable: bool) {}
1326    /// 注册"将标签页移至新窗口"回调。
1327    fn on_move_tab_to_new_window(&self, _callback: Box<dyn FnMut()>) {}
1328    /// 注册"合并所有窗口"回调。
1329    fn on_merge_all_windows(&self, _callback: Box<dyn FnMut()>) {}
1330    /// 注册"切换到上一个标签页"回调。
1331    fn on_select_previous_tab(&self, _callback: Box<dyn FnMut()>) {}
1332    /// 注册"切换到下一个标签页"回调。
1333    fn on_select_next_tab(&self, _callback: Box<dyn FnMut()>) {}
1334    /// 注册"切换标签页栏可见性"回调。
1335    fn on_toggle_tab_bar(&self, _callback: Box<dyn FnMut()>) {}
1336    /// 合并所有窗口为一个窗口的标签页。
1337    fn merge_all_windows(&self) {}
1338    /// 将当前标签页移至新窗口。
1339    fn move_tab_to_new_window(&self) {}
1340    /// 切换标签页总览视图(macOS Exposé 风格)。
1341    fn toggle_window_tab_overview(&self) {}
1342    /// 设置窗口的 tabbing identifier(控制标签页分组)。
1343    fn set_tabbing_identifier(&self, _identifier: Option<String>) {}
1344
1345    /// 返回窗口的原始 HWND 句柄(仅 Windows;后端 `open_window` 登记用)。
1346    #[cfg(target_os = "windows")]
1347    fn get_raw_handle(&self) -> windows::Win32::Foundation::HWND;
1348
1349    /// 返回窗口的内部边界(Linux 下包含 CSD 装饰区域)。
1350    fn inner_window_bounds(&self) -> WindowBounds {
1351        self.window_bounds()
1352    }
1353    /// 请求设置窗口装饰模式(客户端装饰/服务端装饰)。
1354    fn request_decorations(&self, _decorations: WindowDecorations) {}
1355    /// 在指定位置显示窗口系统菜单(Linux 右键标题栏)。
1356    fn show_window_menu(&self, _position: Point<Pixels>) {}
1357    /// 启动窗口拖拽移动(Linux CSD 模式下从自定义标题栏触发)。
1358    fn start_window_move(&self) {}
1359    /// 启动窗口边缘调整大小(Linux CSD 模式下从自定义边框触发)。
1360    fn start_window_resize(&self, _edge: ResizeEdge) {}
1361    /// 设置窗口输入区域(指定哪些区域接收鼠标事件,其余区域穿透)。
1362    fn set_input_region(&self, _region: Option<&[Bounds<Pixels>]>) {}
1363    /// 返回当前窗口装饰类型(客户端/服务端/无装饰)。
1364    fn window_decorations(&self) -> Decorations {
1365        Decorations::Server
1366    }
1367    /// 设置 Wayland app_id(用于窗口标识和桌面集成)。
1368    fn set_app_id(&mut self, _app_id: &str) {}
1369    /// 映射窗口(X11 下将窗口显示到屏幕)。
1370    ///
1371    /// Wayland 没有对应的显式操作:窗口在建窗时 `surface.commit()` 即隐式映射,
1372    /// 走此默认实现返回 `Ok(())` 并非失败,而是「平台隐式完成」。
1373    fn map_window(&mut self) -> anyhow::Result<()> {
1374        Ok(())
1375    }
1376    /// 返回窗口控件信息(最小化/最大化/关闭按钮位置)。
1377    fn window_controls(&self) -> WindowControls {
1378        WindowControls::default()
1379    }
1380    /// 设置客户端区域的内边距(Wayland layer-shell 排除区域)。
1381    fn set_client_inset(&self, _inset: Pixels) {}
1382    /// 返回 GPU 硬件信息(设备名称、显存等)。
1383    fn gpu_specs(&self) -> Option<GpuSpecs>;
1384
1385    /// 更新输入法(IME)候选框的位置。
1386    fn update_ime_position(&self, _bounds: Bounds<Pixels>);
1387
1388    /// 播放系统提示音。
1389    fn play_system_bell(&self) {}
1390
1391    /// 初始化辅助功能适配器,注册辅助功能回调。
1392    fn a11y_init(&self, _callbacks: A11yCallbacks) {}
1393
1394    /// 向辅助功能适配器提供无障碍树更新数据(accesskit)。
1395    fn a11y_tree_update(&self, _tree_update: accesskit::TreeUpdate) {}
1396
1397    /// 使用指定场景渲染到 RGBA 图像纹理(仅测试用途)。
1398    #[cfg(any(test, feature = "test-support"))]
1399    fn as_test(&mut self) -> Option<&mut TestWindow> {
1400        None
1401    }
1402
1403    /// 将给定场景渲染到纹理并返回 RGBA 像素数据(仅测试用途)。
1404    /// 不会将帧呈现到屏幕,用于视觉测试。
1405    #[cfg(any(test, feature = "test-support"))]
1406    fn render_to_image(&self, _scene: &Scene) -> Result<RgbaImage> {
1407        anyhow::bail!("render_to_image not implemented for this platform")
1408    }
1409
1410    /// 为窗口保留多少屏幕空间(逻辑像素),使其他窗口不遮挡它。
1411    ///
1412    /// Wayland 走 layer-shell 的 `set_exclusive_zone`,X11 走 EWMH strut
1413    /// (`_NET_WM_STRUT_PARTIAL`);两边口径一致:从 `set_exclusive_edge` 指定的
1414    /// 屏幕边缘起,往外保留这么宽的一条区域,贴边面板取面板自身高度即可。
1415    /// 非正值表示不保留。只有面板类窗口(layer-shell / DOCK)设置才有意义。
1416    fn set_exclusive_zone(&self, _zone: Pixels) {}
1417    /// 指定 [`Self::set_exclusive_zone`] 作用于哪条屏幕边缘,必须是单一边缘
1418    /// (`TOP` / `BOTTOM` / `LEFT` / `RIGHT` 之一),多bit会被忽略。
1419    ///
1420    /// Wayland 只在角锚定表面上需要它,其余情况边缘由锚点推断;X11 的 strut
1421    /// 没有「保留哪条边」的默认推断,必须先确定边缘才会写入。
1422    #[cfg(all(target_os = "linux", any(feature = "wayland", feature = "x11")))]
1423    fn set_exclusive_edge(&self, _edge: layer_shell::Anchor) {}
1424
1425    /// 请求用户注意力(任务栏闪烁/弹跳,提示用户查看窗口)。
1426    ///
1427    /// 只有 X11 真正实现(ICCM `WM_HINTS` urgency 位);Wayland 无对应协议、
1428    /// Windows 与 macOS 也未实现,走默认空操作。需要跨端提示时请改用
1429    /// `App::show_notification`。
1430    fn request_attention(&self) {}
1431
1432    /// 请求再出一帧(即使窗口当前没有失效区域)。
1433    ///
1434    /// 场景里有定时变换动画时由帧循环调用:动画只推进场景里的精灵、不重绘视图,
1435    /// 但仍然需要平台再交付一次帧回调。
1436    ///
1437    /// **默认实现为空**。各平台的实际情况:
1438    /// - Windows:`RedrawWindow(RDW_INVALIDATE|RDW_NOERASE|RDW_NOFRAME)`;
1439    /// - macOS:CVDisplayLink 以屏幕刷新率持续驱动帧回调,无需显式请求;
1440    /// - Wayland:`complete_frame` 的 `surface.commit()` 会触发合成器的帧回调;
1441    /// - X11:尚未实现(需要在 xcb 连接上异步投递重绘请求;同步调 `refresh`
1442    ///   会在帧回调里递归,不能照抄)。X11 上动画目前只在其它事件引起出帧时推进。
1443    fn request_frame(&self) {}
1444
1445    /// 设置窗口在屏幕上的位置。
1446    ///
1447    /// X11 / Windows 会真正设置;Wayland 只改内部 geometry,合成器可不尊重该请求;
1448    /// macOS 当前为空操作。调用方不应假定位置一定生效。
1449    fn set_position(&mut self, _position: Point<Pixels>) {}
1450
1451    /// 隐藏窗口(从任务栏移除,托盘模式下使用)。
1452    fn hide(&self) {}
1453
1454    /// 设置鼠标事件是否穿透窗口(桌面宠物/覆盖层场景)。
1455    fn set_mouse_passthrough(&self, _passthrough: bool) {}
1456
1457    /// 设置标题栏是否可见(控制自定义标题栏/原生标题栏切换)。
1458    ///
1459    /// Windows 切换标准窗口样式,X11 清零 Motif `_MOTIF_WM_HINTS` 的装饰位(整个原生
1460    /// 框架消失);Wayland 没有对应协议,macOS 侧未实现,两者都是空操作。
1461    fn set_titlebar_visible(&self, _visible: bool) {}
1462
1463    /// 设置输入框的语义内容类型(如 `password`、`email`),
1464    /// 供系统输入法/自动填充识别。macOS 通过 `NSTextContent` 实现,其他平台为空操作。
1465    fn set_text_content_type(&self, _content_type: Option<&'static str>) {}
1466}
1467
1468/// 无头窗口渲染器,可生成真实渲染输出。
1469#[cfg(any(test, feature = "test-support"))]
1470pub trait PlatformHeadlessRenderer {
1471    /// 渲染场景并作为 RGBA 图像返回结果
1472    fn render_scene_to_image(
1473        &mut self,
1474        scene: &Scene,
1475        size: Size<DevicePixels>,
1476    ) -> Result<RgbaImage>;
1477
1478    /// 渲染场景到离屏目标,不读取结果
1479    ///
1480    /// 这是绘制到真实窗口的无头等效操作:它执行与绘制到真实窗口相同的 CPU 端场景编码和 GPU 提交,但不阻塞 GPU 完成或复制像素回来
1481    fn render_scene(&mut self, scene: &Scene, size: Size<DevicePixels>) -> Result<()>;
1482
1483    /// 返回此渲染器使用的精灵图集
1484    fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas>;
1485}
1486
1487/// 带元数据的可运行任务类型别名。
1488/// 之前是单变体枚举,现在简化为直接类型别名。
1489#[doc(hidden)]
1490pub type RunnableVariant = Runnable<RunnableMeta>;
1491
1492#[doc(hidden)]
1493pub type TimerResolutionGuard = rgpui_util::Deferred<Box<dyn FnOnce() + Send>>;
1494
1495#[doc(hidden)]
1496pub enum TasksIncluded {
1497    OnlyCompleted,
1498    CompletedAndRunning,
1499}
1500
1501/// 此类型公开是为了测试宏可以生成和使用它,但不应视为公共 API 的一部分。
1502#[doc(hidden)]
1503pub trait PlatformDispatcher: Send + Sync {
1504    fn is_main_thread(&self) -> bool;
1505    fn dispatch(&self, runnable: RunnableVariant, priority: Priority);
1506    fn dispatch_on_main_thread(&self, runnable: RunnableVariant, priority: Priority);
1507    fn dispatch_after(&self, duration: Duration, runnable: RunnableVariant);
1508
1509    fn spawn_realtime(&self, f: Box<dyn FnOnce() + Send>);
1510
1511    fn now(&self) -> Instant {
1512        Instant::now()
1513    }
1514
1515    fn increase_timer_resolution(&self) -> TimerResolutionGuard {
1516        rgpui_util::defer(Box::new(|| {}))
1517    }
1518
1519    #[cfg(any(test, feature = "test-support"))]
1520    fn as_test(&self) -> Option<&TestDispatcher> {
1521        None
1522    }
1523
1524    // 此 cfg 必须与 `threaded_dispatcher` 模块的匹配,该模块在编译时实现此方法
1525    #[cfg(all(
1526        any(test, feature = "test-support"),
1527        any(
1528            target_os = "windows",
1529            target_os = "linux",
1530            target_os = "macos",
1531            target_family = "wasm"
1532        )
1533    ))]
1534    fn as_threaded(&self) -> Option<&ThreadedDispatcher> {
1535        None
1536    }
1537}
1538
1539/// 平台文本系统抽象 — 提供字体加载、字形光栅化、文本排版等能力。各平台需实现此 trait。
1540pub trait PlatformTextSystem: Send + Sync {
1541    /// 加载指定的字体数据(TTF/OTF 字节流)。
1542    fn add_fonts(&self, fonts: Vec<Cow<'static, [u8]>>) -> Result<()>;
1543    /// 获取所有可用的字体名称。
1544    fn all_font_names(&self) -> Vec<String>;
1545    /// 根据字体描述符获取字体 ID。
1546    fn font_id(&self, descriptor: &Font) -> Result<FontId>;
1547    /// 获取字体的度量信息。
1548    fn font_metrics(&self, font_id: FontId) -> FontMetrics;
1549    /// 获取字形的排版边界。
1550    fn typographic_bounds(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Bounds<f32>>;
1551    /// 获取字形的前进宽度。
1552    fn advance(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>>;
1553    /// 获取字符对应的字形 ID。
1554    fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId>;
1555    /// 获取字形的光栅化边界。
1556    fn glyph_raster_bounds(&self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>>;
1557    /// 光栅化字形。
1558    fn rasterize_glyph(
1559        &self,
1560        params: &RenderGlyphParams,
1561        raster_bounds: Bounds<DevicePixels>,
1562    ) -> Result<(Size<DevicePixels>, Vec<u8>)>;
1563    /// 使用给定的字体运行(Font Run)排版一行文本。
1564    fn layout_line(&self, text: &str, font_size: Pixels, runs: &[FontRun]) -> LineLayout;
1565    /// 返回给定字体和大小的推荐文本渲染模式。
1566    fn recommended_rendering_mode(&self, _font_id: FontId, _font_size: Pixels)
1567    -> TextRenderingMode;
1568    /// 返回以给定颜色绘制字形时使用的膨胀级别。
1569    fn glyph_dilation_for_color(&self, _color: Hsla) -> u8 {
1570        0
1571    }
1572}
1573
1574/// 空操作文本系统实现,所有方法返回默认值。用于测试或无文本系统需求的平台。
1575pub struct NoopTextSystem;
1576
1577impl NoopTextSystem {
1578    /// 创建一个新的空操作文本系统实例。
1579    pub fn new() -> Self {
1580        Self
1581    }
1582}
1583
1584impl PlatformTextSystem for NoopTextSystem {
1585    fn add_fonts(&self, _fonts: Vec<Cow<'static, [u8]>>) -> Result<()> {
1586        Ok(())
1587    }
1588
1589    fn all_font_names(&self) -> Vec<String> {
1590        Vec::new()
1591    }
1592
1593    fn font_id(&self, _descriptor: &Font) -> Result<FontId> {
1594        Ok(FontId(1))
1595    }
1596
1597    fn font_metrics(&self, _font_id: FontId) -> FontMetrics {
1598        FontMetrics {
1599            units_per_em: 1000,
1600            ascent: 1025.0,
1601            descent: -275.0,
1602            line_gap: 0.0,
1603            underline_position: -95.0,
1604            underline_thickness: 60.0,
1605            cap_height: 698.0,
1606            x_height: 516.0,
1607            bounding_box: Bounds {
1608                origin: Point {
1609                    x: -260.0,
1610                    y: -245.0,
1611                },
1612                size: Size {
1613                    width: 1501.0,
1614                    height: 1364.0,
1615                },
1616            },
1617        }
1618    }
1619
1620    fn typographic_bounds(&self, _font_id: FontId, _glyph_id: GlyphId) -> Result<Bounds<f32>> {
1621        Ok(Bounds {
1622            origin: Point { x: 54.0, y: 0.0 },
1623            size: size(392.0, 528.0),
1624        })
1625    }
1626
1627    fn advance(&self, _font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>> {
1628        Ok(size(600.0 * glyph_id.0 as f32, 0.0))
1629    }
1630
1631    fn glyph_for_char(&self, _font_id: FontId, ch: char) -> Option<GlyphId> {
1632        Some(GlyphId(ch.len_utf16() as u32))
1633    }
1634
1635    fn glyph_raster_bounds(&self, _params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>> {
1636        Ok(Default::default())
1637    }
1638
1639    fn rasterize_glyph(
1640        &self,
1641        _params: &RenderGlyphParams,
1642        raster_bounds: Bounds<DevicePixels>,
1643    ) -> Result<(Size<DevicePixels>, Vec<u8>)> {
1644        Ok((raster_bounds.size, Vec::new()))
1645    }
1646
1647    fn layout_line(&self, text: &str, font_size: Pixels, _runs: &[FontRun]) -> LineLayout {
1648        let mut position = px(0.);
1649        let metrics = self.font_metrics(FontId(0));
1650        // NoopTextSystem 自身的 glyph_for_char 恒返回 Some、advance 恒返回 Ok
1651        let glyph = invariant(
1652            self.glyph_for_char(FontId(0), 'm'),
1653            "NoopTextSystem:字符 'm' 必有字形",
1654        );
1655        let advance = invariant_result(
1656            self.advance(FontId(0), glyph),
1657            "NoopTextSystem:advance 必成功",
1658        );
1659        let em_width = font_size * advance.width / metrics.units_per_em as f32;
1660        let mut glyphs = Vec::new();
1661        for (ix, c) in text.char_indices() {
1662            if let Some(glyph) = self.glyph_for_char(FontId(0), c) {
1663                glyphs.push(ShapedGlyph {
1664                    id: glyph,
1665                    position: point(position, px(0.)),
1666                    index: ix,
1667                    is_emoji: glyph.0 == 2,
1668                });
1669                if glyph.0 == 2 {
1670                    position += em_width * 2.0;
1671                } else {
1672                    position += em_width;
1673                }
1674            } else {
1675                position += em_width
1676            }
1677        }
1678        let mut runs = Vec::default();
1679        if !glyphs.is_empty() {
1680            runs.push(ShapedRun {
1681                font_id: FontId(0),
1682                glyphs,
1683            });
1684        } else {
1685            position = px(0.);
1686        }
1687
1688        LineLayout {
1689            font_size,
1690            width: position,
1691            ascent: font_size * (metrics.ascent / metrics.units_per_em as f32),
1692            descent: font_size * (metrics.descent / metrics.units_per_em as f32),
1693            runs,
1694            len: text.len(),
1695        }
1696    }
1697
1698    fn recommended_rendering_mode(
1699        &self,
1700        _font_id: FontId,
1701        _font_size: Pixels,
1702    ) -> TextRenderingMode {
1703        TextRenderingMode::Grayscale
1704    }
1705}
1706
1707// Adapted from https://github.com/microsoft/terminal/blob/1283c0f5b99a2961673249fa77c6b986efb5086c/src/renderer/atlas/dwrite.cpp
1708// Copyright (c) Microsoft Corporation.
1709// Licensed under the MIT license.
1710/// 计算亚像素文本渲染的伽马校正比率。
1711pub fn get_gamma_correction_ratios(gamma: f32) -> [f32; 4] {
1712    const GAMMA_INCORRECT_TARGET_RATIOS: [[f32; 4]; 13] = [
1713        [0.0000 / 4.0, 0.0000 / 4.0, 0.0000 / 4.0, 0.0000 / 4.0], // gamma = 1.0
1714        [0.0166 / 4.0, -0.0807 / 4.0, 0.2227 / 4.0, -0.0751 / 4.0], // gamma = 1.1
1715        [0.0350 / 4.0, -0.1760 / 4.0, 0.4325 / 4.0, -0.1370 / 4.0], // gamma = 1.2
1716        [0.0543 / 4.0, -0.2821 / 4.0, 0.6302 / 4.0, -0.1876 / 4.0], // gamma = 1.3
1717        [0.0739 / 4.0, -0.3963 / 4.0, 0.8167 / 4.0, -0.2287 / 4.0], // gamma = 1.4
1718        [0.0933 / 4.0, -0.5161 / 4.0, 0.9926 / 4.0, -0.2616 / 4.0], // gamma = 1.5
1719        [0.1121 / 4.0, -0.6395 / 4.0, 1.1588 / 4.0, -0.2877 / 4.0], // gamma = 1.6
1720        [0.1300 / 4.0, -0.7649 / 4.0, 1.3159 / 4.0, -0.3080 / 4.0], // gamma = 1.7
1721        [0.1469 / 4.0, -0.8911 / 4.0, 1.4644 / 4.0, -0.3234 / 4.0], // gamma = 1.8
1722        [0.1627 / 4.0, -1.0170 / 4.0, 1.6051 / 4.0, -0.3347 / 4.0], // gamma = 1.9
1723        [0.1773 / 4.0, -1.1420 / 4.0, 1.7385 / 4.0, -0.3426 / 4.0], // gamma = 2.0
1724        [0.1908 / 4.0, -1.2652 / 4.0, 1.8650 / 4.0, -0.3476 / 4.0], // gamma = 2.1
1725        [0.2031 / 4.0, -1.3864 / 4.0, 1.9851 / 4.0, -0.3501 / 4.0], // gamma = 2.2
1726    ];
1727
1728    const NORM13: f32 = ((0x10000 as f64) / (255.0 * 255.0) * 4.0) as f32;
1729    const NORM24: f32 = ((0x100 as f64) / (255.0) * 4.0) as f32;
1730
1731    let index = ((gamma * 10.0).round() as usize).clamp(10, 22) - 10;
1732    let ratios = GAMMA_INCORRECT_TARGET_RATIOS[index];
1733
1734    [
1735        ratios[0] * NORM13,
1736        ratios[1] * NORM24,
1737        ratios[2] * NORM13,
1738        ratios[3] * NORM24,
1739    ]
1740}
1741
1742/// 精灵图集的缓存键,标识一种可渲染的图元(字形、SVG 或图像)。
1743#[derive(PartialEq, Eq, Hash, Clone)]
1744pub enum AtlasKey {
1745    /// 字形图元
1746    Glyph(RenderGlyphParams),
1747    /// SVG 矢量图元
1748    Svg(RenderSvgParams),
1749    /// 位图图像图元
1750    Image(RenderImageParams),
1751}
1752
1753impl AtlasKey {
1754    /// 返回该图集键的纹理类型。
1755    pub fn texture_kind(&self) -> AtlasTextureKind {
1756        match self {
1757            AtlasKey::Glyph(params) => {
1758                if params.is_emoji {
1759                    AtlasTextureKind::Polychrome
1760                } else if params.subpixel_rendering {
1761                    AtlasTextureKind::Subpixel
1762                } else {
1763                    AtlasTextureKind::Monochrome
1764                }
1765            }
1766            AtlasKey::Svg(_) => AtlasTextureKind::Monochrome,
1767            AtlasKey::Image(_) => AtlasTextureKind::Polychrome,
1768        }
1769    }
1770}
1771
1772impl From<RenderGlyphParams> for AtlasKey {
1773    fn from(params: RenderGlyphParams) -> Self {
1774        Self::Glyph(params)
1775    }
1776}
1777
1778impl From<RenderSvgParams> for AtlasKey {
1779    fn from(params: RenderSvgParams) -> Self {
1780        Self::Svg(params)
1781    }
1782}
1783
1784impl From<RenderImageParams> for AtlasKey {
1785    fn from(params: RenderImageParams) -> Self {
1786        Self::Image(params)
1787    }
1788}
1789
1790/// 平台精灵图集抽象 — 管理 GPU 纹理中的图元缓存(字形、SVG、图像)。
1791pub trait PlatformAtlas {
1792    /// 根据键获取图集瓦片,若不存在则通过 build 闭包创建并插入。
1793    fn get_or_insert_with<'a>(
1794        &self,
1795        key: &AtlasKey,
1796        build: &mut dyn FnMut() -> Result<Option<(Size<DevicePixels>, Cow<'a, [u8]>)>>,
1797    ) -> Result<Option<AtlasTile>>;
1798    /// 从图集中移除指定键对应的瓦片。
1799    fn remove(&self, key: &AtlasKey);
1800    /// 测试断言用:图集是否包含指定键(默认实现恒返回 false)。
1801    #[cfg(any(test, feature = "test-support"))]
1802    fn contains(&self, _key: &AtlasKey) -> bool {
1803        false
1804    }
1805}
1806
1807#[doc(hidden)]
1808pub struct AtlasTextureList<T> {
1809    pub textures: Vec<Option<T>>,
1810    pub free_list: Vec<usize>,
1811}
1812
1813impl<T> Default for AtlasTextureList<T> {
1814    fn default() -> Self {
1815        Self {
1816            textures: Vec::default(),
1817            free_list: Vec::default(),
1818        }
1819    }
1820}
1821
1822impl<T> ops::Index<usize> for AtlasTextureList<T> {
1823    type Output = Option<T>;
1824
1825    fn index(&self, index: usize) -> &Self::Output {
1826        &self.textures[index]
1827    }
1828}
1829
1830impl<T> AtlasTextureList<T> {
1831    #[allow(unused)]
1832    pub fn drain(&mut self) -> std::vec::Drain<'_, Option<T>> {
1833        self.free_list.clear();
1834        self.textures.drain(..)
1835    }
1836
1837    pub fn iter_mut(&mut self) -> impl DoubleEndedIterator<Item = &mut T> {
1838        self.textures.iter_mut().flatten()
1839    }
1840}
1841
1842/// 精灵图集中的一块瓦片,描述其在纹理中的位置和边距。
1843#[derive(Copy, Clone, Debug, PartialEq, Eq)]
1844#[repr(C)]
1845pub struct AtlasTile {
1846    /// 该瓦片所属的纹理。
1847    pub texture_id: AtlasTextureId,
1848    /// 该瓦片在其纹理内的唯一 ID。
1849    pub tile_id: TileId,
1850    /// 瓦片内容周围的像素边距。
1851    pub padding: u32,
1852    /// 该瓦片在纹理中的边界区域。
1853    pub bounds: Bounds<DevicePixels>,
1854}
1855
1856/// 图集纹理的唯一标识符,包含索引和内容类型。
1857#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1858#[repr(C)]
1859pub struct AtlasTextureId {
1860    // 使用 u32 而非 usize 以兼容 Metal Shader Language
1861    /// 该纹理在图集中的索引。
1862    pub index: u32,
1863    /// 该纹理中存储的内容类型。
1864    pub kind: AtlasTextureKind,
1865}
1866
1867#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1868#[repr(C)]
1869/// 图集纹理的内容类型,决定颜色格式和渲染路径。
1870pub enum AtlasTextureKind {
1871    /// 单色(灰度字形)
1872    Monochrome,
1873    /// 多色(彩色图像、Emoji)
1874    Polychrome,
1875    /// 亚像素渲染(LCD 抗锯齿字形)
1876    Subpixel,
1877}
1878
1879/// 图集瓦片的唯一标识符,封装 etagere 分配器的序列化 ID。
1880#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
1881#[repr(C)]
1882pub struct TileId(pub u32);
1883
1884impl From<etagere::AllocId> for TileId {
1885    fn from(id: etagere::AllocId) -> Self {
1886        Self(id.serialize())
1887    }
1888}
1889
1890impl From<TileId> for etagere::AllocId {
1891    fn from(id: TileId) -> Self {
1892        Self::deserialize(id.0)
1893    }
1894}
1895
1896/// 平台输入处理器,封装异步窗口上下文和文本输入回调,处理选区、标记文本等 IME 操作。
1897pub struct PlatformInputHandler {
1898    cx: AsyncWindowContext,
1899    handler: Box<dyn InputHandler>,
1900}
1901
1902impl PlatformInputHandler {
1903    /// 创建新的输入处理器。
1904    pub fn new(cx: AsyncWindowContext, handler: Box<dyn InputHandler>) -> Self {
1905        Self { cx, handler }
1906    }
1907
1908    /// 获取当前选中的文本范围(UTF-16 偏移)。
1909    pub fn selected_text_range(&mut self, ignore_disabled_input: bool) -> Option<UTF16Selection> {
1910        self.cx
1911            .update(|window, cx| {
1912                self.handler
1913                    .selected_text_range(ignore_disabled_input, window, cx)
1914            })
1915            .ok()
1916            .flatten()
1917    }
1918
1919    /// 获取当前标记(未确认)文本的范围。
1920    pub fn marked_text_range(&mut self) -> Option<Range<usize>> {
1921        self.cx
1922            .update(|window, cx| self.handler.marked_text_range(window, cx))
1923            .ok()
1924            .flatten()
1925    }
1926
1927    /// 获取指定 UTF-16 范围内的文本内容。
1928    pub fn text_for_range(
1929        &mut self,
1930        range_utf16: Range<usize>,
1931        adjusted: &mut Option<Range<usize>>,
1932    ) -> Option<String> {
1933        self.cx
1934            .update(|window, cx| {
1935                self.handler
1936                    .text_for_range(range_utf16, adjusted, window, cx)
1937            })
1938            .ok()
1939            .flatten()
1940    }
1941
1942    /// 替换指定范围内的文本。
1943    pub fn replace_text_in_range(&mut self, replacement_range: Option<Range<usize>>, text: &str) {
1944        self.cx
1945            .update(|window, cx| {
1946                self.handler
1947                    .replace_text_in_range(replacement_range, text, window, cx);
1948            })
1949            .ok();
1950    }
1951
1952    /// 替换指定范围内的文本并设置标记(IME 组合文本)。
1953    pub fn replace_and_mark_text_in_range(
1954        &mut self,
1955        range_utf16: Option<Range<usize>>,
1956        new_text: &str,
1957        new_selected_range: Option<Range<usize>>,
1958    ) {
1959        self.cx
1960            .update(|window, cx| {
1961                self.handler.replace_and_mark_text_in_range(
1962                    range_utf16,
1963                    new_text,
1964                    new_selected_range,
1965                    window,
1966                    cx,
1967                )
1968            })
1969            .ok();
1970    }
1971
1972    /// 清除标记文本(确认输入)。
1973    pub fn unmark_text(&mut self) {
1974        self.cx
1975            .update(|window, cx| self.handler.unmark_text(window, cx))
1976            .ok();
1977    }
1978
1979    /// 获取指定 UTF-16 范围在屏幕上的边界矩形。
1980    pub fn bounds_for_range(&mut self, range_utf16: Range<usize>) -> Option<Bounds<Pixels>> {
1981        self.cx
1982            .update(|window, cx| self.handler.bounds_for_range(range_utf16, window, cx))
1983            .ok()
1984            .flatten()
1985    }
1986
1987    /// macOS: 是否启用长按弹出字符面板功能。
1988    pub fn apple_press_and_hold_enabled(&mut self) -> bool {
1989        self.handler.apple_press_and_hold_enabled()
1990    }
1991
1992    /// 直接分发文本输入(绕过 IME 组合流程)。
1993    pub fn dispatch_input(&mut self, input: &str, window: &mut Window, cx: &mut App) {
1994        self.handler.replace_text_in_range(None, input, window, cx);
1995    }
1996
1997    /// 计算 IME 候选框的屏幕位置(基于标记文本范围和选区位置)。
1998    pub fn compute_ime_candidate_bounds(
1999        marked_range: Option<Range<usize>>,
2000        selection: &UTF16Selection,
2001        mut bounds_for_range: impl FnMut(Range<usize>) -> Option<Bounds<Pixels>>,
2002    ) -> Option<Bounds<Pixels>> {
2003        if let Some(marked_range) = marked_range {
2004            // Default to the start of the marked (composing) range.
2005            let mut line_start = marked_range.start;
2006
2007            // Walk backward from the caret looking for a line break. A change in
2008            // the Y coordinate means we crossed into the previous visual line, so
2009            // the line start is one position after the break point.
2010            let caret = selection.range.end;
2011            if let Some(caret_bounds) = bounds_for_range(caret..caret) {
2012                for i in (marked_range.start..caret).rev() {
2013                    if let Some(b) = bounds_for_range(i..i) {
2014                        if (b.origin.y - caret_bounds.origin.y).abs() > px(0.1) {
2015                            line_start = i + 1;
2016                            break;
2017                        }
2018                    }
2019                }
2020            }
2021            bounds_for_range(line_start..line_start)
2022        } else {
2023            // No active composition  — use the selection endpoint.
2024            let offset = if selection.reversed {
2025                selection.range.start
2026            } else {
2027                selection.range.end
2028            };
2029            bounds_for_range(offset..offset)
2030        }
2031    }
2032
2033    /// 获取当前选中文本的边界框。
2034    pub fn selected_bounds(&mut self, window: &mut Window, cx: &mut App) -> Option<Bounds<Pixels>> {
2035        let marked_range = self.handler.marked_text_range(window, cx);
2036        let selection = self.handler.selected_text_range(true, window, cx)?;
2037        Self::compute_ime_candidate_bounds(marked_range, &selection, |range| {
2038            self.handler.bounds_for_range(range, window, cx)
2039        })
2040    }
2041
2042    /// 获取 IME 候选区域的边界框。
2043    pub fn ime_candidate_bounds(&mut self) -> Option<Bounds<Pixels>> {
2044        let marked_range = self.marked_text_range();
2045        let selection = self.selected_text_range(true)?;
2046        Self::compute_ime_candidate_bounds(marked_range, &selection, |range| {
2047            self.bounds_for_range(range)
2048        })
2049    }
2050
2051    /// 根据屏幕坐标返回最近的字符索引。
2052    #[allow(unused)]
2053    pub fn character_index_for_point(&mut self, point: Point<Pixels>) -> Option<usize> {
2054        self.cx
2055            .update(|window, cx| self.handler.character_index_for_point(point, window, cx))
2056            .ok()
2057            .flatten()
2058    }
2059
2060    /// 查询当前是否接受文本输入。
2061    pub fn accepts_text_input(&mut self, window: &mut Window, cx: &mut App) -> bool {
2062        self.handler.accepts_text_input(window, cx)
2063    }
2064
2065    /// 查询当前是否接受文本输入(异步版本)。
2066    pub fn query_accepts_text_input(&mut self) -> bool {
2067        self.cx
2068            .update(|window, cx| self.handler.accepts_text_input(window, cx))
2069            .unwrap_or(true)
2070    }
2071
2072    /// 参见 [`InputHandler::prefers_ime_for_printable_keys`]。
2073    ///
2074    /// 这不是对处理器简单的委托:当多按键绑定处于待处理状态时,无论处理器的偏好如何,
2075    /// 该函数都会返回 `false`,因为下一个可打印按键可能完成一个前缀已绕过 IME 的绑定。
2076    pub fn query_prefers_ime_for_printable_keys(&mut self) -> bool {
2077        self.cx
2078            .update(|window, cx| {
2079                // 下一个可打印按键可能完成一个前缀已绕过 IME 的按键组合。
2080                !window.has_pending_keystrokes()
2081                    && self.handler.prefers_ime_for_printable_keys(window, cx)
2082            })
2083            .unwrap_or(false)
2084    }
2085}
2086
2087/// 表示文本缓冲区中的选区,以 UTF16 字符为单位。
2088/// 与 Range 不同,选区的头部可能在尾部之前。
2089#[derive(Debug)]
2090pub struct UTF16Selection {
2091    /// 该选区对应的文档中文本的范围(以 UTF16 字符为单位)。
2092    pub range: Range<usize>,
2093    /// 选区的头部是否在范围的起始位置(true)或结束位置(false)。
2094    pub reversed: bool,
2095}
2096
2097/// Zed 的平台 IME 系统文本输入处理接口。
2098/// 目前是 NSTextInputClient API 的 1:1 映射:
2099///
2100/// <https://developer.apple.com/documentation/appkit/nstextinputclient>
2101pub trait InputHandler: 'static {
2102    /// 获取用户当前选中文本的范围(如果有)。
2103    /// 对应 [selectedRange()](https://developer.apple.com/documentation/appkit/nstextinputclient/1438242-selectedrange)
2104    ///
2105    /// 返回值以 UTF-16 字符为单位,范围从 0 到文档长度。
2106    fn selected_text_range(
2107        &mut self,
2108        ignore_disabled_input: bool,
2109        window: &mut Window,
2110        cx: &mut App,
2111    ) -> Option<UTF16Selection>;
2112
2113    /// 获取当前标记(未确认)文本的范围(如果有)。
2114    /// 对应 [markedRange()](https://developer.apple.com/documentation/appkit/nstextinputclient/1438250-markedrange)
2115    ///
2116    /// 返回值以 UTF-16 字符为单位,范围从 0 到文档长度。
2117    fn marked_text_range(&mut self, window: &mut Window, cx: &mut App) -> Option<Range<usize>>;
2118
2119    /// 获取给定文档范围内的文本(以 UTF-16 字符为单位)。
2120    /// 对应 [attributedSubstring(forProposedRange: actualRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438238-attributedsubstring)
2121    ///
2122    /// range_utf16 以 UTF-16 字符为单位。
2123    fn text_for_range(
2124        &mut self,
2125        range_utf16: Range<usize>,
2126        adjusted_range: &mut Option<Range<usize>>,
2127        window: &mut Window,
2128        cx: &mut App,
2129    ) -> Option<String>;
2130
2131    /// 用给定文本替换文档中指定范围的文本。
2132    /// 对应 [insertText(_:replacementRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438258-inserttext)
2133    ///
2134    /// replacement_range 以 UTF-16 字符为单位。
2135    fn replace_text_in_range(
2136        &mut self,
2137        replacement_range: Option<Range<usize>>,
2138        text: &str,
2139        window: &mut Window,
2140        cx: &mut App,
2141    );
2142
2143    /// 用给定文本替换文档中指定范围的文本,
2144    /// 并将给定文本标记为 IME「组合」状态的一部分。
2145    /// 对应 [setMarkedText(_:selectedRange:replacementRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438246-setmarkedtext)
2146    ///
2147    /// range_utf16 以 UTF-16 字符为单位。
2148    /// new_selected_range 以 UTF-16 字符为单位。
2149    fn replace_and_mark_text_in_range(
2150        &mut self,
2151        range_utf16: Option<Range<usize>>,
2152        new_text: &str,
2153        new_selected_range: Option<Range<usize>>,
2154        window: &mut Window,
2155        cx: &mut App,
2156    );
2157
2158    /// 移除文档中的 IME「组合」状态。
2159    /// 对应 [unmarkText()](https://developer.apple.com/documentation/appkit/nstextinputclient/1438239-unmarktext)
2160    fn unmark_text(&mut self, window: &mut Window, cx: &mut App);
2161
2162    /// 获取给定文档范围在屏幕坐标中的边界区域。
2163    /// 对应 [firstRect(forCharacterRange:actualRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438240-firstrect)
2164    ///
2165    /// 用于定位 IME 候选窗口。
2166    fn bounds_for_range(
2167        &mut self,
2168        range_utf16: Range<usize>,
2169        window: &mut Window,
2170        cx: &mut App,
2171    ) -> Option<Bounds<Pixels>>;
2172
2173    /// 获取给定点在 UTF16 字符中的字符偏移量。
2174    ///
2175    /// 对应 [characterIndexForPoint:](https://developer.apple.com/documentation/appkit/nstextinputclient/characterindex(for:))
2176    fn character_index_for_point(
2177        &mut self,
2178        point: Point<Pixels>,
2179        window: &mut Window,
2180        cx: &mut App,
2181    ) -> Option<usize>;
2182
2183    /// 允许输入上下文选择接收原始按键重复,而非将其发送到平台。
2184    /// TODO: 理想情况下应能通过 NSUserDefaults 设置 ApplePressAndHoldEnabled
2185    /// (iTerm 就是这样做的),但目前似乎不生效。
2186    fn apple_press_and_hold_enabled(&mut self) -> bool {
2187        true
2188    }
2189
2190    /// 返回此处理器是否接受要插入的文本输入。
2191    fn accepts_text_input(&mut self, _window: &mut Window, _cx: &mut App) -> bool {
2192        true
2193    }
2194
2195    /// 返回在非 ASCII 输入源(如日语、韩语、中文 IME)激活时,
2196    /// 可打印按键是否应在按键绑定匹配之前先路由到 IME。
2197    /// 这防止了 `jj` 等多击按键绑定拦截 IME 应该组合的按键。
2198    ///
2199    /// 默认为 `false`。编辑器根据是否期望字符输入来覆盖此值
2200    /// (例如 Vim 插入模式返回 `true`,正常模式返回 `false`)。
2201    /// 终端保持默认的 `false`,以便原始按键到达终端进程。
2202    fn prefers_ime_for_printable_keys(&mut self, _window: &mut Window, _cx: &mut App) -> bool {
2203        false
2204    }
2205
2206    /// 设置输入中的选中文本范围。
2207    fn set_selected_text_range(
2208        &mut self,
2209        _range_utf16: Range<usize>,
2210        _window: &mut Window,
2211        _cx: &mut App,
2212    ) {
2213    }
2214
2215    /// 获取元素在屏幕坐标中的边界区域。
2216    fn element_bounds(&mut self, _window: &mut Window, _cx: &mut App) -> Option<Bounds<Pixels>> {
2217        None
2218    }
2219
2220    /// 获取文本的长度(以 UTF-16 字符为单位)。
2221    fn text_length_utf16(&mut self, _window: &mut Window, _cx: &mut App) -> Option<usize> {
2222        None
2223    }
2224}
2225
2226/// 创建窗口时可配置的变量
2227#[derive(Debug)]
2228pub struct WindowOptions {
2229    /// 指定窗口在屏幕坐标中的状态和边界。
2230    /// - `None`:继承边界。
2231    /// - `Some(WindowBounds)`:以对应的状态和恢复尺寸打开窗口。
2232    pub window_bounds: Option<WindowBounds>,
2233
2234    /// 窗口标题栏配置
2235    pub titlebar: Option<TitlebarOptions>,
2236
2237    /// 窗口创建时是否获取焦点
2238    pub focus: bool,
2239
2240    /// 窗口创建时是否显示
2241    pub show: bool,
2242
2243    /// 要创建的窗口类型
2244    pub kind: WindowKind,
2245
2246    /// 窗口是否可被用户拖拽移动。
2247    /// Windows 用窗口样式落地;X11 写入 Motif functions 位(尊重它的 WM 生效);
2248    /// Wayland 没有禁止移动的协议,`false` 仅用于让框架收敛标题栏交互。
2249    pub is_movable: bool,
2250
2251    /// 窗口是否可被用户调整大小。
2252    /// Windows / X11 会真正阻止缩放,Wayland 尽力而为(协议不提供强制禁用)。
2253    pub is_resizable: bool,
2254
2255    /// 窗口是否可被用户最小化。
2256    /// Windows / X11 会真正阻止最小化,Wayland 尽力而为。
2257    /// 三个平台都会让 `window_controls()` 收敛对应按钮,不画出点不动的按钮。
2258    pub is_minimizable: bool,
2259
2260    /// 在哪个显示器上创建窗口,若为 None,
2261    /// 则在主显示器上创建
2262    pub display_id: Option<DisplayId>,
2263
2264    /// 窗口背景外观。
2265    pub window_background: WindowBackgroundAppearance,
2266
2267    /// 窗口的应用标识符,桌面环境可用于将应用分组。
2268    pub app_id: Option<String>,
2269
2270    /// 窗口最小尺寸
2271    pub window_min_size: Option<Size<Pixels>>,
2272
2273    /// 使用客户端还是服务端装饰(Wayland 与 X11)。
2274    ///
2275    /// 这只是**请求**:Wayland 无 xdg-decoration 支持时服务端装饰会回退为客户端
2276    /// 装饰,X11 无合成器时客户端装饰会回退为服务端装饰。回退记 `warn` 日志,
2277    /// 实际生效值用 `Window::window_decorations()` 查询。
2278    ///
2279    /// 保持 `None`(期望系统装饰)的普通顶层窗口在回退为客户端装饰时,框架会
2280    /// 自动补画一个默认标题栏,以避免 Wayland 上「系统不画、应用也不画」的
2281    /// 无标题栏窗口;显式设为 [`WindowDecorations::Client`] 表示应用自行渲染
2282    /// `TitleBar`,框架不会重复补画。
2283    pub window_decorations: Option<WindowDecorations>,
2284
2285    /// 图标图片(仅 X11)
2286    pub icon: Option<Arc<image::RgbaImage>>,
2287
2288    /// 标签页组名称,允许在 macOS 10.12+ 上以原生标签页方式打开窗口。具有相同 tabbing identifier 的窗口将被分组在一起。
2289    pub tabbing_identifier: Option<String>,
2290
2291    /// macOS 专用:应用是否自行处理标题栏拖拽。当使用自定义标题栏时设置为 true,
2292    /// 使 AppKit 不拦截标题栏点击,由应用通过 `Window::start_window_move` 自行处理。
2293    pub app_owns_titlebar_drag: bool,
2294
2295    /// Windows/Linux:是否启用鼠标事件穿透(点击穿透到后面的窗口)。
2296    /// 用于桌面宠物、覆盖层等需要让鼠标点击穿透到下层窗口的场景。
2297    pub mouse_passthrough: bool,
2298
2299    /// 窗口失焦时的最小帧间隔,默认约 30fps(`33_333µs`)。
2300    ///
2301    /// - `None`:失焦时不限帧(动画窗口、需要后台持续刷新的窗口可这么设)。
2302    /// - `Some(Duration::ZERO)`:等价于不限帧。
2303    ///
2304    /// 高速率输入(≥60fps 的鼠标移动等)期间本档自动暂停,避免输入延迟抖动;
2305    /// 强制呈现(如拖动窗口、连续滚动)也不受本档限制。与温控档同时命中时
2306    /// **取较长的那条间隔**。
2307    pub inactive_frame_interval: Option<Duration>,
2308
2309    /// 系统温控进入 `Serious` / `Critical` 时的最小帧间隔,默认约 60fps(`16_667µs`)。
2310    ///
2311    /// `None` 表示温控降频时也不限帧。`Nominal` / `Fair` 不触发本档——
2312    /// `Fair` 只是「减少非必要工作」的提示,不构成限帧依据。
2313    ///
2314    /// 强制呈现同样不受本档限制;与失焦档同时命中时取较长的那条间隔。
2315    pub thermal_frame_interval: Option<Duration>,
2316}
2317
2318/// 创建窗口时的配置参数。
2319#[derive(Debug)]
2320pub struct WindowParams {
2321    /// 窗口初始位置和尺寸。
2322    pub bounds: Bounds<Pixels>,
2323
2324    /// 标题栏配置。
2325    pub titlebar: Option<TitlebarOptions>,
2326
2327    /// 窗口类型(普通窗口、覆盖层等)。
2328    pub kind: WindowKind,
2329
2330    /// 窗口是否可被用户拖拽移动。
2331    pub is_movable: bool,
2332
2333    /// 窗口是否可被用户调整大小。
2334    pub is_resizable: bool,
2335
2336    /// 窗口是否可被用户最小化。
2337    pub is_minimizable: bool,
2338
2339    /// 窗口打开后是否自动获取焦点。
2340    pub focus: bool,
2341
2342    /// 窗口打开后是否立即显示。
2343    pub show: bool,
2344
2345    /// 窗口图标(仅 X11 有效)。
2346    pub icon: Option<Arc<image::RgbaImage>>,
2347
2348    /// 指定显示在哪个显示器上(None 为默认)。
2349    pub display_id: Option<DisplayId>,
2350
2351    /// 应用标识符(主要用于 Wayland)。
2352    pub app_id: Option<String>,
2353
2354    /// 窗口最小尺寸限制。
2355    pub window_min_size: Option<Size<Pixels>>,
2356    /// macOS 标签页分组标识符,相同标识符的窗口可合并为标签页。
2357    #[cfg(target_os = "macos")]
2358    pub tabbing_identifier: Option<String>,
2359
2360    /// macOS only: 应用是否自行处理标题栏拖拽。
2361    /// 当使用自定义标题栏时设置为 true(macOS 专用,其他平台无效果)。
2362    pub app_owns_titlebar_drag: bool,
2363
2364    /// Windows/Linux: 是否启用鼠标事件穿透(点击穿透到后面的窗口)。
2365    /// 覆盖层窗口需要此选项让鼠标事件穿透到底层窗口。
2366    pub mouse_passthrough: bool,
2367
2368    /// 窗口背景外观。X11 需要在创建窗口时据此选择 24 位不透明 visual 还是
2369    /// 32 位 ARGB visual,窗口创建之后无法再更换 visual。
2370    pub window_background: WindowBackgroundAppearance,
2371}
2372
2373/// 表示窗口打开时应处于的状态
2374#[derive(Debug, Copy, Clone, PartialEq)]
2375pub enum WindowBounds {
2376    /// 表示窗口应以窗口化状态打开,使用给定的边界。
2377    Windowed(Bounds<Pixels>),
2378    /// 表示窗口应以最大化状态打开。
2379    /// 此处提供的边界表示窗口的恢复尺寸。
2380    Maximized(Bounds<Pixels>),
2381    /// 表示窗口应以全屏模式打开。
2382    /// 此处提供的边界表示窗口的恢复尺寸。
2383    Fullscreen(Bounds<Pixels>),
2384}
2385
2386impl Default for WindowBounds {
2387    fn default() -> Self {
2388        WindowBounds::Windowed(Bounds::default())
2389    }
2390}
2391
2392impl WindowBounds {
2393    /// 获取内部边界
2394    pub fn get_bounds(&self) -> Bounds<Pixels> {
2395        match self {
2396            WindowBounds::Windowed(bounds) => *bounds,
2397            WindowBounds::Maximized(bounds) => *bounds,
2398            WindowBounds::Fullscreen(bounds) => *bounds,
2399        }
2400    }
2401
2402    /// 创建一个新的窗口边界,使窗口在屏幕上居中。
2403    pub fn centered(size: Size<Pixels>, cx: &App) -> Self {
2404        WindowBounds::Windowed(Bounds::centered(None, size, cx))
2405    }
2406}
2407
2408impl Default for WindowOptions {
2409    fn default() -> Self {
2410        Self {
2411            window_bounds: None,
2412            titlebar: Some(TitlebarOptions {
2413                title: Default::default(),
2414                appears_transparent: Default::default(),
2415                traffic_light_position: Default::default(),
2416            }),
2417            focus: true,
2418            show: true,
2419            kind: WindowKind::Normal,
2420            is_movable: true,
2421            is_resizable: true,
2422            is_minimizable: true,
2423            display_id: None,
2424            window_background: WindowBackgroundAppearance::default(),
2425            icon: None,
2426            app_id: None,
2427            window_min_size: None,
2428            window_decorations: None,
2429            tabbing_identifier: None,
2430            app_owns_titlebar_drag: false,
2431            mouse_passthrough: false,
2432            inactive_frame_interval: Some(crate::frame_throttle::DEFAULT_INACTIVE_FRAME_INTERVAL),
2433            thermal_frame_interval: Some(crate::frame_throttle::DEFAULT_THERMAL_FRAME_INTERVAL),
2434        }
2435    }
2436}
2437
2438/// 窗口标题栏可配置的选项
2439#[derive(Debug, Default)]
2440pub struct TitlebarOptions {
2441    /// 窗口的初始标题
2442    pub title: Option<SharedString>,
2443
2444    /// 是否隐藏默认系统标题栏以使用自定义绘制的标题栏?(仅 macOS 和 Windows)
2445    /// Linux 上请参见 [`WindowOptions::window_decorations`]
2446    pub appears_transparent: bool,
2447
2448    /// macOS 红绿灯按钮的位置
2449    pub traffic_light_position: Option<Point<Pixels>>,
2450}
2451
2452/// 要创建的窗口类型
2453#[derive(Clone, Debug, PartialEq, Eq)]
2454pub enum WindowKind {
2455    /// 普通应用窗口
2456    Normal,
2457
2458    /// 出现在所有其他窗口上方的窗口,通常用于警告或弹出窗口。
2459    /// 应谨慎使用!
2460    PopUp,
2461
2462    /// 父窗口锚定的原生弹出窗口,用于菜单、组合框、上下文菜单和工具提示。
2463    /// 与 [`WindowKind::PopUp`] 不同,它相对于父窗口定位。
2464    ///
2465    /// 弹出窗口的大小来自 [`WindowOptions::window_bounds`],其原点被忽略。
2466    /// 参见 [`popup::PopupOptions`] 了解放置选项。没有原生实现的平台
2467    /// 会以 [`popup::PopupNotSupportedError`] 拒绝。
2468    AnchoredPopup(popup::PopupOptions),
2469
2470    /// 出现在父窗口上方的浮动窗口
2471    Floating,
2472
2473    /// Linux 面板窗口:Wayland 上是 layer-shell 表面,X11 上是 DOCK 窗口 + strut,
2474    /// 用于覆盖层、面板、桌面背景一类不跟普通窗口抢位置的场景。
2475    #[cfg(target_os = "linux")]
2476    LayerShell(layer_shell::LayerShellOptions),
2477
2478    /// 出现在父窗口上方的模态窗口,阻止与父窗口的交互,
2479    /// 直到模态窗口关闭
2480    Dialog,
2481
2482    /// 覆盖层窗口:始终置顶、无边框、支持透明度
2483    Overlay,
2484}
2485
2486/// 窗口的外观,由操作系统定义。
2487///
2488/// 在 macOS 上,这对应于命名的 [`NSAppearance`](https://developer.apple.com/documentation/appkit/nsappearance)
2489/// 值。
2490#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
2491pub enum WindowAppearance {
2492    /// 亮色外观。
2493    ///
2494    /// 在 macOS 上,这对应于 `aqua` 外观。
2495    #[default]
2496    Light,
2497
2498    /// 带有鲜艳颜色的亮色外观。
2499    ///
2500    /// 在 macOS 上,这对应于 `NSAppearanceNameVibrantLight` 外观。
2501    VibrantLight,
2502
2503    /// 暗色外观。
2504    ///
2505    /// 在 macOS 上,这对应于 `darkAqua` 外观。
2506    Dark,
2507
2508    /// 带有鲜艳颜色的暗色外观。
2509    ///
2510    /// 在 macOS 上,这对应于 `NSAppearanceNameVibrantDark` 外观。
2511    VibrantDark,
2512}
2513
2514/// 窗口本身的背景外观,在没有内容或内容透明时显示。
2515#[derive(Copy, Clone, Debug, Default, PartialEq)]
2516pub enum WindowBackgroundAppearance {
2517    /// 不透明。
2518    ///
2519    /// 告诉窗口管理器此窗口背后的内容不需要绘制。
2520    ///
2521    /// 实际颜色取决于系统,主题应定义完全不透明的背景色。
2522    #[default]
2523    Opaque,
2524    /// 纯 Alpha 透明。
2525    Transparent,
2526    /// 透明,但窗口背后的内容会被模糊。
2527    ///
2528    /// 并非总是支持。
2529    Blurred,
2530    /// Mica 背景材质,Windows 11 支持。
2531    MicaBackdrop,
2532    /// Mica Alt 背景材质,Windows 11 支持。
2533    MicaAltBackdrop,
2534}
2535
2536/// 绘制字形时使用的文本渲染模式。
2537#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
2538pub enum TextRenderingMode {
2539    /// 使用平台默认的文本渲染模式。
2540    #[default]
2541    PlatformDefault,
2542    /// 使用亚像素(ClearType 风格)文本渲染。
2543    Subpixel,
2544    /// 使用灰度文本渲染。
2545    Grayscale,
2546}
2547
2548/// 文件对话框提示可配置的选项
2549#[derive(Clone, Debug)]
2550pub struct PathPromptOptions {
2551    /// 提示是否允许选择文件?
2552    pub files: bool,
2553    /// 提示是否允许选择目录?
2554    pub directories: bool,
2555    /// 提示是否允许多选文件?
2556    pub multiple: bool,
2557    /// 选择路径时显示给用户的提示文本
2558    pub prompt: Option<SharedString>,
2559}
2560
2561/// 提示样式类型
2562#[derive(Copy, Clone, Debug, PartialEq)]
2563pub enum PromptLevel {
2564    /// 通知用户的提示
2565    Info,
2566
2567    /// 警告用户潜在问题的提示
2568    Warning,
2569
2570    /// 发生严重问题时的提示
2571    Critical,
2572}
2573
2574/// 提示对话框按钮
2575#[derive(Clone, Debug, PartialEq)]
2576pub enum PromptButton {
2577    /// 确认按钮
2578    Ok(SharedString),
2579    /// 取消按钮
2580    Cancel(SharedString),
2581    /// 其他按钮
2582    Other(SharedString),
2583}
2584
2585impl PromptButton {
2586    /// 创建带标签的按钮
2587    pub fn new(label: impl Into<SharedString>) -> Self {
2588        PromptButton::Other(label.into())
2589    }
2590
2591    /// 创建确认按钮
2592    pub fn ok(label: impl Into<SharedString>) -> Self {
2593        PromptButton::Ok(label.into())
2594    }
2595
2596    /// 创建取消按钮
2597    pub fn cancel(label: impl Into<SharedString>) -> Self {
2598        PromptButton::Cancel(label.into())
2599    }
2600
2601    /// 返回此按钮是否为取消按钮。
2602    pub fn is_cancel(&self) -> bool {
2603        matches!(self, PromptButton::Cancel(_))
2604    }
2605
2606    /// 返回按钮的标签文本
2607    pub fn label(&self) -> &SharedString {
2608        match self {
2609            PromptButton::Ok(label) => label,
2610            PromptButton::Cancel(label) => label,
2611            PromptButton::Other(label) => label,
2612        }
2613    }
2614}
2615
2616impl From<&str> for PromptButton {
2617    fn from(value: &str) -> Self {
2618        match value.to_lowercase().as_str() {
2619            "ok" => PromptButton::Ok("OK".into()),
2620            "cancel" => PromptButton::Cancel("Cancel".into()),
2621            _ => PromptButton::Other(SharedString::from(value.to_owned())),
2622        }
2623    }
2624}
2625
2626/// 光标(指针)样式
2627#[derive(Copy, Clone, Default, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
2628pub enum CursorStyle {
2629    /// 默认光标
2630    #[default]
2631    Arrow,
2632
2633    /// 文本输入光标
2634    /// 对应 CSS cursor 值 `text`
2635    IBeam,
2636
2637    /// 十字光标
2638    /// 对应 CSS cursor 值 `crosshair`
2639    Crosshair,
2640
2641    /// 闭合手型光标
2642    /// 对应 CSS cursor 值 `grabbing`
2643    ClosedHand,
2644
2645    /// 张开手型光标
2646    /// 对应 CSS cursor 值 `grab`
2647    OpenHand,
2648
2649    /// 指向手型光标
2650    /// 对应 CSS cursor 值 `pointer`
2651    PointingHand,
2652
2653    /// 向左调整大小光标
2654    /// 对应 CSS cursor 值 `w-resize`
2655    ResizeLeft,
2656
2657    /// 向右调整大小光标
2658    /// 对应 CSS cursor 值 `e-resize`
2659    ResizeRight,
2660
2661    /// 左右调整大小光标
2662    /// 对应 CSS cursor 值 `ew-resize`
2663    ResizeLeftRight,
2664
2665    /// 向上调整大小光标
2666    /// 对应 CSS cursor 值 `n-resize`
2667    ResizeUp,
2668
2669    /// 向下调整大小光标
2670    /// 对应 CSS cursor 值 `s-resize`
2671    ResizeDown,
2672
2673    /// 上下调整大小光标
2674    /// 对应 CSS cursor 值 `ns-resize`
2675    ResizeUpDown,
2676
2677    /// 向左上和右下调整大小光标
2678    /// 对应 CSS cursor 值 `nesw-resize`
2679    ResizeUpLeftDownRight,
2680
2681    /// 向右上和左下调整大小光标
2682    /// 对应 CSS cursor 值 `nwse-resize`
2683    ResizeUpRightDownLeft,
2684
2685    /// 表示可以水平调整大小的光标
2686    /// 对应 CSS cursor 值 `col-resize`
2687    ResizeColumn,
2688
2689    /// 表示可以垂直调整大小的光标
2690    /// 对应 CSS cursor 值 `row-resize`
2691    ResizeRow,
2692
2693    /// 垂直布局的文本输入光标
2694    /// 对应 CSS cursor 值 `vertical-text`
2695    IBeamCursorForVerticalLayout,
2696
2697    /// 表示操作不允许的光标
2698    /// 对应 CSS cursor 值 `not-allowed`
2699    OperationNotAllowed,
2700
2701    /// 表示操作将产生链接的光标
2702    /// 对应 CSS cursor 值 `alias`
2703    DragLink,
2704
2705    /// 表示操作将产生副本的光标
2706    /// 对应 CSS cursor 值 `copy`
2707    DragCopy,
2708
2709    /// 表示操作将产生上下文菜单的光标
2710    /// 对应 CSS cursor 值 `context-menu`
2711    ContextualMenu,
2712}
2713
2714/// 一份带 MIME 类型的剪贴板原始负载。
2715///
2716/// 用于 HTML / RTF / CSV / 应用自定义格式等 [`ClipboardEntry::String`] 无法表达的富负载。
2717/// 平台层负责把它映射到原生剪贴板格式(Windows 注册格式、macOS UTType、Linux MIME atom)。
2718/// 一份 [`ClipboardItem`] 通常同时携带纯文本条目与富负载条目,供不同目标程序择一取用。
2719#[derive(Clone, Debug, Eq, PartialEq)]
2720pub struct ClipboardFormat {
2721    /// 负载的 MIME 类型(参见同名常量,如 [`ClipboardFormat::HTML`])。
2722    pub mime_type: String,
2723    /// 与 MIME 类型对应的原始字节。
2724    pub bytes: Vec<u8>,
2725}
2726
2727impl ClipboardFormat {
2728    /// 纯文本(UTF-8)。
2729    pub const PLAIN_TEXT: &'static str = "text/plain";
2730    /// HTML 片段。平台层写盘时按需补全 `CF_HTML` / 完整文档外壳。
2731    pub const HTML: &'static str = "text/html";
2732    /// RTF 富文本。
2733    pub const RTF: &'static str = "text/rtf";
2734    /// Markdown。
2735    pub const MARKDOWN: &'static str = "text/markdown";
2736    /// 逗号分隔值。
2737    pub const CSV: &'static str = "text/csv";
2738    /// 制表符分隔值。
2739    pub const TSV: &'static str = "text/tab-separated-values";
2740    /// URI 列表(每行一个)。
2741    pub const URI_LIST: &'static str = "text/uri-list";
2742
2743    /// 以 MIME 类型与原始字节创建。
2744    pub fn new(mime_type: impl Into<String>, bytes: Vec<u8>) -> Self {
2745        Self {
2746            mime_type: mime_type.into(),
2747            bytes,
2748        }
2749    }
2750
2751    /// 以 MIME 类型与 UTF-8 文本创建。
2752    pub fn new_text(mime_type: impl Into<String>, text: impl Into<String>) -> Self {
2753        Self::new(mime_type, text.into().into_bytes())
2754    }
2755
2756    /// 负载是否为合法 UTF-8;是则返回其文本。
2757    pub fn text(&self) -> Option<&str> {
2758        std::str::from_utf8(&self.bytes).ok()
2759    }
2760}
2761
2762/// 应复制到剪贴板的剪贴板项目
2763#[derive(Clone, Debug, Eq, PartialEq)]
2764pub struct ClipboardItem {
2765    /// 此剪贴板项目的条目。
2766    pub entries: Vec<ClipboardEntry>,
2767}
2768
2769/// 剪贴板字符串或剪贴板图像
2770#[derive(Clone, Debug, Eq, PartialEq)]
2771pub enum ClipboardEntry {
2772    /// 字符串条目
2773    String(ClipboardString),
2774    /// 图像条目
2775    Image(Image),
2776    /// 文件条目
2777    ExternalPaths(crate::ExternalPaths),
2778    /// 带 MIME 类型的富负载条目(HTML / RTF / CSV / 自定义格式)。
2779    Format(ClipboardFormat),
2780}
2781
2782impl ClipboardItem {
2783    /// 创建一个不带关联元数据的新 ClipboardItem::String
2784    pub fn new_string(text: String) -> Self {
2785        Self {
2786            entries: vec![ClipboardEntry::String(ClipboardString::new(text))],
2787        }
2788    }
2789
2790    /// 创建一个带有关联元数据的新 ClipboardItem::String
2791    pub fn new_string_with_metadata(text: String, metadata: String) -> Self {
2792        Self {
2793            entries: vec![ClipboardEntry::String(ClipboardString {
2794                text,
2795                metadata: Some(metadata),
2796            })],
2797        }
2798    }
2799
2800    /// 创建一个带有关联元数据(JSON 序列化)的新 ClipboardItem::String
2801    pub fn new_string_with_json_metadata<T: Serialize>(text: String, metadata: T) -> Self {
2802        Self {
2803            entries: vec![ClipboardEntry::String(
2804                ClipboardString::new(text).with_json_metadata(metadata),
2805            )],
2806        }
2807    }
2808
2809    /// 创建一个不带关联元数据的新 ClipboardItem::Image
2810    pub fn new_image(image: &Image) -> Self {
2811        Self {
2812            entries: vec![ClipboardEntry::Image(image.clone())],
2813        }
2814    }
2815
2816    /// 创建一个「纯文本 + HTML」项目。
2817    ///
2818    /// `plain_text` 为 `Some` 时作为降级表示排在前面,不支持 HTML 的目标程序取到纯文本;
2819    /// HTML 片段本身不含 `CF_HTML` 头,由平台层在写入时补全。
2820    pub fn new_html(html: impl Into<String>, plain_text: Option<String>) -> Self {
2821        let mut entries = Vec::with_capacity(2);
2822        if let Some(text) = plain_text {
2823            entries.push(ClipboardEntry::String(ClipboardString::new(text)));
2824        }
2825        entries.push(ClipboardEntry::Format(ClipboardFormat::new_text(
2826            ClipboardFormat::HTML,
2827            html,
2828        )));
2829        Self { entries }
2830    }
2831
2832    /// 创建一个「纯文本 + RTF」项目。语义同 [`ClipboardItem::new_html`]。
2833    pub fn new_rtf(rtf: impl Into<String>, plain_text: Option<String>) -> Self {
2834        let mut entries = Vec::with_capacity(2);
2835        if let Some(text) = plain_text {
2836            entries.push(ClipboardEntry::String(ClipboardString::new(text)));
2837        }
2838        entries.push(ClipboardEntry::Format(ClipboardFormat::new_text(
2839            ClipboardFormat::RTF,
2840            rtf,
2841        )));
2842        Self { entries }
2843    }
2844
2845    /// 创建一个仅含单个富负载的项目。
2846    pub fn new_with_format(format: ClipboardFormat) -> Self {
2847        Self {
2848            entries: vec![ClipboardEntry::Format(format)],
2849        }
2850    }
2851
2852    /// 追加一段纯文本条目并返回自身。
2853    pub fn with_string(mut self, text: impl Into<String>) -> Self {
2854        self.entries
2855            .push(ClipboardEntry::String(ClipboardString::new(text.into())));
2856        self
2857    }
2858
2859    /// 追加一个富负载条目并返回自身。
2860    pub fn with_format(mut self, format: ClipboardFormat) -> Self {
2861        self.entries.push(ClipboardEntry::Format(format));
2862        self
2863    }
2864
2865    /// 连接项目中所有 ClipboardString 条目的文本。
2866    /// 如果没有 ClipboardString 条目则返回 None。
2867    pub fn text(&self) -> Option<String> {
2868        let mut answer = String::new();
2869
2870        for entry in self.entries.iter() {
2871            if let ClipboardEntry::String(ClipboardString { text, metadata: _ }) = entry {
2872                answer.push_str(text);
2873            }
2874        }
2875
2876        if answer.is_empty() {
2877            for entry in self.entries.iter() {
2878                if let ClipboardEntry::ExternalPaths(paths) = entry {
2879                    for path in &paths.0 {
2880                        use std::fmt::Write as _;
2881                        _ = write!(answer, "{}", path.display());
2882                    }
2883                }
2884            }
2885        }
2886
2887        if !answer.is_empty() {
2888            Some(answer)
2889        } else {
2890            None
2891        }
2892    }
2893
2894    /// 如果此项目是单个 ClipboardEntry::String,返回其元数据。
2895    pub fn metadata(&self) -> Option<&String> {
2896        match self.entries().first() {
2897            Some(ClipboardEntry::String(clipboard_string)) if self.entries.len() == 1 => {
2898                clipboard_string.metadata.as_ref()
2899            }
2900            _ => None,
2901        }
2902    }
2903
2904    /// 获取项目的条目
2905    pub fn entries(&self) -> &[ClipboardEntry] {
2906        &self.entries
2907    }
2908
2909    /// 获取项目条目的所有权版本
2910    pub fn into_entries(self) -> impl Iterator<Item = ClipboardEntry> {
2911        self.entries.into_iter()
2912    }
2913
2914    /// 查找指定 MIME 类型的富负载。
2915    pub fn format(&self, mime_type: &str) -> Option<&ClipboardFormat> {
2916        self.entries.iter().find_map(|entry| match entry {
2917            ClipboardEntry::Format(format) if format.mime_type == mime_type => Some(format),
2918            _ => None,
2919        })
2920    }
2921
2922    /// 遍历项目中的所有富负载条目。
2923    pub fn formats(&self) -> impl Iterator<Item = &ClipboardFormat> {
2924        self.entries.iter().filter_map(|entry| match entry {
2925            ClipboardEntry::Format(format) => Some(format),
2926            _ => None,
2927        })
2928    }
2929
2930    /// HTML 富负载([`ClipboardFormat::HTML`])的文本。
2931    pub fn html(&self) -> Option<&str> {
2932        self.format(ClipboardFormat::HTML)?.text()
2933    }
2934
2935    /// RTF 富负载([`ClipboardFormat::RTF`])的文本。
2936    pub fn rtf(&self) -> Option<&str> {
2937        self.format(ClipboardFormat::RTF)?.text()
2938    }
2939}
2940
2941impl From<ClipboardString> for ClipboardEntry {
2942    fn from(value: ClipboardString) -> Self {
2943        Self::String(value)
2944    }
2945}
2946
2947impl From<String> for ClipboardEntry {
2948    fn from(value: String) -> Self {
2949        Self::from(ClipboardString::from(value))
2950    }
2951}
2952
2953impl From<Image> for ClipboardEntry {
2954    fn from(value: Image) -> Self {
2955        Self::Image(value)
2956    }
2957}
2958
2959impl From<ClipboardFormat> for ClipboardEntry {
2960    fn from(value: ClipboardFormat) -> Self {
2961        Self::Format(value)
2962    }
2963}
2964
2965impl From<ClipboardEntry> for ClipboardItem {
2966    fn from(value: ClipboardEntry) -> Self {
2967        Self {
2968            entries: vec![value],
2969        }
2970    }
2971}
2972
2973impl From<String> for ClipboardItem {
2974    fn from(value: String) -> Self {
2975        Self::from(ClipboardEntry::from(value))
2976    }
2977}
2978
2979impl From<Image> for ClipboardItem {
2980    fn from(value: Image) -> Self {
2981        Self::from(ClipboardEntry::from(value))
2982    }
2983}
2984
2985impl From<ClipboardFormat> for ClipboardItem {
2986    fn from(value: ClipboardFormat) -> Self {
2987        Self::from(ClipboardEntry::from(value))
2988    }
2989}
2990
2991#[cfg(test)]
2992mod clipboard_tests {
2993    use super::*;
2994
2995    /// 纯文本 + HTML 项目同时暴露两种表示。
2996    #[test]
2997    fn html_item_exposes_text_and_html() {
2998        let item = ClipboardItem::new_html("<b>Hi</b>", Some("Hi".to_string()));
2999        assert_eq!(item.text().as_deref(), Some("Hi"));
3000        assert_eq!(item.html(), Some("<b>Hi</b>"));
3001        assert_eq!(item.rtf(), None);
3002        assert_eq!(item.formats().count(), 1);
3003    }
3004
3005    /// 纯文本 + RTF 项目。
3006    #[test]
3007    fn rtf_item_exposes_rtf() {
3008        let item = ClipboardItem::new_rtf(r"{\rtf1 hi}", Some("hi".to_string()));
3009        assert_eq!(item.text().as_deref(), Some("hi"));
3010        assert_eq!(item.rtf(), Some(r"{\rtf1 hi}"));
3011    }
3012
3013    /// 无纯文本时只保留富负载,`text()` 返回 None。
3014    #[test]
3015    fn format_only_item_has_no_plain_text() {
3016        let item = ClipboardItem::new_with_format(ClipboardFormat::new_text(
3017            ClipboardFormat::CSV,
3018            "a,b\n1,2",
3019        ));
3020        assert_eq!(item.text(), None);
3021        assert_eq!(
3022            item.format(ClipboardFormat::CSV)
3023                .and_then(ClipboardFormat::text),
3024            Some("a,b\n1,2")
3025        );
3026    }
3027
3028    /// 二进制负载不是合法 UTF-8 时 `text()` 返回 None。
3029    #[test]
3030    fn non_utf8_format_has_no_text() {
3031        let format = ClipboardFormat::new("application/octet-stream", vec![0xff, 0xfe]);
3032        assert_eq!(format.text(), None);
3033        assert_eq!(format.mime_type, "application/octet-stream");
3034    }
3035
3036    /// 构建器按序追加条目。
3037    #[test]
3038    fn builder_appends_entries_in_order() {
3039        let item = ClipboardItem::new_string("plain".to_string()).with_format(
3040            ClipboardFormat::new_text(ClipboardFormat::HTML, "<i>plain</i>"),
3041        );
3042        assert_eq!(item.entries.len(), 2);
3043        assert!(matches!(item.entries[0], ClipboardEntry::String(_)));
3044        assert!(matches!(item.entries[1], ClipboardEntry::Format(_)));
3045    }
3046}
3047
3048/// 编辑器支持的图像格式之一(如 PNG、JPEG)- 用于处理剪贴板中的图像
3049#[derive(Clone, Copy, Debug, Eq, PartialEq, EnumIter, Hash)]
3050pub enum ImageFormat {
3051    // 按粘贴到编辑器的可能性从高到低排序,
3052    // 在遍历检查剪贴板内容是否匹配时这很重要。
3053    /// .png
3054    Png,
3055    /// .jpeg 或 .jpg
3056    Jpeg,
3057    /// .webp
3058    Webp,
3059    /// .gif
3060    Gif,
3061    /// .svg
3062    Svg,
3063    /// .bmp
3064    Bmp,
3065    /// .tif 或 .tiff
3066    Tiff,
3067    /// .ico
3068    Ico,
3069    /// Netpbm 图像格式(.pbm、.ppm、.pgm)。
3070    Pnm,
3071}
3072
3073impl ImageFormat {
3074    /// 返回 ImageFormat 的 MIME 类型
3075    pub const fn mime_type(self) -> &'static str {
3076        match self {
3077            ImageFormat::Png => "image/png",
3078            ImageFormat::Jpeg => "image/jpeg",
3079            ImageFormat::Webp => "image/webp",
3080            ImageFormat::Gif => "image/gif",
3081            ImageFormat::Svg => "image/svg+xml",
3082            ImageFormat::Bmp => "image/bmp",
3083            ImageFormat::Tiff => "image/tiff",
3084            ImageFormat::Ico => "image/ico",
3085            ImageFormat::Pnm => "image/x-portable-anymap",
3086        }
3087    }
3088
3089    /// 根据 MIME 类型返回对应的 ImageFormat,包括已知别名。
3090    pub fn from_mime_type(mime_type: &str) -> Option<Self> {
3091        use strum::IntoEnumIterator;
3092        Self::iter()
3093            .find(|format| format.mime_type() == mime_type)
3094            .or_else(|| Self::from_mime_type_alias(mime_type))
3095    }
3096
3097    /// 非规范的 MIME 类型,一些生产者在实际使用中使用。
3098    /// 不同于返回单一规范形式的 `mime_type()`,
3099    /// 这些是我们仍需识别的遗留或缩写变体。
3100    fn from_mime_type_alias(mime_type: &str) -> Option<Self> {
3101        match mime_type {
3102            "image/jpg" => Some(Self::Jpeg),
3103            "image/tif" => Some(Self::Tiff),
3104            _ => None,
3105        }
3106    }
3107}
3108
3109/// 图像,包含格式和字节数据
3110#[derive(Clone, Debug, PartialEq, Eq)]
3111pub struct Image {
3112    /// 字节数据表示的图像格式(如 PNG)
3113    pub format: ImageFormat,
3114    /// 原始图像字节
3115    pub bytes: Vec<u8>,
3116    /// 图像的唯一 ID
3117    pub id: u64,
3118}
3119
3120impl Hash for Image {
3121    fn hash<H: Hasher>(&self, state: &mut H) {
3122        state.write_u64(self.id);
3123    }
3124}
3125
3126impl Image {
3127    /// 一个不包含数据的空图像
3128    pub fn empty() -> Self {
3129        Self::from_bytes(ImageFormat::Png, Vec::new())
3130    }
3131
3132    /// 从格式和字节数据创建图像
3133    pub fn from_bytes(format: ImageFormat, bytes: Vec<u8>) -> Self {
3134        Self {
3135            id: hash(&bytes),
3136            format,
3137            bytes,
3138        }
3139    }
3140
3141    /// 获取图像的 ID
3142    pub fn id(&self) -> u64 {
3143        self.id
3144    }
3145
3146    /// 使用 RGPUI `use_asset` API 使此图像可渲染
3147    pub fn use_render_image(
3148        self: Arc<Self>,
3149        window: &mut Window,
3150        cx: &mut App,
3151    ) -> Option<Arc<RenderImage>> {
3152        ImageSource::Image(self)
3153            .use_data(None, window, cx)
3154            .and_then(|result| result.ok())
3155    }
3156
3157    /// 使用 RGPUI `get_asset` API 使此图像可渲染
3158    pub fn get_render_image(
3159        self: Arc<Self>,
3160        window: &mut Window,
3161        cx: &mut App,
3162    ) -> Option<Arc<RenderImage>> {
3163        ImageSource::Image(self)
3164            .get_data(None, window, cx)
3165            .and_then(|result| result.ok())
3166    }
3167
3168    /// 使用 RGPUI `remove_asset` API 移除此图像(如果可能)。
3169    pub fn remove_asset(self: Arc<Self>, cx: &mut App) {
3170        ImageSource::Image(self).remove_asset(cx);
3171    }
3172
3173    /// 将剪贴板图像转换为 `ImageData` 对象。
3174    pub fn to_image_data(&self, svg_renderer: SvgRenderer) -> Result<Arc<RenderImage>> {
3175        fn frames_for_image(
3176            bytes: &[u8],
3177            format: image::ImageFormat,
3178        ) -> Result<SmallVec<[Frame; 1]>> {
3179            let mut data = image::load_from_memory_with_format(bytes, format)?.into_rgba8();
3180
3181            // Convert from RGBA to BGRA.
3182            for pixel in data.chunks_exact_mut(4) {
3183                pixel.swap(0, 2);
3184            }
3185
3186            Ok(SmallVec::from_elem(Frame::new(data), 1))
3187        }
3188
3189        let frames = match self.format {
3190            ImageFormat::Gif => {
3191                let decoder = GifDecoder::new(Cursor::new(&self.bytes))?;
3192                let mut frames = SmallVec::new();
3193
3194                for frame in decoder.into_frames() {
3195                    match frame {
3196                        Ok(mut frame) => {
3197                            // Convert from RGBA to BGRA.
3198                            for pixel in frame.buffer_mut().chunks_exact_mut(4) {
3199                                pixel.swap(0, 2);
3200                            }
3201                            frames.push(frame);
3202                        }
3203                        Err(err) => {
3204                            log::debug!("Skipping GIF frame due to decode error: {err}");
3205                        }
3206                    }
3207                }
3208
3209                if frames.is_empty() {
3210                    anyhow::bail!("GIF could not be decoded: all frames failed");
3211                }
3212
3213                frames
3214            }
3215            ImageFormat::Png => frames_for_image(&self.bytes, image::ImageFormat::Png)?,
3216            ImageFormat::Jpeg => frames_for_image(&self.bytes, image::ImageFormat::Jpeg)?,
3217            ImageFormat::Webp => frames_for_image(&self.bytes, image::ImageFormat::WebP)?,
3218            ImageFormat::Bmp => frames_for_image(&self.bytes, image::ImageFormat::Bmp)?,
3219            ImageFormat::Tiff => {
3220                #[cfg(feature = "image-tiff")]
3221                {
3222                    frames_for_image(&self.bytes, image::ImageFormat::Tiff)?
3223                }
3224                #[cfg(not(feature = "image-tiff"))]
3225                {
3226                    anyhow::bail!("TIFF format not enabled, enable `image-tiff` feature")
3227                }
3228            }
3229            ImageFormat::Ico => frames_for_image(&self.bytes, image::ImageFormat::Ico)?,
3230            ImageFormat::Svg => {
3231                return svg_renderer
3232                    .render_single_frame(&self.bytes, 1.0)
3233                    .map_err(Into::into);
3234            }
3235            ImageFormat::Pnm => frames_for_image(&self.bytes, image::ImageFormat::Pnm)?,
3236        };
3237
3238        Ok(Arc::new(RenderImage::new(frames)))
3239    }
3240
3241    /// 获取剪贴板图像的格式
3242    pub fn format(&self) -> ImageFormat {
3243        self.format
3244    }
3245
3246    /// 获取剪贴板图像的原始字节
3247    pub fn bytes(&self) -> &[u8] {
3248        self.bytes.as_slice()
3249    }
3250}
3251
3252/// 应复制到剪贴板的剪贴板字符串项目
3253#[derive(Clone, Debug, Eq, PartialEq)]
3254pub struct ClipboardString {
3255    /// 文本内容。
3256    pub text: String,
3257    /// 关联的可选元数据。
3258    pub metadata: Option<String>,
3259}
3260
3261impl ClipboardString {
3262    /// 创建一个新的剪贴板字符串
3263    pub fn new(text: String) -> Self {
3264        Self {
3265            text,
3266            metadata: None,
3267        }
3268    }
3269
3270    /// 返回一个新的剪贴板项目,其元数据通过 JSON 序列化后替换为给定值。
3271    ///
3272    /// 序列化失败(自定义 `Serialize` 实现报错、非字符串键等)时保留原元数据并记警告,
3273    /// 剪贴板文本本身不受影响。
3274    pub fn with_json_metadata<T: Serialize>(mut self, metadata: T) -> Self {
3275        match serde_json::to_string(&metadata) {
3276            Ok(json) => self.metadata = Some(json),
3277            Err(err) => log::warn!("[rgpui::platform] 剪贴板元数据 JSON 序列化失败,已忽略:{err}"),
3278        }
3279        self
3280    }
3281
3282    /// 获取剪贴板字符串的文本
3283    pub fn text(&self) -> &String {
3284        &self.text
3285    }
3286
3287    /// 获取剪贴板字符串的所有权文本
3288    pub fn into_text(self) -> String {
3289        self.text
3290    }
3291
3292    /// 获取剪贴板字符串的元数据(JSON 格式)
3293    pub fn metadata_json<T>(&self) -> Option<T>
3294    where
3295        T: for<'a> Deserialize<'a>,
3296    {
3297        self.metadata
3298            .as_ref()
3299            .and_then(|m| serde_json::from_str(m).ok())
3300    }
3301
3302    /// 计算给定文本的哈希值,用于剪贴板变化检测。
3303    pub fn text_hash(text: &str) -> u64 {
3304        let mut hasher = SeaHasher::new();
3305        text.hash(&mut hasher);
3306        hasher.finish()
3307    }
3308}
3309
3310impl From<String> for ClipboardString {
3311    fn from(value: String) -> Self {
3312        Self {
3313            text: value,
3314            metadata: None,
3315        }
3316    }
3317}
3318
3319#[cfg(test)]
3320mod image_tests {
3321    use super::*;
3322    use std::sync::Arc;
3323
3324    #[test]
3325    fn test_svg_image_to_image_data_converts_to_bgra() {
3326        let image = Image::from_bytes(
3327            ImageFormat::Svg,
3328            br##"<svg xmlns="http://www.w3.org/2000/svg" width="1" height="1">
3329<rect width="1" height="1" fill="#38BDF8"/>
3330</svg>"##
3331                .to_vec(),
3332        );
3333
3334        let render_image = image.to_image_data(SvgRenderer::new(Arc::new(()))).unwrap();
3335        let bytes = render_image.as_bytes(0).unwrap();
3336
3337        for pixel in bytes.chunks_exact(4) {
3338            assert_eq!(pixel, &[0xF8, 0xBD, 0x38, 0xFF]);
3339        }
3340    }
3341}
3342
3343#[cfg(all(test, any(target_os = "linux", target_os = "freebsd")))]
3344mod tests {
3345    use super::*;
3346    use rgpui::collections::HashSet;
3347
3348    #[test]
3349    fn test_window_button_layout_parse_standard() {
3350        let layout = WindowButtonLayout::parse("close,minimize:maximize").unwrap();
3351        assert_eq!(
3352            layout.left,
3353            [
3354                Some(WindowButton::Close),
3355                Some(WindowButton::Minimize),
3356                None
3357            ]
3358        );
3359        assert_eq!(layout.right, [Some(WindowButton::Maximize), None, None]);
3360    }
3361
3362    #[test]
3363    fn test_window_button_layout_parse_right_only() {
3364        let layout = WindowButtonLayout::parse("minimize,maximize,close").unwrap();
3365        assert_eq!(layout.left, [None, None, None]);
3366        assert_eq!(
3367            layout.right,
3368            [
3369                Some(WindowButton::Minimize),
3370                Some(WindowButton::Maximize),
3371                Some(WindowButton::Close)
3372            ]
3373        );
3374    }
3375
3376    #[test]
3377    fn test_window_button_layout_parse_left_only() {
3378        let layout = WindowButtonLayout::parse("close,minimize,maximize:").unwrap();
3379        assert_eq!(
3380            layout.left,
3381            [
3382                Some(WindowButton::Close),
3383                Some(WindowButton::Minimize),
3384                Some(WindowButton::Maximize)
3385            ]
3386        );
3387        assert_eq!(layout.right, [None, None, None]);
3388    }
3389
3390    #[test]
3391    fn test_window_button_layout_parse_with_whitespace() {
3392        let layout = WindowButtonLayout::parse(" close , minimize : maximize ").unwrap();
3393        assert_eq!(
3394            layout.left,
3395            [
3396                Some(WindowButton::Close),
3397                Some(WindowButton::Minimize),
3398                None
3399            ]
3400        );
3401        assert_eq!(layout.right, [Some(WindowButton::Maximize), None, None]);
3402    }
3403
3404    #[test]
3405    fn test_window_button_layout_parse_empty() {
3406        let layout = WindowButtonLayout::parse("").unwrap();
3407        assert_eq!(layout.left, [None, None, None]);
3408        assert_eq!(layout.right, [None, None, None]);
3409    }
3410
3411    #[test]
3412    fn test_window_button_layout_parse_intentionally_empty() {
3413        let layout = WindowButtonLayout::parse(":").unwrap();
3414        assert_eq!(layout.left, [None, None, None]);
3415        assert_eq!(layout.right, [None, None, None]);
3416    }
3417
3418    #[test]
3419    fn test_window_button_layout_parse_invalid_buttons() {
3420        let layout = WindowButtonLayout::parse("close,invalid,minimize:maximize,foo").unwrap();
3421        assert_eq!(
3422            layout.left,
3423            [
3424                Some(WindowButton::Close),
3425                Some(WindowButton::Minimize),
3426                None
3427            ]
3428        );
3429        assert_eq!(layout.right, [Some(WindowButton::Maximize), None, None]);
3430    }
3431
3432    #[test]
3433    fn test_window_button_layout_parse_deduplicates_same_side_buttons() {
3434        let layout = WindowButtonLayout::parse("close,close,minimize").unwrap();
3435        assert_eq!(
3436            layout.right,
3437            [
3438                Some(WindowButton::Close),
3439                Some(WindowButton::Minimize),
3440                None
3441            ]
3442        );
3443        assert_eq!(layout.format(), ":close,minimize");
3444    }
3445
3446    #[test]
3447    fn test_window_button_layout_parse_deduplicates_buttons_across_sides() {
3448        let layout = WindowButtonLayout::parse("close:maximize,close,minimize").unwrap();
3449        assert_eq!(layout.left, [Some(WindowButton::Close), None, None]);
3450        assert_eq!(
3451            layout.right,
3452            [
3453                Some(WindowButton::Maximize),
3454                Some(WindowButton::Minimize),
3455                None
3456            ]
3457        );
3458
3459        let button_ids: Vec<_> = layout
3460            .left
3461            .iter()
3462            .chain(layout.right.iter())
3463            .flatten()
3464            .map(WindowButton::id)
3465            .collect();
3466        let unique_button_ids = button_ids.iter().copied().collect::<HashSet<_>>();
3467        assert_eq!(unique_button_ids.len(), button_ids.len());
3468        assert_eq!(layout.format(), "close:maximize,minimize");
3469    }
3470
3471    #[test]
3472    fn test_window_button_layout_parse_gnome_style() {
3473        let layout = WindowButtonLayout::parse("close").unwrap();
3474        assert_eq!(layout.left, [None, None, None]);
3475        assert_eq!(layout.right, [Some(WindowButton::Close), None, None]);
3476    }
3477
3478    #[test]
3479    fn test_window_button_layout_parse_elementary_style() {
3480        let layout = WindowButtonLayout::parse("close:maximize").unwrap();
3481        assert_eq!(layout.left, [Some(WindowButton::Close), None, None]);
3482        assert_eq!(layout.right, [Some(WindowButton::Maximize), None, None]);
3483    }
3484
3485    #[test]
3486    fn test_window_button_layout_round_trip() {
3487        let cases = [
3488            "close:minimize,maximize",
3489            "minimize,maximize,close:",
3490            ":close",
3491            "close:",
3492            "close:maximize",
3493            ":",
3494        ];
3495
3496        for case in cases {
3497            let layout = WindowButtonLayout::parse(case).unwrap();
3498            assert_eq!(layout.format(), case, "Round-trip failed for: {}", case);
3499        }
3500    }
3501
3502    #[test]
3503    fn test_window_button_layout_linux_default() {
3504        let layout = WindowButtonLayout::linux_default();
3505        assert_eq!(layout.left, [None, None, None]);
3506        assert_eq!(
3507            layout.right,
3508            [
3509                Some(WindowButton::Minimize),
3510                Some(WindowButton::Maximize),
3511                Some(WindowButton::Close)
3512            ]
3513        );
3514
3515        let round_tripped = WindowButtonLayout::parse(&layout.format()).unwrap();
3516        assert_eq!(round_tripped, layout);
3517    }
3518
3519    #[test]
3520    fn test_window_button_layout_parse_all_invalid() {
3521        assert!(WindowButtonLayout::parse("asdfghjkl").is_err());
3522    }
3523}