use std::collections::BTreeMap;
use std::path::PathBuf;
use iced_core::{Point as IcedPoint, Size as IcedSize, theme, window};
use icedwright_locator::{AnyRole, IntoLocator, IntoTestId, RoleKind, RoleType, TextMatch, role};
use icedwright_types::units::{Logical, Physical, ScaleFactor};
use icedwright_types::{Point, Size};
use crate::error::{HarnessError, Result};
use crate::fakes::WindowRequest;
use crate::harness::{Handle, Harness, TestProgram};
#[derive(Debug, Clone)]
pub struct WindowInfo {
pub id: window::Id,
pub title: String,
pub logical_size: Logical<Size>,
pub physical_size: Physical<Size<u32>>,
pub scale_factor: ScaleFactor,
pub position: Option<Logical<Point>>,
pub mode: window::Mode,
pub maximized: bool,
pub minimized: bool,
pub focused: bool,
pub theme_mode: theme::Mode,
pub settings: window::Settings,
pub attention: Option<window::UserAttention>,
}
impl WindowInfo {
pub(crate) fn layout_size(&self) -> IcedSize {
let physical = self.physical_size.get();
let factor = self.scale_factor.get();
IcedSize::new(
physical.width as f32 / factor,
physical.height as f32 / factor,
)
}
}
#[derive(Debug, Clone, PartialEq)]
pub(crate) enum Effect {
Event(window::Id, window::Event),
Broadcast(window::Id, window::Event),
Exit,
}
#[derive(Debug, Clone)]
pub(crate) struct WindowState {
pub(crate) info: WindowInfo,
pub(crate) requests: Vec<WindowRequest>,
pub(crate) ordinal: u64,
pub(crate) system_scale: ScaleFactor,
}
#[derive(Debug, Clone)]
pub(crate) struct WindowSet {
pub(crate) windows: BTreeMap<window::Id, WindowState>,
pub(crate) focused: Option<window::Id>,
daemon: bool,
next_ordinal: u64,
pub(crate) monitor: Logical<Size>,
}
fn clamp(size: Size, settings: &window::Settings) -> Size {
let min = settings.min_size.unwrap_or(IcedSize::ZERO);
let max = settings
.max_size
.unwrap_or(IcedSize::new(f32::INFINITY, f32::INFINITY));
Size::new(
size.width.clamp(min.width, max.width.max(min.width)),
size.height.clamp(min.height, max.height.max(min.height)),
)
}
impl WindowSet {
pub(crate) fn new(daemon: bool, monitor: Logical<Size>) -> Self {
Self {
windows: BTreeMap::new(),
focused: None,
daemon,
next_ordinal: 0,
monitor,
}
}
pub(crate) fn get(&self, id: window::Id) -> Result<&WindowState, HarnessError> {
self.windows.get(&id).ok_or(HarnessError::NoSuchWindow(id))
}
fn get_mut(&mut self, id: window::Id) -> Result<&mut WindowState, HarnessError> {
self.windows
.get_mut(&id)
.ok_or(HarnessError::NoSuchWindow(id))
}
pub(crate) fn open(
&mut self,
id: window::Id,
settings: window::Settings,
size: Logical<Size>,
system_scale: ScaleFactor,
) -> Vec<Effect> {
self.next_ordinal += 1;
let size = Logical(clamp(size.0, &settings));
let position = match settings.position {
window::Position::Specific(point) => Some(Logical(Point::from(point))),
_ => None,
};
let info = WindowInfo {
id,
title: String::new(),
logical_size: size,
physical_size: size.to_physical_pixels(system_scale),
scale_factor: system_scale,
position,
mode: if settings.visible {
window::Mode::Windowed
} else {
window::Mode::Hidden
},
maximized: settings.maximized,
minimized: false,
focused: false,
theme_mode: theme::Mode::None,
settings,
attention: None,
};
self.windows.insert(
id,
WindowState {
info,
requests: Vec::new(),
ordinal: self.next_ordinal,
system_scale,
},
);
let mut effects = vec![Effect::Event(
id,
window::Event::Opened {
position: position.map(|p| IcedPoint::from(p.0)),
size: IcedSize::from(size.0),
},
)];
effects.extend(self.focus(id));
effects
}
pub(crate) fn focus(&mut self, id: window::Id) -> Vec<Effect> {
if self.focused == Some(id) || !self.windows.contains_key(&id) {
return Vec::new();
}
let mut effects = Vec::new();
if let Some(old) = self.focused.take()
&& let Some(state) = self.windows.get_mut(&old)
{
state.info.focused = false;
effects.push(Effect::Event(old, window::Event::Unfocused));
}
if let Some(state) = self.windows.get_mut(&id) {
state.info.focused = true;
}
self.focused = Some(id);
effects.push(Effect::Event(id, window::Event::Focused));
effects
}
pub(crate) fn close(&mut self, id: window::Id) -> Result<Vec<Effect>, HarnessError> {
let state = self
.windows
.remove(&id)
.ok_or(HarnessError::NoSuchWindow(id))?;
let mut effects = vec![Effect::Broadcast(id, window::Event::Closed)];
if state.info.focused {
self.focused = None;
let latest = self
.windows
.values()
.max_by_key(|state| state.ordinal)
.map(|state| state.info.id);
if let Some(next) = latest {
effects.extend(self.focus(next));
}
}
if self.windows.is_empty() && !self.daemon {
effects.push(Effect::Exit);
}
Ok(effects)
}
pub(crate) fn resize(
&mut self,
id: window::Id,
size: Logical<Size>,
force: bool,
) -> Result<Vec<Effect>, HarnessError> {
let state = self.get_mut(id)?;
if !force && !state.info.settings.resizable {
return Err(HarnessError::NotResizable(id));
}
let size = if force {
size.0
} else {
clamp(size.0, &state.info.settings)
};
state.info.logical_size = Logical(size);
state.info.physical_size = Logical(size).to_physical_pixels(state.system_scale);
Ok(vec![Effect::Event(
id,
window::Event::Resized(IcedSize::from(size)),
)])
}
pub(crate) fn rescale(
&mut self,
id: window::Id,
factor: ScaleFactor,
program_scale: f32,
) -> Result<Vec<Effect>, HarnessError> {
let state = self.get_mut(id)?;
state.system_scale = factor;
state.info.physical_size = state.info.logical_size.to_physical_pixels(factor);
state.info.scale_factor = ScaleFactor::new(factor.get() * program_scale).unwrap_or(factor);
Ok(vec![Effect::Event(
id,
window::Event::Rescaled(state.info.scale_factor.get()),
)])
}
pub(crate) fn apply(&mut self, action: iced_runtime::window::Action) -> Option<Vec<Effect>> {
use iced_runtime::window::Action;
let effects = match action {
Action::Close(id) => self.close(id).unwrap_or_default(),
Action::GetOldest(sender) => {
let oldest = self
.windows
.values()
.min_by_key(|s| s.ordinal)
.map(|s| s.info.id);
let _ = sender.send(oldest);
Vec::new()
}
Action::GetLatest(sender) => {
let latest = self
.windows
.values()
.max_by_key(|s| s.ordinal)
.map(|s| s.info.id);
let _ = sender.send(latest);
Vec::new()
}
Action::Drag(id) => self.request(id, WindowRequest::Drag),
Action::DragResize(id, direction) => {
self.request(id, WindowRequest::DragResize(direction))
}
Action::ShowSystemMenu(id) => self.request(id, WindowRequest::ShowSystemMenu),
Action::SetIcon(id, _) => self.request(id, WindowRequest::SetIcon),
Action::EnableMousePassthrough(id) => {
self.request(id, WindowRequest::MousePassthrough(true))
}
Action::DisableMousePassthrough(id) => {
self.request(id, WindowRequest::MousePassthrough(false))
}
Action::SetAllowAutomaticTabbing(on) => {
if let Some(id) = self.focused {
let _ = self.request(id, WindowRequest::AutomaticTabbing(on));
}
Vec::new()
}
Action::RequestUserAttention(id, attention) => {
if let Some(state) = self.windows.get_mut(&id) {
state.info.attention = attention;
}
self.request(id, WindowRequest::RequestUserAttention(attention))
}
Action::Resize(id, size) => self
.resize(id, Logical(Size::from(size)), true)
.unwrap_or_default(),
Action::GetSize(id, sender) => {
if let Ok(state) = self.get(id) {
let _ = sender.send(IcedSize::from(state.info.logical_size.0));
}
Vec::new()
}
Action::GetMaximized(id, sender) => {
if let Ok(state) = self.get(id) {
let _ = sender.send(state.info.maximized);
}
Vec::new()
}
Action::Maximize(id, on) => self.update(id, |info| info.maximized = on),
Action::ToggleMaximize(id) => self.update(id, |info| info.maximized = !info.maximized),
Action::GetMinimized(id, sender) => {
if let Ok(state) = self.get(id) {
let _ = sender.send(Some(state.info.minimized));
}
Vec::new()
}
Action::Minimize(id, on) => self.update(id, |info| info.minimized = on),
Action::GetPosition(id, sender) => {
if let Ok(state) = self.get(id) {
let _ = sender.send(state.info.position.map(|p| IcedPoint::from(p.0)));
}
Vec::new()
}
Action::GetScaleFactor(id, sender) => {
if let Ok(state) = self.get(id) {
let _ = sender.send(state.info.scale_factor.get());
}
Vec::new()
}
Action::Move(id, point) => {
let _ = self.update(id, |info| info.position = Some(Logical(Point::from(point))));
vec![Effect::Event(id, window::Event::Moved(point))]
}
Action::SetMode(id, mode) => self.update(id, |info| info.mode = mode),
Action::GetMode(id, sender) => {
if let Ok(state) = self.get(id) {
let _ = sender.send(state.info.mode);
}
Vec::new()
}
Action::ToggleDecorations(id) => self.update(id, |info| {
info.settings.decorations = !info.settings.decorations;
}),
Action::GainFocus(id) => self.focus(id),
Action::SetLevel(id, level) => self.update(id, |info| info.settings.level = level),
Action::GetRawId(id, sender) => {
if let Ok(state) = self.get(id) {
let _ = sender.send(state.ordinal);
}
Vec::new()
}
Action::SetMinSize(id, size) => self.update(id, |info| info.settings.min_size = size),
Action::SetMaxSize(id, size) => self.update(id, |info| info.settings.max_size = size),
Action::SetResizable(id, on) => self.update(id, |info| info.settings.resizable = on),
Action::SetResizeIncrements(_, _) => Vec::new(),
Action::GetMonitorSize(_, sender) => {
let _ = sender.send(Some(IcedSize::from(self.monitor.0)));
Vec::new()
}
Action::Open(..)
| Action::Run(..)
| Action::Screenshot(..)
| Action::RedrawAll
| Action::RelayoutAll => return None,
};
Some(effects)
}
fn request(&mut self, id: window::Id, request: WindowRequest) -> Vec<Effect> {
if let Some(state) = self.windows.get_mut(&id) {
state.requests.push(request);
}
Vec::new()
}
fn update(&mut self, id: window::Id, change: impl FnOnce(&mut WindowInfo)) -> Vec<Effect> {
if let Some(state) = self.windows.get_mut(&id) {
change(&mut state.info);
}
Vec::new()
}
}
#[must_use]
pub struct WindowRef<'h, P: TestProgram> {
harness: &'h mut Harness<P>,
id: window::Id,
}
impl<P: TestProgram> std::fmt::Debug for WindowRef<'_, P> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("WindowRef")
.field("id", &self.id)
.finish_non_exhaustive()
}
}
impl<'h, P: TestProgram> WindowRef<'h, P> {
pub(crate) fn new(harness: &'h mut Harness<P>, id: window::Id) -> Self {
Self { harness, id }
}
#[must_use]
pub fn id(&self) -> window::Id {
self.id
}
pub fn info(&self) -> Result<&WindowInfo> {
Ok(&self.harness.window_set().get(self.id)?.info)
}
pub fn requests(&self) -> Result<&[WindowRequest]> {
Ok(&self.harness.window_set().get(self.id)?.requests)
}
pub fn resize(self, size: impl Into<Logical<Size>>) -> Result {
self.harness.resize_window(self.id, size.into(), false)
}
pub fn force_size(self, size: impl Into<Logical<Size>>) -> Result {
self.harness.resize_window(self.id, size.into(), true)
}
pub fn set_scale_factor(self, factor: ScaleFactor) -> Result {
self.harness.rescale_window(self.id, factor)
}
pub fn move_to(self, position: Logical<Point>) -> Result {
let point = IcedPoint::from(position.0);
self.harness
.window_action(iced_runtime::window::Action::Move(self.id, point))
}
pub fn focus(self) -> Result {
self.harness
.window_action(iced_runtime::window::Action::GainFocus(self.id))
}
pub fn request_close(self) -> Result {
self.harness.request_close(self.id)
}
pub fn hover_files(self, paths: impl IntoIterator<Item = impl Into<PathBuf>>) -> Result {
let events = paths
.into_iter()
.map(|path| window::Event::FileHovered(path.into()))
.collect();
self.harness.window_events(self.id, events)
}
pub fn leave_files(self) -> Result {
self.harness
.window_events(self.id, vec![window::Event::FilesHoveredLeft])
}
pub fn drop_files(self, paths: impl IntoIterator<Item = impl Into<PathBuf>>) -> Result {
self.harness.check_file_drops()?;
let events = paths
.into_iter()
.map(|path| window::Event::FileDropped(path.into()))
.collect();
self.harness.window_events(self.id, events)
}
pub fn page(self) -> Handle<'h, P, role::Window> {
Handle::new(self.harness, icedwright_locator::page(), Some(self.id))
}
pub fn locate<R: RoleKind>(self, locator: impl IntoLocator<R>) -> Handle<'h, P, R> {
Handle::new(self.harness, locator.into_locator(), Some(self.id))
}
pub fn get_by_role<R: RoleType>(self, role: R) -> Handle<'h, P, R> {
let id = self.id;
Handle::new(
self.harness,
icedwright_locator::get_by_role(role),
Some(id),
)
}
pub fn get_by_text(self, text: impl Into<TextMatch>) -> Handle<'h, P, AnyRole> {
let id = self.id;
Handle::new(
self.harness,
icedwright_locator::get_by_text(text),
Some(id),
)
}
pub fn get_by_test_id<'a>(self, test_id: impl IntoTestId<'a>) -> Handle<'h, P, AnyRole> {
let id = self.id;
Handle::new(
self.harness,
icedwright_locator::get_by_test_id(test_id),
Some(id),
)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn settings() -> window::Settings {
window::Settings {
min_size: Some(IcedSize::new(200.0, 100.0)),
max_size: Some(IcedSize::new(800.0, 600.0)),
..window::Settings::default()
}
}
fn set(daemon: bool) -> WindowSet {
WindowSet::new(daemon, Logical(Size::new(1920.0, 1080.0)))
}
fn open(set: &mut WindowSet) -> window::Id {
let id = window::Id::unique();
let _ = set.open(
id,
settings(),
Logical(Size::new(400.0, 300.0)),
ScaleFactor::ONE,
);
id
}
#[test]
fn open_emits_opened_then_focus_and_close_emits_closed() {
let mut windows = set(false);
let first = open(&mut windows);
let second = window::Id::unique();
let effects = windows.open(
second,
settings(),
Logical(Size::new(400.0, 300.0)),
ScaleFactor::ONE,
);
assert!(
matches!(effects[0], Effect::Event(id, window::Event::Opened { .. }) if id == second)
);
assert_eq!(effects[1], Effect::Event(first, window::Event::Unfocused));
assert_eq!(effects[2], Effect::Event(second, window::Event::Focused));
let closed = windows.close(second).unwrap();
assert_eq!(closed[0], Effect::Broadcast(second, window::Event::Closed));
assert_eq!(closed[1], Effect::Event(first, window::Event::Focused));
assert_eq!(windows.focused, Some(first));
}
#[test]
fn resize_clamps_and_refuses_a_fixed_window() {
let mut windows = set(false);
let id = open(&mut windows);
let effects = windows
.resize(id, Logical(Size::new(1000.0, 50.0)), false)
.unwrap();
assert_eq!(
effects,
vec![Effect::Event(
id,
window::Event::Resized(IcedSize::new(800.0, 100.0))
)]
);
windows
.windows
.get_mut(&id)
.unwrap()
.info
.settings
.resizable = false;
assert!(matches!(
windows.resize(id, Logical(Size::new(300.0, 300.0)), false),
Err(HarnessError::NotResizable(_))
));
assert!(
windows
.resize(id, Logical(Size::new(10.0, 10.0)), true)
.is_ok()
);
assert_eq!(
windows.get(id).unwrap().info.logical_size,
Logical(Size::new(10.0, 10.0))
);
}
#[test]
fn closing_the_last_window_exits_an_application_not_a_daemon() {
let mut application = set(false);
let id = open(&mut application);
assert!(application.close(id).unwrap().contains(&Effect::Exit));
let mut daemon = set(true);
let id = open(&mut daemon);
assert!(!daemon.close(id).unwrap().contains(&Effect::Exit));
}
#[test]
fn focus_moves_on_gain_focus() {
let mut windows = set(false);
let first = open(&mut windows);
let second = open(&mut windows);
let effects = windows
.apply(iced_runtime::window::Action::GainFocus(first))
.unwrap();
assert_eq!(
effects,
vec![
Effect::Event(second, window::Event::Unfocused),
Effect::Event(first, window::Event::Focused)
]
);
assert!(windows.get(first).unwrap().info.focused);
assert!(!windows.get(second).unwrap().info.focused);
}
#[test]
fn windows_are_visited_in_id_order() {
let mut windows = set(false);
let ids: Vec<window::Id> = (0..3).map(|_| open(&mut windows)).collect();
let visited: Vec<window::Id> = windows.windows.keys().copied().collect();
let mut sorted = ids.clone();
sorted.sort();
assert_eq!(visited, sorted);
}
#[test]
fn a_drag_is_recorded_for_its_window() {
let mut windows = set(false);
let id = open(&mut windows);
let _ = windows.apply(iced_runtime::window::Action::Drag(id));
assert_eq!(windows.get(id).unwrap().requests, vec![WindowRequest::Drag]);
}
#[test]
fn rescale_doubles_the_physical_size() {
let mut windows = set(false);
let id = open(&mut windows);
let _ = windows.rescale(id, ScaleFactor::TWO, 1.0).unwrap();
let info = &windows.get(id).unwrap().info;
assert_eq!(info.physical_size.get(), Size::new(800, 600));
assert_eq!(info.layout_size(), IcedSize::new(400.0, 300.0));
}
}