use std::path::PathBuf;
use std::rc::Rc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use mgui_core::{Rect, Size};
use mgui_shell::{
ClipboardHandle, CursorIcon, FileDialogOptions, FileDragOptions, FileDragOutcome, NativeMenuController,
Notification, ResizeDirection, ShellMetrics, SystemTheme, WindowCommand, WindowCommandBus, WindowCorners,
WindowShell, WindowState,
};
use winit::dpi::{LogicalPosition, LogicalSize};
use winit::window::{
CursorIcon as WinitCursorIcon, Fullscreen, ResizeDirection as WinitResizeDirection, Theme as WinitTheme, Window,
WindowLevel as WinitWindowLevel,
};
#[derive(Clone)]
pub struct DesktopWindow {
window: Arc<Window>,
close_requested: Arc<AtomicBool>,
tray_available: Arc<AtomicBool>,
app_id: Option<String>,
clipboard: ClipboardHandle,
native_menu: Option<Rc<dyn NativeMenuController>>,
window_commands: Option<WindowCommandBus>,
window_name: Option<String>,
}
impl DesktopWindow {
pub fn new(window: Arc<Window>) -> Self {
Self {
window,
close_requested: Arc::new(AtomicBool::new(false)),
tray_available: Arc::new(AtomicBool::new(false)),
app_id: None,
clipboard: ClipboardHandle::new(Box::new(crate::clipboard::DesktopClipboard::new())),
native_menu: None,
window_commands: None,
window_name: None,
}
}
pub fn with_window_identity(mut self, name: impl Into<String>, bus: WindowCommandBus) -> Self {
self.window_name = Some(name.into());
self.window_commands = Some(bus);
self
}
pub fn set_native_menu_controller(&mut self, controller: Option<Rc<dyn NativeMenuController>>) {
self.native_menu = controller;
}
pub fn with_app_id(mut self, app_id: impl Into<String>) -> Self {
self.app_id = Some(app_id.into());
self
}
pub fn as_winit(&self) -> &Arc<Window> {
&self.window
}
pub fn take_close_request(&self) -> bool {
self.close_requested.swap(false, Ordering::SeqCst)
}
pub fn set_tray_available(&self, available: bool) {
self.tray_available.store(available, Ordering::SeqCst);
}
fn dialog(&self, options: &FileDialogOptions) -> rfd::FileDialog {
let mut dialog = rfd::FileDialog::new().set_parent(self.window.as_ref());
if !options.title.is_empty() {
dialog = dialog.set_title(&options.title);
}
if let Some(directory) = &options.directory {
dialog = dialog.set_directory(directory);
}
if let Some(file_name) = &options.file_name {
dialog = dialog.set_file_name(file_name);
}
for filter in &options.filters {
if filter.extensions.is_empty() {
continue;
}
let extensions: Vec<&str> = filter.extensions.iter().map(String::as_str).collect();
dialog = dialog.add_filter(&filter.name, &extensions);
}
dialog
}
}
impl WindowShell for DesktopWindow {
fn metrics(&self) -> ShellMetrics {
let sf = (self.window.scale_factor() as f32).max(0.01);
let phys = self.window.inner_size();
ShellMetrics::from_physical(phys.width, phys.height, sf)
}
fn request_redraw(&self) {
self.window.request_redraw();
}
fn window_name(&self) -> Option<String> {
self.window_name.clone()
}
fn send_window_command(&self, window: &str, command: WindowCommand) -> Result<(), String> {
match &self.window_commands {
Some(bus) => {
bus.send(window, command);
self.window.request_redraw();
Ok(())
}
None => Err("单窗口宿主没有跨窗口命令总线".to_string()),
}
}
fn set_title(&self, title: &str) {
self.window.set_title(title);
}
fn set_visible(&self, visible: bool) {
self.window.set_visible(visible);
}
fn is_visible(&self) -> bool {
self.window.is_visible().unwrap_or(true)
}
fn set_ime_allowed(&self, allowed: bool) {
self.window.set_ime_allowed(allowed);
}
fn set_ime_cursor_area(&self, rect: Rect) {
self.window.set_ime_cursor_area(
LogicalPosition::new(rect.x as f64, rect.y as f64),
LogicalSize::new(rect.width.max(0.0) as f64, rect.height.max(0.0) as f64),
);
}
fn set_cursor(&self, cursor: CursorIcon) {
self.window.set_cursor(map_cursor(cursor));
}
fn set_fullscreen(&self, fullscreen: bool) {
self.window.set_fullscreen(fullscreen.then_some(Fullscreen::Borderless(None)));
}
fn is_fullscreen(&self) -> bool {
self.window.fullscreen().is_some()
}
fn set_minimized(&self, minimized: bool) {
self.window.set_minimized(minimized);
}
fn set_maximized(&self, maximized: bool) {
self.window.set_maximized(maximized);
}
fn is_maximized(&self) -> bool {
self.window.is_maximized()
}
fn focus_window(&self) {
self.window.focus_window();
}
fn set_decorations(&self, decorations: bool) {
self.window.set_decorations(decorations);
}
fn start_dragging(&self) -> Result<(), String> {
self.window.drag_window().map_err(|e| format!("start_dragging: {e}"))
}
fn start_resize(&self, direction: ResizeDirection) -> Result<(), String> {
self.window.drag_resize_window(map_resize_direction(direction)).map_err(|e| format!("start_resize: {e}"))
}
fn set_resizable(&self, resizable: bool) {
self.window.set_resizable(resizable);
}
fn set_always_on_top(&self, on_top: bool) {
self.window.set_window_level(if on_top { WinitWindowLevel::AlwaysOnTop } else { WinitWindowLevel::Normal });
}
fn set_size(&self, size: Size) {
let _ = self.window.request_inner_size(LogicalSize::new(size.width as f64, size.height as f64));
}
fn set_position(&self, x: f32, y: f32) {
self.window.set_outer_position(LogicalPosition::new(x as f64, y as f64));
}
fn request_close(&self) {
self.close_requested.store(true, Ordering::SeqCst);
self.window.request_redraw();
}
fn tray_available(&self) -> bool {
self.tray_available.load(Ordering::SeqCst)
}
fn system_theme(&self) -> Option<SystemTheme> {
self.window.theme().map(|theme| match theme {
WinitTheme::Light => SystemTheme::Light,
WinitTheme::Dark => SystemTheme::Dark,
})
}
fn high_contrast(&self) -> bool {
crate::high_contrast::is_enabled()
}
fn clipboard(&self) -> ClipboardHandle {
self.clipboard.clone()
}
fn native_menu(&self) -> Option<Rc<dyn NativeMenuController>> {
self.native_menu.clone()
}
fn set_undecorated_shadow(&self, shadow: bool) {
#[cfg(target_os = "windows")]
{
use winit::platform::windows::WindowExtWindows;
self.window.set_undecorated_shadow(shadow);
}
#[cfg(not(target_os = "windows"))]
let _ = shadow;
}
fn set_window_corners(&self, corners: WindowCorners) {
#[cfg(target_os = "windows")]
{
use winit::platform::windows::{CornerPreference, WindowExtWindows};
let preference = match corners {
WindowCorners::Default => CornerPreference::Default,
WindowCorners::Square => CornerPreference::DoNotRound,
WindowCorners::Rounded => CornerPreference::Round,
};
self.window.set_corner_preference(preference);
}
#[cfg(not(target_os = "windows"))]
let _ = corners;
}
fn window_state(&self) -> Option<WindowState> {
let sf = (self.window.scale_factor() as f32).max(0.01);
let inner = self.window.inner_size();
let size = Size::new(inner.width as f32 / sf, inner.height as f32 / sf);
let position = self.window.outer_position().ok().map(|p| (p.x as f32 / sf, p.y as f32 / sf));
Some(WindowState { size, position, maximized: self.window.is_maximized() })
}
fn pick_file(&self, options: &FileDialogOptions) -> Option<PathBuf> {
self.dialog(options).pick_file()
}
fn pick_files(&self, options: &FileDialogOptions) -> Option<Vec<PathBuf>> {
self.dialog(options).pick_files()
}
fn pick_folder(&self, options: &FileDialogOptions) -> Option<PathBuf> {
self.dialog(options).pick_folder()
}
fn save_file(&self, options: &FileDialogOptions) -> Option<PathBuf> {
self.dialog(options).save_file()
}
fn start_file_drag(&self, paths: &[PathBuf], options: &FileDragOptions) -> Result<FileDragOutcome, String> {
#[cfg(any(target_os = "windows", target_os = "macos"))]
{
if paths.is_empty() {
return Err("拖出文件列表为空".to_string());
}
let preview = options.preview.clone().or_else(|| paths.first().cloned());
let item = drag::DragItem::Files(paths.to_vec());
let image = drag::Image::File(preview.unwrap_or_else(|| paths[0].clone()));
let mode = if options.copy { drag::DragMode::Copy } else { drag::DragMode::Move };
let result = std::sync::Arc::new(std::sync::Mutex::new(None));
let callback_result = std::sync::Arc::clone(&result);
drag::start_drag(
self.window.as_ref(),
item,
image,
move |outcome, _| {
if let Ok(mut slot) = callback_result.lock() {
*slot = Some(outcome);
}
},
drag::Options { mode, ..Default::default() },
)
.map_err(|e| format!("start_file_drag: {e}"))?;
let outcome = result.lock().ok().and_then(|mut slot| slot.take());
Ok(match outcome {
Some(drag::DragResult::Dropped) => FileDragOutcome::Dropped,
Some(drag::DragResult::Cancel) | None => FileDragOutcome::Cancelled,
})
}
#[cfg(not(any(target_os = "windows", target_os = "macos")))]
{
let _ = (paths, options);
Err("当前平台暂不支持从窗口拖出文件".to_string())
}
}
fn show_notification(&self, notification: &Notification) -> Result<(), String> {
crate::notification::show(notification, self.app_id.as_deref())
}
}
fn map_resize_direction(direction: ResizeDirection) -> WinitResizeDirection {
match direction {
ResizeDirection::East => WinitResizeDirection::East,
ResizeDirection::North => WinitResizeDirection::North,
ResizeDirection::NorthEast => WinitResizeDirection::NorthEast,
ResizeDirection::NorthWest => WinitResizeDirection::NorthWest,
ResizeDirection::South => WinitResizeDirection::South,
ResizeDirection::SouthEast => WinitResizeDirection::SouthEast,
ResizeDirection::SouthWest => WinitResizeDirection::SouthWest,
ResizeDirection::West => WinitResizeDirection::West,
}
}
fn map_cursor(cursor: CursorIcon) -> WinitCursorIcon {
match cursor {
CursorIcon::Default => WinitCursorIcon::Default,
CursorIcon::Pointer => WinitCursorIcon::Pointer,
CursorIcon::Text => WinitCursorIcon::Text,
CursorIcon::Crosshair => WinitCursorIcon::Crosshair,
CursorIcon::Move => WinitCursorIcon::Move,
CursorIcon::NotAllowed => WinitCursorIcon::NotAllowed,
CursorIcon::Wait => WinitCursorIcon::Wait,
CursorIcon::Progress => WinitCursorIcon::Progress,
CursorIcon::Help => WinitCursorIcon::Help,
CursorIcon::Grab => WinitCursorIcon::Grab,
CursorIcon::Grabbing => WinitCursorIcon::Grabbing,
CursorIcon::ZoomIn => WinitCursorIcon::ZoomIn,
CursorIcon::ZoomOut => WinitCursorIcon::ZoomOut,
CursorIcon::ResizeHorizontal => WinitCursorIcon::EwResize,
CursorIcon::ResizeVertical => WinitCursorIcon::NsResize,
CursorIcon::ResizeNwSe => WinitCursorIcon::NwseResize,
CursorIcon::ResizeNeSw => WinitCursorIcon::NeswResize,
CursorIcon::ResizeAll => WinitCursorIcon::AllScroll,
CursorIcon::ColumnResize => WinitCursorIcon::ColResize,
CursorIcon::RowResize => WinitCursorIcon::RowResize,
}
}