Skip to main content

slint_pixel/
lib.rs

1//! slint-pixel:可复用像素风 Slint 1.18 组件库。
2//!
3//! 提供:
4//! - Slint 组件(经 `@slint_pixel` 导入,嵌入你自己的 `.slint`):
5//!   `PixelPainter` 画板、`PixelTitleBar` 标题栏、`PixelButton` 按钮、`PixelCheckBox` 复选、
6//!   `PixelSwitch` 开关、`PixelSlider` 滑块、`PixelTextInput` 输入框、`PixelProgressBar` 进度条、
7//!   `PixelBadge` 徽章、`PixelPanel` 面板、`PixelDialog` 对话框、`Swatch` 色块。
8//! - 成品窗口 [`PixelPainterWindow`](Rust 类型,直接 `::new()` 使用)。
9//! - Rust 侧一键接线:`install_painter()`(画/擦、清空、导出 PNG)与
10//!   `install_title_bar_controls()`(拖拽、最小化、最大化、关闭)。
11//! - `library_paths()`:供下游 crate 的 build.rs 注册 `@slint_pixel` 库导入。
12//! - 画布数据:[`Canvas`](网格级 RGBA + 放大渲染 + PNG 导出)。
13//!
14//! # 在其它 Slint 项目里复用
15//!
16//! ## 1. 添加依赖
17//!
18//! ```toml
19//! [dependencies]
20//! slint = "1.18"
21//! slint-pixel = { path = "../slint-pixel" }
22//!
23//! [build-dependencies]
24//! slint-build = "1.18"
25//! slint-pixel = { path = "../slint-pixel" }
26//! ```
27//!
28//! ## 2. `build.rs` 注册库路径并编译自己的 `.slint`
29//!
30//! ```ignore
31//! let config = slint_build::CompilerConfiguration::new()
32//!     .with_library_paths(slint_pixel::library_paths());
33//! slint_build::compile_with_config("ui/main.slint", config).unwrap();
34//! ```
35//!
36//! ## 3. 在 `ui/main.slint` 中导入组件
37//!
38//! ```slint,ignore
39//! import { PixelPainter, PixelTitleBar } from "@slint_pixel";
40//! ```
41//!
42//! ## 4. Rust 侧接线(宏把生成类型适配到本库契约,然后一键安装)
43//!
44//! ```ignore
45//! slint::include_modules!();
46//! slint_pixel::impl_painter_ui!(MainWindow);
47//! slint_pixel::impl_title_bar_ui!(MainWindow);
48//!
49//! let ui = MainWindow::new().unwrap();
50//! slint_pixel::install_painter(&ui);
51//! slint_pixel::install_title_bar_controls(&ui);
52//! ui.run().unwrap();
53//! ```
54//!
55//! 也可以直接用成品窗口,连 `.slint` 都不用写:
56//!
57//! ```no_run
58//! use slint::ComponentHandle;
59//!
60//! let ui = slint_pixel::PixelPainterWindow::new().unwrap();
61//! slint_pixel::install_painter(&ui);
62//! slint_pixel::install_title_bar_controls(&ui);
63//! ui.run().unwrap();
64//! ```
65//!
66#![deny(unsafe_code)]
67
68pub mod canvas;
69
70use std::cell::RefCell;
71use std::collections::HashMap;
72use std::path::PathBuf;
73use std::rc::Rc;
74
75pub use canvas::{Canvas, CELL_PX, GRID};
76
77slint::include_modules!();
78
79/// 返回 `@slint_pixel` 库路径表,供下游 crate 的 build.rs 注册。
80///
81/// 返回值是绝对路径(基于本库的 manifest 目录),与库内 build.rs 保持一致。
82pub fn library_paths() -> HashMap<String, PathBuf> {
83    HashMap::from([(
84        "slint_pixel".to_string(),
85        PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("ui/lib.slint"),
86    )])
87}
88
89/// 画板接线契约:任何暴露 `PixelPainter` 相同属性/回调的 Slint 组件均可实现。
90///
91/// 不需要手写实现——对由 `@slint_pixel` 生成的组件调用 [`impl_painter_ui!`]
92/// 即可自动适配(trait 方法名与生成代码的固有方法一致时,固有方法优先)。
93pub trait PainterUi: slint::ComponentHandle {
94    fn set_canvas_image(&self, image: slint::Image);
95    fn set_status_text(&self, text: slint::SharedString);
96    fn get_brush_size(&self) -> i32;
97    fn get_eraser(&self) -> bool;
98    fn get_brush_color(&self) -> slint::Color;
99    fn on_paint(&self, cb: impl FnMut(f32, f32, bool) + 'static);
100    fn on_clear_canvas(&self, cb: impl FnMut() + 'static);
101    fn on_save_png(&self, cb: impl FnMut() + 'static);
102}
103
104/// 为生成类型实现 [`PainterUi`]。用法:
105/// ```rust,ignore
106/// slint_pixel::impl_painter_ui!(MainWindow);
107/// ```
108#[macro_export]
109macro_rules! impl_painter_ui {
110    ($ty:ty) => {
111        impl $crate::PainterUi for $ty {
112            fn set_canvas_image(&self, image: ::slint::Image) {
113                self.set_canvas_image(image);
114            }
115            fn set_status_text(&self, text: ::slint::SharedString) {
116                self.set_status_text(text);
117            }
118            fn get_brush_size(&self) -> i32 {
119                self.get_brush_size()
120            }
121            fn get_eraser(&self) -> bool {
122                self.get_eraser()
123            }
124            fn get_brush_color(&self) -> ::slint::Color {
125                self.get_brush_color()
126            }
127            fn on_paint(&self, cb: impl FnMut(f32, f32, bool) + 'static) {
128                self.on_paint(cb);
129            }
130            fn on_clear_canvas(&self, cb: impl FnMut() + 'static) {
131                self.on_clear_canvas(cb);
132            }
133            fn on_save_png(&self, cb: impl FnMut() + 'static) {
134                self.on_save_png(cb);
135            }
136        }
137    };
138}
139
140/// 像素标题栏接线契约:带 `drag-start / minimize / toggle-maximize / close-window`
141/// 回调的组件(如 `PixelTitleBar` 或组装后的窗口)均可实现。
142pub trait TitleBarUi: slint::ComponentHandle {
143    fn on_drag_start(&self, cb: impl FnMut() + 'static);
144    fn on_minimize(&self, cb: impl FnMut() + 'static);
145    fn on_toggle_maximize(&self, cb: impl FnMut() + 'static);
146    fn on_close_window(&self, cb: impl FnMut() + 'static);
147}
148
149/// 为生成类型实现 [`TitleBarUi`]。用法:
150/// ```rust,ignore
151/// slint_pixel::impl_title_bar_ui!(MainWindow);
152/// ```
153#[macro_export]
154macro_rules! impl_title_bar_ui {
155    ($ty:ty) => {
156        impl $crate::TitleBarUi for $ty {
157            fn on_drag_start(&self, cb: impl FnMut() + 'static) {
158                self.on_drag_start(cb);
159            }
160            fn on_minimize(&self, cb: impl FnMut() + 'static) {
161                self.on_minimize(cb);
162            }
163            fn on_toggle_maximize(&self, cb: impl FnMut() + 'static) {
164                self.on_toggle_maximize(cb);
165            }
166            fn on_close_window(&self, cb: impl FnMut() + 'static) {
167                self.on_close_window(cb);
168            }
169        }
170    };
171}
172
173// 本库自带的成品窗口直接实现接线契约,开箱即用:
174// `PixelPainterWindow` 无需再调用宏,可直接传给 install_painter / install_title_bar_controls。
175crate::impl_painter_ui!(PixelPainterWindow);
176crate::impl_title_bar_ui!(PixelPainterWindow);
177
178/// 安装画板接线:画/擦、清空、导出 PNG,并返回画布句柄(供高级用法直接读写)。
179///
180/// 导出目录为进程当前工作目录,文件名 `pixel-art-<时间戳>.png`。
181pub fn install_painter<T: PainterUi + 'static>(ui: &T) -> Rc<RefCell<Canvas>> {
182    let canvas = Rc::new(RefCell::new(Canvas::new(GRID, CELL_PX)));
183    ui.set_canvas_image(canvas.borrow().render_display());
184
185    // 画笔 / 擦除
186    let weak = ui.as_weak();
187    let canvas_paint = canvas.clone();
188    ui.on_paint(move |x, y, erase| {
189        let Some(ui) = weak.upgrade() else { return };
190        let col = cell_index(x);
191        let row = cell_index(y);
192        let size = ui.get_brush_size().max(1) as usize;
193        let color = if erase || ui.get_eraser() {
194            None
195        } else {
196            Some(to_rgba(ui.get_brush_color()))
197        };
198        canvas_paint.borrow_mut().paint_brush(col, row, size, color);
199        ui.set_canvas_image(canvas_paint.borrow().render_display());
200    });
201
202    // 清空画布
203    let weak = ui.as_weak();
204    let canvas_clear = canvas.clone();
205    ui.on_clear_canvas(move || {
206        let Some(ui) = weak.upgrade() else { return };
207        canvas_clear.borrow_mut().clear();
208        ui.set_canvas_image(canvas_clear.borrow().render_display());
209        ui.set_status_text("画布已清空".into());
210    });
211
212    // 导出 PNG(保存到当前工作目录)
213    let weak = ui.as_weak();
214    let canvas_save = canvas.clone();
215    ui.on_save_png(move || {
216        let Some(ui) = weak.upgrade() else { return };
217        let path = export_path();
218        match canvas_save.borrow().export_png(&path) {
219            Ok(()) => ui.set_status_text(format!("已保存: {}", path.display()).into()),
220            Err(e) => ui.set_status_text(format!("保存失败: {e}").into()),
221        }
222    });
223
224    canvas
225}
226
227/// 安装像素标题栏窗口控制:拖拽移动、最小化、最大化/还原、关闭。
228pub fn install_title_bar_controls<T: TitleBarUi + 'static>(ui: &T) {
229    install_title_bar_controls_impl(ui, true);
230}
231
232/// 同 [`install_title_bar_controls`],但关闭只隐藏当前窗口、不退出整个事件循环
233/// (适合子窗口;主窗口关闭用 `quit_on_close: true`)。
234pub fn install_title_bar_controls_no_quit<T: TitleBarUi + 'static>(ui: &T) {
235    install_title_bar_controls_impl(ui, false);
236}
237
238fn install_title_bar_controls_impl<T: TitleBarUi + 'static>(ui: &T, quit_on_close: bool) {
239    use slint::winit_030::WinitWindowAccessor;
240
241    // 拖拽移动
242    let weak = ui.as_weak();
243    ui.on_drag_start(move || {
244        let Some(ui) = weak.upgrade() else { return };
245        ui.window().with_winit_window(|w| {
246            let _ = w.drag_window();
247        });
248    });
249
250    // 最小化
251    let weak = ui.as_weak();
252    ui.on_minimize(move || {
253        if let Some(ui) = weak.upgrade() {
254            ui.window().set_minimized(true);
255        }
256    });
257
258    // 最大化 / 还原
259    let weak = ui.as_weak();
260    ui.on_toggle_maximize(move || {
261        if let Some(ui) = weak.upgrade() {
262            let maximized = ui.window().is_maximized();
263            ui.window().set_maximized(!maximized);
264        }
265    });
266
267    // 关闭
268    let weak = ui.as_weak();
269    ui.on_close_window(move || {
270        if let Some(ui) = weak.upgrade() {
271            let _ = ui.window().hide();
272            if quit_on_close {
273                let _ = slint::quit_event_loop();
274            }
275        }
276    });
277}
278
279/// 窗口缩放接线契约:带 `begin-resize(direction)` 回调的组件(配合 PixelWindowResize 热区)。
280pub trait ResizeUi: slint::ComponentHandle {
281    fn on_begin_resize(&self, cb: impl FnMut(slint::SharedString) + 'static);
282}
283
284/// 为生成类型实现 [`ResizeUi`]。用法:
285/// ```rust,ignore
286/// slint_pixel::impl_resize_ui!(MainWindow);
287/// ```
288#[macro_export]
289macro_rules! impl_resize_ui {
290    ($ty:ty) => {
291        impl $crate::ResizeUi for $ty {
292            fn on_begin_resize(&self, cb: impl FnMut(::slint::SharedString) + 'static) {
293                self.on_begin_resize(cb);
294            }
295        }
296    };
297}
298
299/// 安装无边框窗口缩放:把 `PixelWindowResize` 热区的方向回调接到
300/// winit 的 `drag_resize_window`(系统级缩放循环,跨平台)。
301pub fn install_window_resize<T: ResizeUi + 'static>(ui: &T) {
302    use slint::winit_030::winit::window::ResizeDirection;
303    use slint::winit_030::WinitWindowAccessor;
304
305    let weak = ui.as_weak();
306    ui.on_begin_resize(move |dir| {
307        let Some(ui) = weak.upgrade() else { return };
308        let direction = match dir.as_str() {
309            "north" => ResizeDirection::North,
310            "south" => ResizeDirection::South,
311            "east" => ResizeDirection::East,
312            "west" => ResizeDirection::West,
313            "north-east" => ResizeDirection::NorthEast,
314            "north-west" => ResizeDirection::NorthWest,
315            "south-east" => ResizeDirection::SouthEast,
316            "south-west" => ResizeDirection::SouthWest,
317            _ => return,
318        };
319        ui.window().with_winit_window(|w| {
320            let _ = w.drag_resize_window(direction);
321        });
322    });
323}
324
325/// 开启透明窗口,无边框窗口做「圆角窗身」时必须调用它。
326///
327/// 用法(在创建任何窗口之前设置 backend,把 hook 串进去):
328///
329/// ```ignore
330/// slint::BackendSelector::new()
331///     .with_winit_window_attributes_hook(|attrs| slint_pixel::transparent_window(attrs))
332///     .select()?;
333/// ```
334///
335/// 配方(三步,缺一不可):
336/// 1. 宿主打开透明窗口(本函数);
337/// 2. `PixelTheme.window-radius = 12px`(或任意 > 0 的值;默认 0px 表示直角窗口、旧观感);
338/// 3. 窗口内容放进 `PixelWindowBody { ... }`(它负责透明边距 + 圆角 + 描边 + clip)。
339///
340/// 不打开透明窗口就设 `window-radius > 0`,圆角外那圈边距会显示成黑边。
341pub fn transparent_window(
342    attributes: slint::winit_030::winit::window::WindowAttributes,
343) -> slint::winit_030::winit::window::WindowAttributes {
344    attributes.with_transparent(true)
345}
346
347/// 把 `child` 窗口设为 `owner` 的子窗口。
348/// Windows 上子窗口不再单独出现在任务栏(跟随 owner 一起最小化/还原);
349/// 其他平台为 no-op。需在窗口 `show()` 且 winit 窗口创建完成后调用
350/// (`with_winit_window` 只在事件循环运行时有效,show 后窗口是异步创建的,
351/// 通常需在事件循环内调用,或 show 后延迟一小段时间)。
352#[cfg(target_os = "windows")]
353pub fn attach_owner<C: slint::ComponentHandle, O: slint::ComponentHandle>(child: &C, owner: &O) {
354    use slint::winit_030::WinitWindowAccessor;
355    let child_hwnd = child.window().with_winit_window(win_hwnd);
356    let owner_hwnd = owner.window().with_winit_window(win_hwnd);
357    if let (Some(Some(c)), Some(Some(o))) = (child_hwnd, owner_hwnd) {
358        set_parent_hwnd(c, o);
359    }
360}
361
362/// 非 Windows 平台:无 owner 概念,no-op(macOS 用 NSWindow parent、Linux 用 transient 由宿主自行处理)。
363#[cfg(not(target_os = "windows"))]
364pub fn attach_owner<C: slint::ComponentHandle, O: slint::ComponentHandle>(_child: &C, _owner: &O) {}
365
366#[cfg(target_os = "windows")]
367#[allow(unsafe_code)]
368fn win_hwnd(w: &slint::winit_030::winit::window::Window) -> Option<isize> {
369    use raw_window_handle::{HasWindowHandle, RawWindowHandle};
370    let handle = w.window_handle().ok()?;
371    match handle.as_raw() {
372        RawWindowHandle::Win32(h) => Some(h.hwnd.get()),
373        _ => None,
374    }
375}
376
377#[cfg(target_os = "windows")]
378#[allow(unsafe_code)]
379fn set_parent_hwnd(child: isize, owner: isize) {
380    const GWLP_HWNDPARENT: i32 = -8;
381    // SAFETY: 标准 Win32 API;HWND 来自 winit 窗口,调用发生在 UI 线程
382    unsafe extern "system" {
383        fn SetWindowLongPtrW(
384            hWnd: *const core::ffi::c_void,
385            nIndex: i32,
386            dwNewLong: isize,
387        ) -> isize;
388    }
389    // SAFETY: child/owner 是有效 HWND,由 winit 窗口句柄转换而来
390    unsafe {
391        SetWindowLongPtrW(child as *const core::ffi::c_void, GWLP_HWNDPARENT, owner);
392    }
393}
394/// 逻辑坐标 → 网格列/行(越界裁剪到画布内)。
395fn cell_index(pos: f32) -> usize {
396    let cell = (pos / CELL_PX as f32) as i32;
397    cell.clamp(0, GRID as i32 - 1) as usize
398}
399
400fn to_rgba(color: slint::Color) -> [u8; 4] {
401    [color.red(), color.green(), color.blue(), color.alpha()]
402}
403
404fn export_path() -> PathBuf {
405    let name = format!("pixel-art-{}.png", timestamp());
406    std::env::current_dir()
407        .unwrap_or_else(|_| PathBuf::from("."))
408        .join(name)
409}
410
411fn timestamp() -> u64 {
412    std::time::SystemTime::now()
413        .duration_since(std::time::UNIX_EPOCH)
414        .map(|d| d.as_secs())
415        .unwrap_or(0)
416}