Skip to main content

velox_engine/
app.rs

1//! 极简桌面应用启动层 `velox_engine::app`(参照 `gpui-kit` 启动范式)。
2//!
3//! 让桌面端启动代码精简到极致(仅需数行):
4//! ```no_run
5//! use velox_engine::prelude::*;
6//!
7//! struct HelloWorld;
8//! impl View for HelloWorld {
9//!     fn render<'a>(&mut self, cx: &'a mut Scope<Self>) -> Element<'a> {
10//!         div().size_full().items_center().justify_center().child(cx, text("Hello, World!")).into_element(cx)
11//!     }
12//! }
13//!
14//! fn main() {
15//!     velox_engine::app::application().run(|cx| {
16//!         velox_engine::app::init(cx);
17//!         velox_engine::app::open_window(
18//!             WindowOptions::new("Hello Velox").size(480, 320),
19//!             cx,
20//!             |cx| cx.new(|_| HelloWorld),
21//!         )
22//!         .expect("Failed to open window");
23//!     });
24//! }
25//! ```
26
27use core::fmt;
28use std::string::String;
29use std::sync::Arc;
30
31use crate::async_rt::{NativeStdScheduler, SchedulerBackend, Task};
32use crate::element::View;
33use crate::engine::VeloxEngine;
34use crate::i18n::{DynamicCatalog, Locale, StaticCatalog};
35use crate::platform::winit::WinitPlatform;
36use crate::platform::{DesktopRenderBackend, Platform};
37use crate::pod::{CoreTheme, Handle};
38
39/// 窗口打开与初始化过程中的错误类型。
40#[derive(Clone, PartialEq, Eq, Debug)]
41pub enum AppError {
42    /// 单窗口桌面运行器中重复打开主窗口。
43    WindowAlreadyOpen,
44}
45
46impl fmt::Display for AppError {
47    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
48        match self {
49            Self::WindowAlreadyOpen => {
50                write!(f, "primary window has already been opened in this AppContext")
51            }
52        }
53    }
54}
55
56impl std::error::Error for AppError {}
57
58/// 桌面窗口创建配置项(参照 `gpui-kit` `WindowOptions`)。
59#[derive(Clone, Debug)]
60pub struct WindowOptions {
61    /// 窗口标题。
62    pub title: String,
63    /// 初始逻辑宽度(像素,默认 `960`)。
64    pub width: i16,
65    /// 初始逻辑高度(像素,默认 `640`)。
66    pub height: i16,
67    /// 可选窗口级主题覆盖(未指定时继承 [`Application`] 全局主题,默认暗色)。
68    pub theme: Option<CoreTheme>,
69    /// 可选窗口级语言区域覆盖(未指定时继承 [`Application`] 全局语言)。
70    pub locale: Option<Locale>,
71    /// 可选固定 HiDPI 缩放倍率(`None` 时自动跟随操作系统缩放)。
72    pub dpi_scale: Option<usize>,
73    /// 桌面渲染后端(默认 [`DesktopRenderBackend::default_desktop`])。
74    pub backend: Option<DesktopRenderBackend>,
75    /// 可选默认滚轮回退目标列表 ID。
76    pub scroll_list_id: Option<u32>,
77}
78
79impl Default for WindowOptions {
80    fn default() -> Self {
81        Self {
82            title: String::from("Velox Application"),
83            width: 960,
84            height: 640,
85            theme: None,
86            locale: None,
87            dpi_scale: None,
88            backend: None,
89            scroll_list_id: None,
90        }
91    }
92}
93
94impl WindowOptions {
95    /// 使用指定窗口标题创建默认尺寸(`960x640`)的窗口配置。
96    pub fn new(title: impl Into<String>) -> Self {
97        Self {
98            title: title.into(),
99            ..Self::default()
100        }
101    }
102
103    /// 设置窗口标题。
104    pub fn title(mut self, title: impl Into<String>) -> Self {
105        self.title = title.into();
106        self
107    }
108
109    /// 设置窗口初始逻辑宽高 `(width, height)`。
110    #[inline]
111    pub const fn size(mut self, width: i16, height: i16) -> Self {
112        self.width = width;
113        self.height = height;
114        self
115    }
116
117    /// 设置窗口初始主题。
118    #[inline]
119    pub const fn theme(mut self, theme: CoreTheme) -> Self {
120        self.theme = Some(theme);
121        self
122    }
123
124    /// 设置窗口初始语言区域。
125    #[inline]
126    pub const fn locale(mut self, locale: Locale) -> Self {
127        self.locale = Some(locale);
128        self
129    }
130
131    /// 显式锁定 HiDPI 缩放倍率(如 `1` / `2`)。
132    #[inline]
133    pub const fn dpi_scale(mut self, scale: usize) -> Self {
134        self.dpi_scale = Some(scale);
135        self
136    }
137
138    /// 配置渲染后端(GPU 或 Software)。
139    #[inline]
140    pub const fn backend(mut self, backend: DesktopRenderBackend) -> Self {
141        self.backend = Some(backend);
142        self
143    }
144
145    /// 使用内置多线程软件光栅渲染器。
146    #[inline]
147    pub const fn software(mut self) -> Self {
148        self.backend = Some(DesktopRenderBackend::Software);
149        self
150    }
151
152    /// 使用硬件加速 `wgpu` 2D SDF 渲染器。
153    #[inline]
154    pub const fn gpu(mut self) -> Self {
155        self.backend = Some(DesktopRenderBackend::Wgpu);
156        self
157    }
158
159    /// 绑定未命中滚动容器时的回退滚动列表 ID。
160    #[inline]
161    pub const fn scroll_list_id(mut self, id: u32) -> Self {
162        self.scroll_list_id = Some(id);
163        self
164    }
165}
166
167/// 已打开窗口的类型化根视图句柄。
168#[derive(Copy, Clone, PartialEq, Eq, Debug)]
169pub struct WindowHandle<V> {
170    root: Handle<V>,
171}
172
173impl<V> WindowHandle<V> {
174    /// 获取窗口根视图的强类型 [`Handle<V>`]。
175    #[inline(always)]
176    pub const fn root(&self) -> Handle<V> {
177        self.root
178    }
179}
180
181/// 窗口初始化闭包上下文(在 [`open_window`] 回调中提供 `cx.new(|cx| ...)` 与子视图挂载能力)。
182pub struct WindowContext<'a> {
183    engine: &'a mut VeloxEngine,
184}
185
186impl<'a> WindowContext<'a> {
187    /// 构造并挂载窗口根视图(参照 `gpui-kit` `|cx| cx.new(|_| Example)` 写法)。
188    #[inline]
189    pub fn new<V: View>(&mut self, build: impl FnOnce(&mut Self) -> V) -> Handle<V> {
190        let view = build(self);
191        self.engine.mount_root(view)
192    }
193
194    /// 注册一个独立的子视图(L2 局部重排边界),返回其 [`Handle<V>`]。
195    #[inline]
196    pub fn insert_view<V: View>(&mut self, view: V) -> Handle<V> {
197        self.engine.insert_view(view)
198    }
199
200    /// 直接挂载已构造好的根视图实例。
201    #[inline]
202    pub fn mount_root<V: View>(&mut self, view: V) -> Handle<V> {
203        self.engine.mount_root(view)
204    }
205
206    /// 获取当前窗口绑定的 [`VeloxEngine`] 只读引用。
207    #[inline(always)]
208    pub fn engine(&self) -> &VeloxEngine {
209        self.engine
210    }
211
212    /// 获取当前窗口绑定的 [`VeloxEngine`] 可变引用(可用于挂载复合子视图、设置初始状态或派生启动任务)。
213    #[inline(always)]
214    pub fn engine_mut(&mut self) -> &mut VeloxEngine {
215        self.engine
216    }
217
218    /// 返回当前引擎绑定的调度器名称。
219    #[inline]
220    pub fn scheduler_name(&self) -> &'static str {
221        self.engine.scheduler_name()
222    }
223
224    /// 在窗口初始化阶段为指定视图派生启动期前景异步任务。
225    #[inline]
226    pub fn spawn_for<V, T, F, Fut>(&mut self, handle: Handle<V>, f: F) -> Task<T>
227    where
228        V: View,
229        T: 'static,
230        F: FnOnce(Handle<V>, crate::async_rt::AsyncApp) -> Fut,
231        Fut: core::future::Future<Output = T> + 'static,
232    {
233        self.engine.spawn_for(handle, f)
234    }
235}
236
237/// 无头构建完成后返回的已初始化窗口与引擎(供自动化测试、`--headless` 与 `--save-png` 零弹窗复用)。
238pub struct BuiltWindow {
239    pub options: WindowOptions,
240    pub engine: VeloxEngine,
241}
242
243/// 应用级启动上下文(传入 [`Application::run`] 回调,参照 `gpui-kit` `|cx| { init(cx); open_window(..., cx, ...); }`)。
244pub struct AppContext {
245    scheduler: Arc<dyn SchedulerBackend>,
246    theme: CoreTheme,
247    locale: Option<Locale>,
248    static_catalog: Option<&'static StaticCatalog>,
249    dynamic_catalog: Option<Arc<DynamicCatalog>>,
250    backend: DesktopRenderBackend,
251    dpi_scale: Option<usize>,
252    primary_window: Option<BuiltWindow>,
253}
254
255impl AppContext {
256    /// 设置全局默认异步调度器后端(后续打开的窗口将自动继承)。
257    pub fn set_scheduler(&mut self, scheduler: Arc<dyn SchedulerBackend>) {
258        self.scheduler = scheduler;
259    }
260
261    /// 返回当前应用配置的异步调度器名称。
262    #[inline]
263    pub fn scheduler_name(&self) -> &'static str {
264        self.scheduler.name()
265    }
266
267    /// 设置全局默认主题。
268    #[inline]
269    pub fn set_theme(&mut self, theme: CoreTheme) {
270        self.theme = theme;
271    }
272
273    /// 设置全局默认语言区域。
274    #[inline]
275    pub fn set_locale(&mut self, locale: Locale) {
276        self.locale = Some(locale);
277    }
278
279    /// 注册全局静态多语言翻译词典。
280    #[inline]
281    pub fn set_i18n_catalog(&mut self, catalog: &'static StaticCatalog) {
282        self.static_catalog = Some(catalog);
283    }
284
285    /// 注册全局动态多语言翻译词典。
286    #[inline]
287    pub fn set_dynamic_catalog(&mut self, catalog: Arc<DynamicCatalog>) {
288        self.dynamic_catalog = Some(catalog);
289    }
290
291    /// 设置默认桌面渲染后端。
292    #[inline]
293    pub fn set_backend(&mut self, backend: DesktopRenderBackend) {
294        self.backend = backend;
295    }
296
297    /// 打开主桌面窗口并挂载根视图。
298    pub fn open_window<V: View>(
299        &mut self,
300        options: WindowOptions,
301        build_root: impl FnOnce(&mut WindowContext<'_>) -> Handle<V>,
302    ) -> Result<WindowHandle<V>, AppError> {
303        if self.primary_window.is_some() {
304            return Err(AppError::WindowAlreadyOpen);
305        }
306
307        let w = options.width.max(1);
308        let h = options.height.max(1);
309        let mut engine = VeloxEngine::new(w, h).with_scheduler(Arc::clone(&self.scheduler));
310        engine.set_theme(options.theme.unwrap_or(self.theme));
311        if let Some(loc) = options.locale.or(self.locale) {
312            engine.set_locale(loc);
313        }
314        if let Some(cat) = self.static_catalog {
315            engine.set_i18n_catalog(cat);
316        }
317        if let Some(cat) = &self.dynamic_catalog {
318            engine.set_dynamic_catalog(Arc::clone(cat));
319        }
320
321        let root = {
322            let mut wcx = WindowContext {
323                engine: &mut engine,
324            };
325            build_root(&mut wcx)
326        };
327
328        let mut merged_opts = options;
329        if merged_opts.backend.is_none() {
330            merged_opts.backend = Some(self.backend);
331        }
332        if merged_opts.dpi_scale.is_none() {
333            merged_opts.dpi_scale = self.dpi_scale;
334        }
335
336        self.primary_window = Some(BuiltWindow {
337            options: merged_opts,
338            engine,
339        });
340        Ok(WindowHandle { root })
341    }
342}
343
344/// 极简跨平台桌面应用启动构建器(由 [`application`] 创建,参照 `gpui-kit`)。
345pub struct Application {
346    scheduler: Arc<dyn SchedulerBackend>,
347    theme: CoreTheme,
348    locale: Option<Locale>,
349    static_catalog: Option<&'static StaticCatalog>,
350    dynamic_catalog: Option<Arc<DynamicCatalog>>,
351    backend: DesktopRenderBackend,
352    dpi_scale: Option<usize>,
353}
354
355impl Default for Application {
356    fn default() -> Self {
357        Self::new()
358    }
359}
360
361impl Application {
362    /// 创建一个使用内置零依赖 [`NativeStdScheduler`] 与默认暗色主题的 [`Application`] 构建器。
363    pub fn new() -> Self {
364        Self {
365            scheduler: NativeStdScheduler::global(),
366            theme: CoreTheme::dark(),
367            locale: None,
368            static_catalog: None,
369            dynamic_catalog: None,
370            backend: DesktopRenderBackend::default_desktop(),
371            dpi_scale: None,
372        }
373    }
374
375    /// 注入自定义可插拔异步调度器后端(如 `velox-async` 的 `TokioScheduler::global()` 或 `SmolScheduler::global()`)。
376    pub fn with_scheduler(mut self, scheduler: Arc<dyn SchedulerBackend>) -> Self {
377        self.scheduler = scheduler;
378        self
379    }
380
381    /// 配置应用级默认主题。
382    #[inline]
383    pub const fn with_theme(mut self, theme: CoreTheme) -> Self {
384        self.theme = theme;
385        self
386    }
387
388    /// 配置应用级默认语言区域。
389    #[inline]
390    pub const fn with_locale(mut self, locale: Locale) -> Self {
391        self.locale = Some(locale);
392        self
393    }
394
395    /// 注册应用级静态多语言翻译目录。
396    #[inline]
397    pub const fn with_i18n_catalog(mut self, catalog: &'static StaticCatalog) -> Self {
398        self.static_catalog = Some(catalog);
399        self
400    }
401
402    /// 注册应用级动态多语言翻译目录。
403    pub fn with_dynamic_catalog(mut self, catalog: Arc<DynamicCatalog>) -> Self {
404        self.dynamic_catalog = Some(catalog);
405        self
406    }
407
408    /// 配置应用级默认桌面渲染后端(GPU / Software)。
409    #[inline]
410    pub const fn with_backend(mut self, backend: DesktopRenderBackend) -> Self {
411        self.backend = backend;
412        self
413    }
414
415    /// 显式锁定 HiDPI 缩放倍率。
416    #[inline]
417    pub const fn with_dpi_scale(mut self, scale: usize) -> Self {
418        self.dpi_scale = Some(scale);
419        self
420    }
421
422    fn into_context(self) -> AppContext {
423        AppContext {
424            scheduler: self.scheduler,
425            theme: self.theme,
426            locale: self.locale,
427            static_catalog: self.static_catalog,
428            dynamic_catalog: self.dynamic_catalog,
429            backend: self.backend,
430            dpi_scale: self.dpi_scale,
431            primary_window: None,
432        }
433    }
434
435    /// 以无头模式执行应用初始化回调并返回已配置好的 [`BuiltWindow`](不弹出真实窗口,专供测试、CI 与 `--headless`)。
436    pub fn build_headless(self, setup: impl FnOnce(&mut AppContext)) -> Option<BuiltWindow> {
437        let mut cx = self.into_context();
438        setup(&mut cx);
439        cx.primary_window
440    }
441
442    /// 启动桌面应用主事件循环:执行 `setup` 打开窗口并自动接管原生 `winit` 事件循环。
443    pub fn run(self, setup: impl FnOnce(&mut AppContext)) {
444        let Some(built) = self.build_headless(setup) else {
445            return;
446        };
447        let BuiltWindow { options, engine } = built;
448        let mut plat = WinitPlatform::new(
449            options.title,
450            options.width.max(1) as usize,
451            options.height.max(1) as usize,
452        )
453        .with_backend(
454            options
455                .backend
456                .unwrap_or_else(DesktopRenderBackend::default_desktop),
457        );
458        if let Some(scale) = options.dpi_scale {
459            plat = plat.with_dpi_scale(scale);
460        }
461        if let Some(scroll_id) = options.scroll_list_id {
462            plat.run(engine, Some(scroll_id));
463        } else {
464            plat.run_event_loop(engine);
465        }
466    }
467}
468
469/// 创建桌面应用启动构建器(对齐 `gpui_kit::application()`)。
470#[inline]
471pub fn application() -> Application {
472    Application::new()
473}
474
475/// 初始化 Velox 应用默认环境(对齐 `gpui_kit::init(cx)` 习惯;保留作为扩展初始化锚点)。
476#[inline]
477pub fn init(_cx: &mut AppContext) {}
478
479/// 在应用启动回调中打开桌面窗口并挂载根视图(对齐 `gpui_kit::open_window(options, cx, |cx| cx.new(...))`)。
480#[inline]
481pub fn open_window<V: View>(
482    options: WindowOptions,
483    cx: &mut AppContext,
484    build_root: impl FnOnce(&mut WindowContext<'_>) -> Handle<V>,
485) -> Result<WindowHandle<V>, AppError> {
486    cx.open_window(options, build_root)
487}