slint-pixel 0.3.0

可复用像素风 Slint 1.18 组件库:16×16 像素画板 widget + 像素标题栏(跨平台)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
//! slint-pixel:可复用像素风 Slint 1.18 组件库。
//!
//! 提供:
//! - Slint 组件(经 `@slint_pixel` 导入,嵌入你自己的 `.slint`):
//!   `PixelPainter` 画板、`PixelTitleBar` 标题栏、`PixelButton` 按钮、`PixelCheckBox` 复选、
//!   `PixelSwitch` 开关、`PixelSlider` 滑块、`PixelTextInput` 输入框、`PixelProgressBar` 进度条、
//!   `PixelBadge` 徽章、`PixelPanel` 面板、`PixelDialog` 对话框、`Swatch` 色块。
//! - 成品窗口 [`PixelPainterWindow`](Rust 类型,直接 `::new()` 使用)。
//! - Rust 侧一键接线:`install_painter()`(画/擦、清空、导出 PNG)与
//!   `install_title_bar_controls()`(拖拽、最小化、最大化、关闭)。
//! - `library_paths()`:供下游 crate 的 build.rs 注册 `@slint_pixel` 库导入。
//! - 画布数据:[`Canvas`](网格级 RGBA + 放大渲染 + PNG 导出)。
//!
//! # 在其它 Slint 项目里复用
//!
//! ## 1. 添加依赖
//!
//! ```toml
//! [dependencies]
//! slint = "1.18"
//! slint-pixel = { path = "../slint-pixel" }
//!
//! [build-dependencies]
//! slint-build = "1.18"
//! slint-pixel = { path = "../slint-pixel" }
//! ```
//!
//! ## 2. `build.rs` 注册库路径并编译自己的 `.slint`
//!
//! ```ignore
//! let config = slint_build::CompilerConfiguration::new()
//!     .with_library_paths(slint_pixel::library_paths());
//! slint_build::compile_with_config("ui/main.slint", config).unwrap();
//! ```
//!
//! ## 3. 在 `ui/main.slint` 中导入组件
//!
//! ```slint,ignore
//! import { PixelPainter, PixelTitleBar } from "@slint_pixel";
//! ```
//!
//! ## 4. Rust 侧接线(宏把生成类型适配到本库契约,然后一键安装)
//!
//! ```ignore
//! slint::include_modules!();
//! slint_pixel::impl_painter_ui!(MainWindow);
//! slint_pixel::impl_title_bar_ui!(MainWindow);
//!
//! let ui = MainWindow::new().unwrap();
//! slint_pixel::install_painter(&ui);
//! slint_pixel::install_title_bar_controls(&ui);
//! ui.run().unwrap();
//! ```
//!
//! 也可以直接用成品窗口,连 `.slint` 都不用写:
//!
//! ```no_run
//! use slint::ComponentHandle;
//!
//! let ui = slint_pixel::PixelPainterWindow::new().unwrap();
//! slint_pixel::install_painter(&ui);
//! slint_pixel::install_title_bar_controls(&ui);
//! ui.run().unwrap();
//! ```
//!
#![deny(unsafe_code)]

pub mod canvas;

use std::cell::RefCell;
use std::collections::HashMap;
use std::path::PathBuf;
use std::rc::Rc;

pub use canvas::{Canvas, CELL_PX, GRID};

slint::include_modules!();

/// 返回 `@slint_pixel` 库路径表,供下游 crate 的 build.rs 注册。
///
/// 返回值是绝对路径(基于本库的 manifest 目录),与库内 build.rs 保持一致。
pub fn library_paths() -> HashMap<String, PathBuf> {
    HashMap::from([(
        "slint_pixel".to_string(),
        PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("ui/lib.slint"),
    )])
}

/// 画板接线契约:任何暴露 `PixelPainter` 相同属性/回调的 Slint 组件均可实现。
///
/// 不需要手写实现——对由 `@slint_pixel` 生成的组件调用 [`impl_painter_ui!`]
/// 即可自动适配(trait 方法名与生成代码的固有方法一致时,固有方法优先)。
pub trait PainterUi: slint::ComponentHandle {
    fn set_canvas_image(&self, image: slint::Image);
    fn set_status_text(&self, text: slint::SharedString);
    fn get_brush_size(&self) -> i32;
    fn get_eraser(&self) -> bool;
    fn get_brush_color(&self) -> slint::Color;
    fn on_paint(&self, cb: impl FnMut(f32, f32, bool) + 'static);
    fn on_clear_canvas(&self, cb: impl FnMut() + 'static);
    fn on_save_png(&self, cb: impl FnMut() + 'static);
}

/// 为生成类型实现 [`PainterUi`]。用法:
/// ```rust,ignore
/// slint_pixel::impl_painter_ui!(MainWindow);
/// ```
#[macro_export]
macro_rules! impl_painter_ui {
    ($ty:ty) => {
        impl $crate::PainterUi for $ty {
            fn set_canvas_image(&self, image: ::slint::Image) {
                self.set_canvas_image(image);
            }
            fn set_status_text(&self, text: ::slint::SharedString) {
                self.set_status_text(text);
            }
            fn get_brush_size(&self) -> i32 {
                self.get_brush_size()
            }
            fn get_eraser(&self) -> bool {
                self.get_eraser()
            }
            fn get_brush_color(&self) -> ::slint::Color {
                self.get_brush_color()
            }
            fn on_paint(&self, cb: impl FnMut(f32, f32, bool) + 'static) {
                self.on_paint(cb);
            }
            fn on_clear_canvas(&self, cb: impl FnMut() + 'static) {
                self.on_clear_canvas(cb);
            }
            fn on_save_png(&self, cb: impl FnMut() + 'static) {
                self.on_save_png(cb);
            }
        }
    };
}

/// 像素标题栏接线契约:带 `drag-start / minimize / toggle-maximize / close-window`
/// 回调的组件(如 `PixelTitleBar` 或组装后的窗口)均可实现。
pub trait TitleBarUi: slint::ComponentHandle {
    fn on_drag_start(&self, cb: impl FnMut() + 'static);
    fn on_minimize(&self, cb: impl FnMut() + 'static);
    fn on_toggle_maximize(&self, cb: impl FnMut() + 'static);
    fn on_close_window(&self, cb: impl FnMut() + 'static);
}

/// 为生成类型实现 [`TitleBarUi`]。用法:
/// ```rust,ignore
/// slint_pixel::impl_title_bar_ui!(MainWindow);
/// ```
#[macro_export]
macro_rules! impl_title_bar_ui {
    ($ty:ty) => {
        impl $crate::TitleBarUi for $ty {
            fn on_drag_start(&self, cb: impl FnMut() + 'static) {
                self.on_drag_start(cb);
            }
            fn on_minimize(&self, cb: impl FnMut() + 'static) {
                self.on_minimize(cb);
            }
            fn on_toggle_maximize(&self, cb: impl FnMut() + 'static) {
                self.on_toggle_maximize(cb);
            }
            fn on_close_window(&self, cb: impl FnMut() + 'static) {
                self.on_close_window(cb);
            }
        }
    };
}

// 本库自带的成品窗口直接实现接线契约,开箱即用:
// `PixelPainterWindow` 无需再调用宏,可直接传给 install_painter / install_title_bar_controls。
crate::impl_painter_ui!(PixelPainterWindow);
crate::impl_title_bar_ui!(PixelPainterWindow);

/// 安装画板接线:画/擦、清空、导出 PNG,并返回画布句柄(供高级用法直接读写)。
///
/// 导出目录为进程当前工作目录,文件名 `pixel-art-<时间戳>.png`。
pub fn install_painter<T: PainterUi + 'static>(ui: &T) -> Rc<RefCell<Canvas>> {
    let canvas = Rc::new(RefCell::new(Canvas::new(GRID, CELL_PX)));
    ui.set_canvas_image(canvas.borrow().render_display());

    // 画笔 / 擦除
    let weak = ui.as_weak();
    let canvas_paint = canvas.clone();
    ui.on_paint(move |x, y, erase| {
        let Some(ui) = weak.upgrade() else { return };
        let col = cell_index(x);
        let row = cell_index(y);
        let size = ui.get_brush_size().max(1) as usize;
        let color = if erase || ui.get_eraser() {
            None
        } else {
            Some(to_rgba(ui.get_brush_color()))
        };
        canvas_paint.borrow_mut().paint_brush(col, row, size, color);
        ui.set_canvas_image(canvas_paint.borrow().render_display());
    });

    // 清空画布
    let weak = ui.as_weak();
    let canvas_clear = canvas.clone();
    ui.on_clear_canvas(move || {
        let Some(ui) = weak.upgrade() else { return };
        canvas_clear.borrow_mut().clear();
        ui.set_canvas_image(canvas_clear.borrow().render_display());
        ui.set_status_text("画布已清空".into());
    });

    // 导出 PNG(保存到当前工作目录)
    let weak = ui.as_weak();
    let canvas_save = canvas.clone();
    ui.on_save_png(move || {
        let Some(ui) = weak.upgrade() else { return };
        let path = export_path();
        match canvas_save.borrow().export_png(&path) {
            Ok(()) => ui.set_status_text(format!("已保存: {}", path.display()).into()),
            Err(e) => ui.set_status_text(format!("保存失败: {e}").into()),
        }
    });

    canvas
}

/// 安装像素标题栏窗口控制:拖拽移动、最小化、最大化/还原、关闭。
pub fn install_title_bar_controls<T: TitleBarUi + 'static>(ui: &T) {
    install_title_bar_controls_impl(ui, true);
}

/// 同 [`install_title_bar_controls`],但关闭只隐藏当前窗口、不退出整个事件循环
/// (适合子窗口;主窗口关闭用 `quit_on_close: true`)。
pub fn install_title_bar_controls_no_quit<T: TitleBarUi + 'static>(ui: &T) {
    install_title_bar_controls_impl(ui, false);
}

fn install_title_bar_controls_impl<T: TitleBarUi + 'static>(ui: &T, quit_on_close: bool) {
    use slint::winit_030::WinitWindowAccessor;

    // 拖拽移动
    let weak = ui.as_weak();
    ui.on_drag_start(move || {
        let Some(ui) = weak.upgrade() else { return };
        ui.window().with_winit_window(|w| {
            let _ = w.drag_window();
        });
    });

    // 最小化
    let weak = ui.as_weak();
    ui.on_minimize(move || {
        if let Some(ui) = weak.upgrade() {
            ui.window().set_minimized(true);
        }
    });

    // 最大化 / 还原
    let weak = ui.as_weak();
    ui.on_toggle_maximize(move || {
        if let Some(ui) = weak.upgrade() {
            let maximized = ui.window().is_maximized();
            ui.window().set_maximized(!maximized);
        }
    });

    // 关闭
    let weak = ui.as_weak();
    ui.on_close_window(move || {
        if let Some(ui) = weak.upgrade() {
            let _ = ui.window().hide();
            if quit_on_close {
                let _ = slint::quit_event_loop();
            }
        }
    });
}

/// 窗口缩放接线契约:带 `begin-resize(direction)` 回调的组件(配合 PixelWindowResize 热区)。
pub trait ResizeUi: slint::ComponentHandle {
    fn on_begin_resize(&self, cb: impl FnMut(slint::SharedString) + 'static);
}

/// 为生成类型实现 [`ResizeUi`]。用法:
/// ```rust,ignore
/// slint_pixel::impl_resize_ui!(MainWindow);
/// ```
#[macro_export]
macro_rules! impl_resize_ui {
    ($ty:ty) => {
        impl $crate::ResizeUi for $ty {
            fn on_begin_resize(&self, cb: impl FnMut(::slint::SharedString) + 'static) {
                self.on_begin_resize(cb);
            }
        }
    };
}

/// 安装无边框窗口缩放:把 `PixelWindowResize` 热区的方向回调接到
/// winit 的 `drag_resize_window`(系统级缩放循环,跨平台)。
pub fn install_window_resize<T: ResizeUi + 'static>(ui: &T) {
    use slint::winit_030::winit::window::ResizeDirection;
    use slint::winit_030::WinitWindowAccessor;

    let weak = ui.as_weak();
    ui.on_begin_resize(move |dir| {
        let Some(ui) = weak.upgrade() else { return };
        let direction = match dir.as_str() {
            "north" => ResizeDirection::North,
            "south" => ResizeDirection::South,
            "east" => ResizeDirection::East,
            "west" => ResizeDirection::West,
            "north-east" => ResizeDirection::NorthEast,
            "north-west" => ResizeDirection::NorthWest,
            "south-east" => ResizeDirection::SouthEast,
            "south-west" => ResizeDirection::SouthWest,
            _ => return,
        };
        ui.window().with_winit_window(|w| {
            let _ = w.drag_resize_window(direction);
        });
    });
}

/// 开启透明窗口,无边框窗口做「圆角窗身」时必须调用它。
///
/// 用法(在创建任何窗口之前设置 backend,把 hook 串进去):
///
/// ```ignore
/// slint::BackendSelector::new()
///     .with_winit_window_attributes_hook(|attrs| slint_pixel::transparent_window(attrs))
///     .select()?;
/// ```
///
/// 配方(三步,缺一不可):
/// 1. 宿主打开透明窗口(本函数);
/// 2. `PixelTheme.window-radius = 12px`(或任意 > 0 的值;默认 0px 表示直角窗口、旧观感);
/// 3. 窗口内容放进 `PixelWindowBody { ... }`(它负责透明边距 + 圆角 + 描边 + clip)。
///
/// 不打开透明窗口就设 `window-radius > 0`,圆角外那圈边距会显示成黑边。
pub fn transparent_window(
    attributes: slint::winit_030::winit::window::WindowAttributes,
) -> slint::winit_030::winit::window::WindowAttributes {
    attributes.with_transparent(true)
}

/// 把 `child` 窗口设为 `owner` 的子窗口。
/// Windows 上子窗口不再单独出现在任务栏(跟随 owner 一起最小化/还原);
/// 其他平台为 no-op。需在窗口 `show()` 且 winit 窗口创建完成后调用
/// (`with_winit_window` 只在事件循环运行时有效,show 后窗口是异步创建的,
/// 通常需在事件循环内调用,或 show 后延迟一小段时间)。
#[cfg(target_os = "windows")]
pub fn attach_owner<C: slint::ComponentHandle, O: slint::ComponentHandle>(child: &C, owner: &O) {
    use slint::winit_030::WinitWindowAccessor;
    let child_hwnd = child.window().with_winit_window(win_hwnd);
    let owner_hwnd = owner.window().with_winit_window(win_hwnd);
    if let (Some(Some(c)), Some(Some(o))) = (child_hwnd, owner_hwnd) {
        set_parent_hwnd(c, o);
    }
}

/// 非 Windows 平台:无 owner 概念,no-op(macOS 用 NSWindow parent、Linux 用 transient 由宿主自行处理)。
#[cfg(not(target_os = "windows"))]
pub fn attach_owner<C: slint::ComponentHandle, O: slint::ComponentHandle>(_child: &C, _owner: &O) {}

#[cfg(target_os = "windows")]
#[allow(unsafe_code)]
fn win_hwnd(w: &slint::winit_030::winit::window::Window) -> Option<isize> {
    use raw_window_handle::{HasWindowHandle, RawWindowHandle};
    let handle = w.window_handle().ok()?;
    match handle.as_raw() {
        RawWindowHandle::Win32(h) => Some(h.hwnd.get()),
        _ => None,
    }
}

#[cfg(target_os = "windows")]
#[allow(unsafe_code)]
fn set_parent_hwnd(child: isize, owner: isize) {
    const GWLP_HWNDPARENT: i32 = -8;
    // SAFETY: 标准 Win32 API;HWND 来自 winit 窗口,调用发生在 UI 线程
    unsafe extern "system" {
        fn SetWindowLongPtrW(
            hWnd: *const core::ffi::c_void,
            nIndex: i32,
            dwNewLong: isize,
        ) -> isize;
    }
    // SAFETY: child/owner 是有效 HWND,由 winit 窗口句柄转换而来
    unsafe {
        SetWindowLongPtrW(child as *const core::ffi::c_void, GWLP_HWNDPARENT, owner);
    }
}
/// 逻辑坐标 → 网格列/行(越界裁剪到画布内)。
fn cell_index(pos: f32) -> usize {
    let cell = (pos / CELL_PX as f32) as i32;
    cell.clamp(0, GRID as i32 - 1) as usize
}

fn to_rgba(color: slint::Color) -> [u8; 4] {
    [color.red(), color.green(), color.blue(), color.alpha()]
}

fn export_path() -> PathBuf {
    let name = format!("pixel-art-{}.png", timestamp());
    std::env::current_dir()
        .unwrap_or_else(|_| PathBuf::from("."))
        .join(name)
}

fn timestamp() -> u64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0)
}