1#![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
79pub 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
89pub 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#[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
140pub 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#[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
173crate::impl_painter_ui!(PixelPainterWindow);
176crate::impl_title_bar_ui!(PixelPainterWindow);
177
178pub 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 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 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 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
227pub fn install_title_bar_controls<T: TitleBarUi + 'static>(ui: &T) {
229 install_title_bar_controls_impl(ui, true);
230}
231
232pub 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 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 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 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 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
279pub trait ResizeUi: slint::ComponentHandle {
281 fn on_begin_resize(&self, cb: impl FnMut(slint::SharedString) + 'static);
282}
283
284#[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
299pub 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
325pub 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#[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#[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 unsafe extern "system" {
383 fn SetWindowLongPtrW(
384 hWnd: *const core::ffi::c_void,
385 nIndex: i32,
386 dwNewLong: isize,
387 ) -> isize;
388 }
389 unsafe {
391 SetWindowLongPtrW(child as *const core::ffi::c_void, GWLP_HWNDPARENT, owner);
392 }
393}
394fn 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}