use super::*;
#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
pub enum QuitMode {
#[default]
Default,
LastWindowClosed,
Explicit,
}
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum QuitReason {
Explicit,
Relaunch,
LastWindowClosed,
OperatingSystem,
}
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub struct QuitRequest {
pub reason: QuitReason,
}
impl QuitMode {
pub(super) const fn quits_when_empty(self) -> bool {
match self {
Self::Default => cfg!(not(target_os = "macos")),
Self::LastWindowClosed => true,
Self::Explicit => false,
}
}
}
#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
pub enum PerformanceProfile {
#[default]
Balanced,
LowPower,
HighPerformance,
}
#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
pub enum WindowAppearance {
#[default]
Light,
Dark,
}
impl WindowAppearance {
pub const fn is_dark(self) -> bool {
matches!(self, Self::Dark)
}
}
#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
pub enum WindowBackgroundAppearance {
#[default]
Opaque,
Transparent,
Blurred,
}
impl WindowBackgroundAppearance {
pub const fn is_transparent(self) -> bool {
!matches!(self, Self::Opaque)
}
pub const fn is_blurred(self) -> bool {
matches!(self, Self::Blurred)
}
pub(super) const fn changes_from(self, previous: Self) -> WindowBackgroundChanges {
WindowBackgroundChanges {
transparency: self.is_transparent() != previous.is_transparent(),
blur: self.is_blurred() != previous.is_blurred(),
}
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(super) struct WindowBackgroundChanges {
pub(super) transparency: bool,
pub(super) blur: bool,
}
#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
pub enum TitleBarStyle {
#[default]
Default,
HiddenInset,
Hidden,
}
#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
pub enum WindowKind {
#[default]
Normal,
Popover,
SystemPopover,
Floating,
Dialog,
}
#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
pub enum WindowLevel {
AlwaysOnBottom,
#[default]
Normal,
AlwaysOnTop,
}
#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
pub enum TaskbarProgressState {
#[default]
None,
Normal,
Indeterminate,
Paused,
Error,
}
#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
pub enum CursorGrabMode {
#[default]
None,
Confined,
Locked,
}
impl CursorGrabMode {
pub(super) const fn to_winit(self) -> WinitCursorGrabMode {
match self {
Self::None => WinitCursorGrabMode::None,
Self::Confined => WinitCursorGrabMode::Confined,
Self::Locked => WinitCursorGrabMode::Locked,
}
}
}
impl WindowLevel {
pub(super) const fn to_winit(self) -> WinitWindowLevel {
match self {
Self::AlwaysOnBottom => WinitWindowLevel::AlwaysOnBottom,
Self::Normal => WinitWindowLevel::Normal,
Self::AlwaysOnTop => WinitWindowLevel::AlwaysOnTop,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum WindowBounds {
Windowed(Rect),
Maximized(Rect),
Fullscreen(Rect),
}
impl WindowBounds {
pub const fn bounds(self) -> Rect {
match self {
Self::Windowed(bounds) | Self::Maximized(bounds) | Self::Fullscreen(bounds) => bounds,
}
}
pub const fn windowed(x: f32, y: f32, width: f32, height: f32) -> Self {
Self::Windowed(Rect::new(x, y, width, height))
}
}
impl Default for WindowBounds {
fn default() -> Self {
Self::Windowed(Rect::new(0.0, 0.0, 960.0, 640.0))
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct WindowState {
pub handle: WindowHandle,
pub display_id: Option<DisplayId>,
pub kind: WindowKind,
pub bounds: WindowBounds,
pub viewport_size: Size,
pub minimum_size: Option<Size>,
pub maximum_size: Option<Size>,
pub scale_factor: f32,
pub appearance: WindowAppearance,
pub background_appearance: WindowBackgroundAppearance,
pub focused: bool,
pub focusable: bool,
pub visible: bool,
pub minimized: bool,
pub maximized: bool,
pub fullscreen: bool,
pub occluded: bool,
pub movable: bool,
pub resizable: bool,
pub minimizable: bool,
pub maximizable: bool,
pub closable: bool,
pub decorated: bool,
pub shadow: bool,
pub content_protected: bool,
pub window_level: WindowLevel,
pub skip_taskbar: bool,
pub visible_on_all_workspaces: bool,
pub opacity: f32,
pub has_icon: bool,
pub taskbar_progress_state: TaskbarProgressState,
pub taskbar_progress: f32,
pub has_taskbar_overlay_icon: bool,
pub cursor_visible: bool,
pub cursor_grab: CursorGrabMode,
pub cursor_hit_test: bool,
pub cursor_position: Option<Point>,
pub represented_file: bool,
pub document_edited: bool,
pub native_tabbing: bool,
pub native_tabs: WindowTabState,
#[cfg(feature = "inspector")]
pub inspector_active: bool,
}
pub const MAX_WINDOW_TITLE_BYTES: usize = 16 * 1024;
pub const MAX_WINDOW_DOCUMENT_PATH_BYTES: usize = 16 * 1024;
pub const MAX_WINDOW_TABBING_IDENTIFIER_BYTES: usize = 4 * 1024;
pub const MAX_SYSTEM_WINDOW_TABS: usize = 256;
pub const MAX_WINDOW_LOGICAL_DIMENSION: f32 = 32_768.0;
pub const MAX_WINDOW_LOGICAL_COORDINATE: f32 = 16_777_216.0;
pub const MAX_WINDOW_COMMANDS_PER_EVENT: usize = 256;
pub const MAX_PENDING_WINDOW_COMMANDS: usize = 1_024;
pub const MAX_CHILD_WINDOW_CLOSE_LISTENERS_PER_WINDOW: usize = 256;
pub const MAX_APPLICATION_WINDOWS: usize = 4_096;
pub const MAX_PENDING_NATIVE_POPUP_MENUS: usize = 16;
#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
pub enum WindowCommandError {
#[error("this context is not attached to a native window")]
Unavailable,
#[error("one event cannot queue more than {MAX_WINDOW_COMMANDS_PER_EVENT} window commands")]
QueueFull,
#[error("window bounds must be finite, positive, and within the supported desktop range")]
InvalidBounds,
#[error("a window title cannot exceed {MAX_WINDOW_TITLE_BYTES} UTF-8 bytes")]
TitleTooLong,
#[error(
"a represented document path must be non-empty, NUL-free, and at most {MAX_WINDOW_DOCUMENT_PATH_BYTES} encoded bytes"
)]
InvalidDocumentPath,
#[error(
"a native tabbing identifier must be non-empty, NUL-free, and at most {MAX_WINDOW_TABBING_IDENTIFIER_BYTES} UTF-8 bytes"
)]
InvalidTabbingIdentifier,
#[error("a native tab index must be smaller than {MAX_SYSTEM_WINDOW_TABS}")]
InvalidTabIndex,
#[error("a hidden titlebar cannot expose or reposition native traffic-light buttons")]
HiddenTitleBarTrafficLights,
#[error("system popovers require one finite parent-relative popover configuration")]
InvalidPopoverConfiguration,
#[error("a system popover must be opened from an existing parent window")]
PopoverParentRequired,
#[error("minimum window size cannot exceed maximum window size")]
InvalidSizeConstraints,
#[error("window opacity must be finite and between 0.0 and 1.0")]
InvalidOpacity,
#[error("taskbar progress must be finite and between 0.0 and 1.0")]
InvalidTaskbarProgress,
#[error(
"a taskbar overlay description must be NUL-free and at most {MAX_TASKBAR_OVERLAY_DESCRIPTION_BYTES} UTF-8 bytes"
)]
InvalidTaskbarOverlayDescription,
#[error("the per-window native menu declaration is invalid")]
InvalidMenus,
}
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub struct WindowTabState {
pub count: usize,
pub selected_index: Option<usize>,
pub tab_bar_visible: bool,
pub overview_visible: bool,
pub truncated: bool,
}
impl Default for WindowTabState {
fn default() -> Self {
Self {
count: 1,
selected_index: Some(0),
tab_bar_visible: false,
overview_visible: false,
truncated: false,
}
}
}
impl WindowTabState {
pub const fn is_valid(self) -> bool {
self.count > 0
&& self.count <= MAX_SYSTEM_WINDOW_TABS
&& match self.selected_index {
Some(index) => index < self.count,
None => true,
}
}
}
static NEXT_WINDOW_HANDLE: AtomicU64 = AtomicU64::new(1);
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct WindowHandle(u64);
impl WindowHandle {
pub(crate) fn next() -> Self {
Self(NEXT_WINDOW_HANDLE.fetch_add(1, Ordering::Relaxed).max(1))
}
pub const fn as_u64(self) -> u64 {
self.0
}
pub const fn from_u64(value: u64) -> Option<Self> {
if value == 0 { None } else { Some(Self(value)) }
}
}
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct WindowRegistry {
handles: Arc<[WindowHandle]>,
active_window: Option<WindowHandle>,
truncated: bool,
}
impl WindowRegistry {
pub(crate) fn new(
handles: impl Into<Arc<[WindowHandle]>>,
active_window: Option<WindowHandle>,
truncated: bool,
) -> Self {
Self {
handles: handles.into(),
active_window,
truncated,
}
}
pub fn windows(&self) -> &[WindowHandle] {
&self.handles
}
pub const fn active_window(&self) -> Option<WindowHandle> {
self.active_window
}
pub fn contains(&self, handle: WindowHandle) -> bool {
self.handles.binary_search(&handle).is_ok()
}
pub const fn is_truncated(&self) -> bool {
self.truncated
}
}
#[derive(Clone, Debug)]
pub struct WindowOptions {
pub title: String,
pub size: Size,
pub window_bounds: Option<WindowBounds>,
pub display_id: Option<DisplayId>,
pub minimum_size: Option<Size>,
pub maximum_size: Option<Size>,
pub represented_file: Option<PathBuf>,
pub document_edited: bool,
pub tabbing_identifier: Option<String>,
pub background: Color,
pub window_background: WindowBackgroundAppearance,
pub performance_profile: PerformanceProfile,
pub preferred_appearance: Option<WindowAppearance>,
pub title_bar_style: TitleBarStyle,
pub kind: WindowKind,
pub popover: Option<crate::PopoverOptions>,
pub focus: bool,
pub focusable: bool,
pub show: bool,
pub is_movable: bool,
pub is_resizable: bool,
pub is_minimizable: bool,
pub is_maximizable: bool,
pub is_closable: bool,
pub decorated: bool,
pub shadow: bool,
pub content_protected: bool,
pub window_level: Option<WindowLevel>,
pub skip_taskbar: bool,
pub visible_on_all_workspaces: bool,
pub opacity: f32,
pub icon: Option<Image>,
pub taskbar_progress_state: TaskbarProgressState,
pub taskbar_progress: f32,
pub taskbar_overlay_icon: Option<Image>,
pub taskbar_overlay_description: Option<String>,
pub cursor_visible: bool,
pub cursor_grab: CursorGrabMode,
pub cursor_hit_test: bool,
pub cursor_position: Option<Point>,
pub window_menus: Option<Vec<Menu>>,
pub traffic_light_position: Option<Point>,
pub line_scroll_pixels: f32,
pub key_sequence_timeout: Duration,
pub reduce_motion: bool,
#[cfg(feature = "inspector")]
pub inspector: bool,
}
impl Default for WindowOptions {
fn default() -> Self {
Self {
title: "QuickGUI".to_owned(),
size: Size::new(960.0, 640.0),
window_bounds: None,
display_id: None,
minimum_size: Some(Size::new(320.0, 240.0)),
maximum_size: None,
represented_file: None,
document_edited: false,
tabbing_identifier: None,
background: Color::rgb8(18, 18, 20),
window_background: WindowBackgroundAppearance::Opaque,
performance_profile: PerformanceProfile::Balanced,
preferred_appearance: None,
title_bar_style: TitleBarStyle::Default,
kind: WindowKind::Normal,
popover: None,
focus: true,
focusable: true,
show: true,
is_movable: true,
is_resizable: true,
is_minimizable: true,
is_maximizable: true,
is_closable: true,
decorated: true,
shadow: true,
content_protected: false,
window_level: None,
skip_taskbar: false,
visible_on_all_workspaces: false,
opacity: 1.0,
icon: None,
taskbar_progress_state: TaskbarProgressState::None,
taskbar_progress: 0.0,
taskbar_overlay_icon: None,
taskbar_overlay_description: None,
cursor_visible: true,
cursor_grab: CursorGrabMode::None,
cursor_hit_test: true,
cursor_position: None,
window_menus: None,
traffic_light_position: None,
line_scroll_pixels: 40.0,
key_sequence_timeout: Duration::from_secs(1),
reduce_motion: false,
#[cfg(feature = "inspector")]
inspector: false,
}
}
}
impl WindowOptions {
pub fn new(title: impl Into<String>) -> Self {
Self {
title: title.into(),
..Self::default()
}
}
pub fn title(mut self, title: impl Into<String>) -> Self {
self.title = title.into();
self
}
pub fn size(mut self, width: f32, height: f32) -> Self {
self.size = Size::new(width, height);
if let Some(bounds) = &mut self.window_bounds {
let state = *bounds;
let rect = state.bounds();
let rect = Rect::new(rect.x, rect.y, width, height);
*bounds = match state {
WindowBounds::Windowed(_) => WindowBounds::Windowed(rect),
WindowBounds::Maximized(_) => WindowBounds::Maximized(rect),
WindowBounds::Fullscreen(_) => WindowBounds::Fullscreen(rect),
};
}
self
}
pub fn window_bounds(mut self, bounds: WindowBounds) -> Self {
let rect = bounds.bounds();
self.size = Size::new(rect.width, rect.height);
self.window_bounds = Some(bounds);
self
}
pub fn position(mut self, x: f32, y: f32) -> Self {
let bounds = self
.window_bounds
.unwrap_or_else(|| WindowBounds::Windowed(Rect::from_size(self.size)));
let rect = bounds.bounds();
let rect = Rect::new(x, y, rect.width, rect.height);
self.window_bounds = Some(match bounds {
WindowBounds::Windowed(_) => WindowBounds::Windowed(rect),
WindowBounds::Maximized(_) => WindowBounds::Maximized(rect),
WindowBounds::Fullscreen(_) => WindowBounds::Fullscreen(rect),
});
self
}
pub fn display(mut self, display: DisplayId) -> Self {
self.display_id = Some(display);
self
}
pub fn without_display(mut self) -> Self {
self.display_id = None;
self
}
pub fn maximized(mut self, maximized: bool) -> Self {
let rect = self
.window_bounds
.map(WindowBounds::bounds)
.unwrap_or_else(|| Rect::from_size(self.size));
self.window_bounds = Some(if maximized {
WindowBounds::Maximized(rect)
} else {
WindowBounds::Windowed(rect)
});
self
}
pub fn fullscreen(mut self, fullscreen: bool) -> Self {
let rect = self
.window_bounds
.map(WindowBounds::bounds)
.unwrap_or_else(|| Rect::from_size(self.size));
self.window_bounds = Some(if fullscreen {
WindowBounds::Fullscreen(rect)
} else {
WindowBounds::Windowed(rect)
});
self
}
pub fn minimum_size(mut self, width: f32, height: f32) -> Self {
self.minimum_size = Some(Size::new(width, height));
self
}
pub fn without_minimum_size(mut self) -> Self {
self.minimum_size = None;
self
}
pub fn maximum_size(mut self, width: f32, height: f32) -> Self {
self.maximum_size = Some(Size::new(width, height));
self
}
pub fn without_maximum_size(mut self) -> Self {
self.maximum_size = None;
self
}
pub fn represented_file(mut self, path: impl Into<PathBuf>) -> Self {
self.represented_file = Some(path.into());
self
}
pub fn document_path(self, path: impl Into<PathBuf>) -> Self {
self.represented_file(path)
}
pub fn without_represented_file(mut self) -> Self {
self.represented_file = None;
self
}
pub fn window_menus(mut self, menus: impl IntoIterator<Item = Menu>) -> Self {
self.window_menus = Some(menus.into_iter().collect());
self
}
pub fn use_application_menus(mut self) -> Self {
self.window_menus = None;
self
}
pub fn document_edited(mut self, edited: bool) -> Self {
self.document_edited = edited;
self
}
pub fn tabbing_identifier(mut self, identifier: impl Into<String>) -> Self {
self.tabbing_identifier = Some(identifier.into());
self
}
pub fn without_tabbing_identifier(mut self) -> Self {
self.tabbing_identifier = None;
self
}
pub fn background(mut self, background: Color) -> Self {
self.background = background;
self
}
pub fn window_background(mut self, appearance: WindowBackgroundAppearance) -> Self {
self.window_background = appearance;
self
}
pub fn performance_profile(mut self, profile: PerformanceProfile) -> Self {
self.performance_profile = profile;
self
}
pub fn window_appearance(mut self, appearance: WindowAppearance) -> Self {
self.preferred_appearance = Some(appearance);
self
}
pub fn follow_system_appearance(mut self) -> Self {
self.preferred_appearance = None;
self
}
pub fn title_bar_style(mut self, style: TitleBarStyle) -> Self {
self.title_bar_style = style;
self.decorated = style != TitleBarStyle::Hidden;
self
}
pub fn window_kind(mut self, kind: WindowKind) -> Self {
self.kind = kind;
if kind != WindowKind::SystemPopover {
self.popover = None;
}
self
}
pub fn system_popover(mut self, popover: crate::PopoverOptions) -> Self {
self.kind = WindowKind::SystemPopover;
self.focus = popover.grab;
self.focusable = popover.accepts_key_focus;
self.popover = Some(popover);
self.minimum_size = None;
self.maximum_size = None;
self.title_bar_style = TitleBarStyle::Hidden;
self.decorated = false;
self.traffic_light_position = None;
self.is_movable = false;
self.is_resizable = false;
self.is_minimizable = false;
self.is_maximizable = false;
self.is_closable = false;
self
}
pub fn focus(mut self, focus: bool) -> Self {
self.focus = focus;
self
}
pub fn focusable(mut self, focusable: bool) -> Self {
self.focusable = focusable;
if !focusable {
self.focus = false;
}
self
}
pub fn show(mut self, show: bool) -> Self {
self.show = show;
self
}
pub fn movable(mut self, movable: bool) -> Self {
self.is_movable = movable;
self
}
pub fn resizable(mut self, resizable: bool) -> Self {
self.is_resizable = resizable;
self
}
pub fn minimizable(mut self, minimizable: bool) -> Self {
self.is_minimizable = minimizable;
self
}
pub fn maximizable(mut self, maximizable: bool) -> Self {
self.is_maximizable = maximizable;
self
}
pub fn closable(mut self, closable: bool) -> Self {
self.is_closable = closable;
self
}
pub fn decorations(mut self, decorated: bool) -> Self {
self.decorated = decorated;
if !decorated {
self.title_bar_style = TitleBarStyle::Hidden;
self.traffic_light_position = None;
} else if self.title_bar_style == TitleBarStyle::Hidden {
self.title_bar_style = TitleBarStyle::Default;
}
self
}
pub fn shadow(mut self, shadow: bool) -> Self {
self.shadow = shadow;
self
}
pub fn content_protected(mut self, protected: bool) -> Self {
self.content_protected = protected;
self
}
pub fn window_level(mut self, level: WindowLevel) -> Self {
self.window_level = Some(level);
self
}
pub fn automatic_window_level(mut self) -> Self {
self.window_level = None;
self
}
pub fn skip_taskbar(mut self, skip: bool) -> Self {
self.skip_taskbar = skip;
self
}
pub fn visible_on_all_workspaces(mut self, visible: bool) -> Self {
self.visible_on_all_workspaces = visible;
self
}
pub fn opacity(mut self, opacity: f32) -> Self {
self.opacity = opacity;
self
}
pub fn icon(mut self, icon: Image) -> Self {
self.icon = Some(icon);
self
}
pub fn without_icon(mut self) -> Self {
self.icon = None;
self
}
pub fn taskbar_progress(mut self, state: TaskbarProgressState, progress: f32) -> Self {
self.taskbar_progress_state = state;
self.taskbar_progress = progress;
self
}
pub fn taskbar_overlay_icon(mut self, icon: Image, description: impl Into<String>) -> Self {
self.taskbar_overlay_icon = Some(icon);
self.taskbar_overlay_description = Some(description.into());
self
}
pub fn without_taskbar_overlay_icon(mut self) -> Self {
self.taskbar_overlay_icon = None;
self.taskbar_overlay_description = None;
self
}
pub fn cursor_visible(mut self, visible: bool) -> Self {
self.cursor_visible = visible;
self
}
pub fn cursor_grab(mut self, mode: CursorGrabMode) -> Self {
self.cursor_grab = mode;
self
}
pub fn cursor_hit_test(mut self, hit_test: bool) -> Self {
self.cursor_hit_test = hit_test;
self
}
pub fn cursor_position(mut self, position: Point) -> Self {
self.cursor_position = Some(position);
self
}
pub fn without_cursor_position(mut self) -> Self {
self.cursor_position = None;
self
}
pub fn always_on_top(self, always_on_top: bool) -> Self {
self.window_level(if always_on_top {
WindowLevel::AlwaysOnTop
} else {
WindowLevel::Normal
})
}
pub fn always_on_bottom(self, always_on_bottom: bool) -> Self {
self.window_level(if always_on_bottom {
WindowLevel::AlwaysOnBottom
} else {
WindowLevel::Normal
})
}
pub fn traffic_light_position(mut self, x: f32, y: f32) -> Self {
self.traffic_light_position = Some(Point::new(x, y));
self
}
pub fn without_traffic_light_position(mut self) -> Self {
self.traffic_light_position = None;
self
}
pub fn reduce_motion(mut self, reduce_motion: bool) -> Self {
self.reduce_motion = reduce_motion;
self
}
#[cfg(feature = "inspector")]
pub fn inspector(mut self, inspector: bool) -> Self {
self.inspector = inspector;
self
}
}
pub(crate) fn validate_window_bounds(bounds: WindowBounds) -> Result<(), WindowCommandError> {
let bounds = bounds.bounds();
let valid = bounds.x.is_finite()
&& bounds.y.is_finite()
&& bounds.width.is_finite()
&& bounds.height.is_finite()
&& bounds.x.abs() <= MAX_WINDOW_LOGICAL_COORDINATE
&& bounds.y.abs() <= MAX_WINDOW_LOGICAL_COORDINATE
&& bounds.width > 0.0
&& bounds.height > 0.0
&& bounds.width <= MAX_WINDOW_LOGICAL_DIMENSION
&& bounds.height <= MAX_WINDOW_LOGICAL_DIMENSION;
if valid {
Ok(())
} else {
Err(WindowCommandError::InvalidBounds)
}
}
pub(crate) fn validate_window_size(size: Size) -> Result<(), WindowCommandError> {
validate_window_bounds(WindowBounds::Windowed(Rect::from_size(size)))
}
pub(crate) fn validate_window_position(position: Point) -> Result<(), WindowCommandError> {
validate_window_bounds(WindowBounds::Windowed(Rect::new(
position.x, position.y, 1.0, 1.0,
)))
}
pub(crate) fn validate_window_title(title: &str) -> Result<(), WindowCommandError> {
if title.len() <= MAX_WINDOW_TITLE_BYTES {
Ok(())
} else {
Err(WindowCommandError::TitleTooLong)
}
}
pub(crate) fn validate_window_document_path(path: &Path) -> Result<(), WindowCommandError> {
let bytes = path.as_os_str().as_encoded_bytes();
if !bytes.is_empty() && bytes.len() <= MAX_WINDOW_DOCUMENT_PATH_BYTES && !bytes.contains(&0) {
Ok(())
} else {
Err(WindowCommandError::InvalidDocumentPath)
}
}
pub(crate) fn validate_window_tabbing_identifier(
identifier: &str,
) -> Result<(), WindowCommandError> {
if !identifier.is_empty()
&& identifier.len() <= MAX_WINDOW_TABBING_IDENTIFIER_BYTES
&& !identifier.as_bytes().contains(&0)
{
Ok(())
} else {
Err(WindowCommandError::InvalidTabbingIdentifier)
}
}
pub(super) fn validate_window_options(options: &WindowOptions) -> Result<(), WindowCommandError> {
validate_window_title(&options.title)?;
validate_window_size(options.size)?;
if let Some(bounds) = options.window_bounds {
validate_window_bounds(bounds)?;
}
if let Some(minimum) = options.minimum_size {
validate_window_size(minimum)?;
}
if let Some(maximum) = options.maximum_size {
validate_window_size(maximum)?;
}
validate_window_opacity(options.opacity)?;
validate_taskbar_progress(options.taskbar_progress)?;
validate_taskbar_overlay_description(options.taskbar_overlay_description.as_deref())?;
if let Some(position) = options.cursor_position {
validate_window_position(position)?;
}
if let (Some(minimum), Some(maximum)) = (options.minimum_size, options.maximum_size)
&& (minimum.width > maximum.width || minimum.height > maximum.height)
{
return Err(WindowCommandError::InvalidSizeConstraints);
}
if let Some(path) = options.represented_file.as_deref() {
validate_window_document_path(path)?;
}
if let Some(identifier) = options.tabbing_identifier.as_deref() {
validate_window_tabbing_identifier(identifier)?;
}
if let Some(menus) = options.window_menus.as_deref() {
validate_menus(menus).map_err(|_| WindowCommandError::InvalidMenus)?;
}
if options.title_bar_style == TitleBarStyle::Hidden && options.traffic_light_position.is_some()
{
return Err(WindowCommandError::HiddenTitleBarTrafficLights);
}
match (options.kind, options.popover.as_ref()) {
(WindowKind::SystemPopover, Some(popover))
if popover.is_valid(MAX_WINDOW_LOGICAL_COORDINATE, MAX_WINDOW_LOGICAL_DIMENSION)
&& !options.decorated
&& options.title_bar_style == TitleBarStyle::Hidden
&& options.minimum_size.is_none()
&& options.maximum_size.is_none()
&& !options.is_movable
&& !options.is_resizable
&& !options.is_minimizable
&& !options.is_maximizable
&& !options.is_closable
&& !matches!(
options.window_bounds,
Some(WindowBounds::Maximized(_) | WindowBounds::Fullscreen(_))
) => {}
(WindowKind::SystemPopover, _) | (_, Some(_)) => {
return Err(WindowCommandError::InvalidPopoverConfiguration);
}
(_, None) => {}
}
Ok(())
}
pub(crate) fn validate_window_opacity(opacity: f32) -> Result<(), WindowCommandError> {
if opacity.is_finite() && (0.0..=1.0).contains(&opacity) {
Ok(())
} else {
Err(WindowCommandError::InvalidOpacity)
}
}
pub(crate) fn validate_taskbar_progress(progress: f32) -> Result<(), WindowCommandError> {
if progress.is_finite() && (0.0..=1.0).contains(&progress) {
Ok(())
} else {
Err(WindowCommandError::InvalidTaskbarProgress)
}
}
pub(crate) fn validate_taskbar_overlay_description(
description: Option<&str>,
) -> Result<(), WindowCommandError> {
if description.is_some_and(|description| {
description.len() > crate::MAX_TASKBAR_OVERLAY_DESCRIPTION_BYTES
|| description.as_bytes().contains(&0)
}) {
Err(WindowCommandError::InvalidTaskbarOverlayDescription)
} else {
Ok(())
}
}
pub trait View: Sized + 'static {
fn event(&mut self, _event: &Event, _cx: &mut EventContext) {}
fn render(&mut self, cx: &mut ViewContext<'_, Self>) -> impl IntoElement;
}
pub(super) trait AnyView {
fn event(&mut self, event: &Event, cx: &mut EventContext);
#[allow(clippy::too_many_arguments)]
fn render(
&mut self,
size: Size,
scale_factor: f32,
metrics: FrameMetrics,
focused: Option<ElementId>,
focused_path: Vec<ElementId>,
listeners: &mut ListenerRegistry,
window: WindowHandle,
window_state: WindowState,
displays: &Displays,
keyboard_layout: &KeyboardLayout,
assets: &Assets,
app_info: Option<&AppInfo>,
app_paths: Option<&AppPaths>,
system_info: &SystemInfo,
system_preferences: &SystemPreferences,
background_tasks: Option<&BackgroundTaskPoolHandle>,
foreground_tasks: &ForegroundTaskSpawner,
globals: &GlobalStore,
event_proxy: Option<&EventLoopProxy<RuntimeEvent>>,
) -> (Element, bool, Option<Instant>);
fn as_any_mut(&mut self) -> &mut dyn Any;
#[cfg(any(test, feature = "test-support"))]
fn as_any(&self) -> &dyn Any;
}
pub(super) struct ViewAdapter<V>(V);
impl<V: View> AnyView for ViewAdapter<V> {
fn event(&mut self, event: &Event, cx: &mut EventContext) {
self.0.event(event, cx);
}
fn render(
&mut self,
size: Size,
scale_factor: f32,
metrics: FrameMetrics,
focused: Option<ElementId>,
focused_path: Vec<ElementId>,
listeners: &mut ListenerRegistry,
window: WindowHandle,
window_state: WindowState,
displays: &Displays,
keyboard_layout: &KeyboardLayout,
assets: &Assets,
app_info: Option<&AppInfo>,
app_paths: Option<&AppPaths>,
system_info: &SystemInfo,
system_preferences: &SystemPreferences,
background_tasks: Option<&BackgroundTaskPoolHandle>,
foreground_tasks: &ForegroundTaskSpawner,
globals: &GlobalStore,
event_proxy: Option<&EventLoopProxy<RuntimeEvent>>,
) -> (Element, bool, Option<Instant>) {
let mut cx = ViewContext::<V> {
size,
scale_factor,
metrics,
focused,
focused_path,
request_animation_frame: false,
repaint_deadline: None,
listeners,
window,
window_state,
displays,
keyboard_layout,
assets,
app_info,
app_paths,
system_info,
system_preferences,
background_tasks,
foreground_tasks,
globals,
event_proxy,
marker: PhantomData,
};
cx.listeners.clear();
let root = self.0.render(&mut cx).into_element();
(root, cx.request_animation_frame, cx.repaint_deadline)
}
fn as_any_mut(&mut self) -> &mut dyn Any {
&mut self.0
}
#[cfg(any(test, feature = "test-support"))]
fn as_any(&self) -> &dyn Any {
&self.0
}
}
pub(crate) struct WindowRequest {
pub(crate) handle: WindowHandle,
pub(super) view: Box<dyn AnyView>,
pub(crate) options: WindowOptions,
pub(crate) parent: Option<WindowHandle>,
pub(crate) popover_anchor_element: Option<ElementId>,
}
impl WindowRequest {
pub(crate) fn new<V: View>(view: V, options: WindowOptions) -> Self {
Self::with_parent(view, options, None)
}
pub(crate) fn with_parent<V: View>(
view: V,
options: WindowOptions,
parent: Option<WindowHandle>,
) -> Self {
Self::with_handle(view, options, parent, WindowHandle::next())
}
pub(crate) fn with_handle<V: View>(
view: V,
options: WindowOptions,
parent: Option<WindowHandle>,
handle: WindowHandle,
) -> Self {
Self {
handle,
view: Box::new(ViewAdapter(view)),
options,
parent,
popover_anchor_element: None,
}
}
}
impl fmt::Debug for WindowRequest {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("WindowRequest")
.field("handle", &self.handle)
.field("parent", &self.parent)
.field("popover_anchor_element", &self.popover_anchor_element)
.field("options", &self.options)
.finish_non_exhaustive()
}
}
#[derive(Debug)]
pub(crate) enum WindowCommand {
SetTitle(WindowHandle, String),
SetRepresentedFile(WindowHandle, Option<PathBuf>),
SetDocumentEdited(WindowHandle, bool),
ShowCharacterPalette(WindowHandle),
SetTabbingIdentifier(WindowHandle, Option<String>),
SelectNextTab(WindowHandle),
SelectPreviousTab(WindowHandle),
SelectTab(WindowHandle, usize),
MergeAllWindows(WindowHandle),
MoveTabToNewWindow(WindowHandle),
ToggleTabBar(WindowHandle),
ToggleTabOverview(WindowHandle),
SetBounds(WindowHandle, WindowBounds),
Move(WindowHandle, Point),
Resize(WindowHandle, Size),
Minimize(WindowHandle),
Restore(WindowHandle),
Zoom(WindowHandle),
ToggleFullscreen(WindowHandle),
SetFullscreen(WindowHandle, bool),
SetVisible(WindowHandle, bool),
SetMovable(WindowHandle, bool),
SetResizable(WindowHandle, bool),
SetMinimumSize(WindowHandle, Option<Size>),
SetMaximumSize(WindowHandle, Option<Size>),
SetMinimizable(WindowHandle, bool),
SetMaximizable(WindowHandle, bool),
SetClosable(WindowHandle, bool),
SetDecorated(WindowHandle, bool),
SetShadow(WindowHandle, bool),
SetContentProtected(WindowHandle, bool),
SetWindowLevel(WindowHandle, Option<WindowLevel>),
SetFocusable(WindowHandle, bool),
SetSkipTaskbar(WindowHandle, bool),
SetVisibleOnAllWorkspaces(WindowHandle, bool),
SetOpacity(WindowHandle, f32),
SetIcon(WindowHandle, Option<Image>),
SetTaskbarProgress(WindowHandle, TaskbarProgressState, f32),
SetTaskbarOverlayIcon(WindowHandle, Option<Image>, Option<String>),
SetCursorVisible(WindowHandle, bool),
SetCursorGrab(WindowHandle, CursorGrabMode),
SetCursorHitTest(WindowHandle, bool),
SetCursorPosition(WindowHandle, Point),
SetAppearance(WindowHandle, Option<WindowAppearance>),
SetBackgroundAppearance(WindowHandle, WindowBackgroundAppearance),
#[cfg(feature = "inspector")]
SetInspector(WindowHandle, bool),
#[cfg(feature = "inspector")]
ToggleInspector(WindowHandle),
RequestAttention(WindowHandle),
}
impl WindowCommand {
pub(crate) fn handle(&self) -> WindowHandle {
match self {
Self::SetTitle(handle, _)
| Self::SetRepresentedFile(handle, _)
| Self::SetDocumentEdited(handle, _)
| Self::ShowCharacterPalette(handle)
| Self::SetTabbingIdentifier(handle, _)
| Self::SelectNextTab(handle)
| Self::SelectPreviousTab(handle)
| Self::SelectTab(handle, _)
| Self::MergeAllWindows(handle)
| Self::MoveTabToNewWindow(handle)
| Self::ToggleTabBar(handle)
| Self::ToggleTabOverview(handle)
| Self::SetBounds(handle, _)
| Self::Move(handle, _)
| Self::Resize(handle, _)
| Self::Minimize(handle)
| Self::Restore(handle)
| Self::Zoom(handle)
| Self::ToggleFullscreen(handle)
| Self::SetFullscreen(handle, _)
| Self::SetVisible(handle, _)
| Self::SetMovable(handle, _)
| Self::SetResizable(handle, _)
| Self::SetMinimumSize(handle, _)
| Self::SetMaximumSize(handle, _)
| Self::SetMinimizable(handle, _)
| Self::SetMaximizable(handle, _)
| Self::SetClosable(handle, _)
| Self::SetDecorated(handle, _)
| Self::SetShadow(handle, _)
| Self::SetContentProtected(handle, _)
| Self::SetWindowLevel(handle, _)
| Self::SetFocusable(handle, _)
| Self::SetSkipTaskbar(handle, _)
| Self::SetVisibleOnAllWorkspaces(handle, _)
| Self::SetOpacity(handle, _)
| Self::SetIcon(handle, _)
| Self::SetTaskbarProgress(handle, _, _)
| Self::SetTaskbarOverlayIcon(handle, _, _)
| Self::SetCursorVisible(handle, _)
| Self::SetCursorGrab(handle, _)
| Self::SetCursorHitTest(handle, _)
| Self::SetCursorPosition(handle, _)
| Self::SetAppearance(handle, _)
| Self::SetBackgroundAppearance(handle, _)
| Self::RequestAttention(handle) => *handle,
#[cfg(feature = "inspector")]
Self::SetInspector(handle, _) | Self::ToggleInspector(handle) => *handle,
}
}
}