summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--Cargo.toml2
-rw-r--r--core/src/event.rs2
-rw-r--r--core/src/widget/tree.rs2
-rw-r--r--core/src/window/id.rs28
-rw-r--r--core/src/window/position.rs0
-rw-r--r--core/src/window/settings.rs (renamed from src/window/settings.rs)0
-rw-r--r--examples/events/src/main.rs8
-rw-r--r--examples/integration/src/main.rs1
-rw-r--r--examples/integration_opengl/src/main.rs0
-rw-r--r--examples/multi_window/Cargo.toml9
-rw-r--r--examples/multi_window/src/main.rs170
-rw-r--r--examples/multi_window_panes/Cargo.toml12
-rw-r--r--examples/multi_window_panes/src/main.rs639
-rw-r--r--glutin/src/application.rs0
-rw-r--r--native/src/subscription.rs0
-rw-r--r--native/src/window.rs0
-rw-r--r--runtime/src/command/action.rs8
-rw-r--r--runtime/src/window/action.rs11
-rw-r--r--src/lib.rs3
-rw-r--r--src/multi_window.rs4
-rw-r--r--src/multi_window/application.rs256
-rw-r--r--src/window/position.rs32
-rw-r--r--widget/src/text_input.rs2
-rw-r--r--winit/Cargo.toml1
-rw-r--r--winit/src/application.rs13
-rw-r--r--winit/src/conversion.rs46
-rw-r--r--winit/src/icon.rs (renamed from src/window/icon.rs)0
-rw-r--r--winit/src/lib.rs12
-rw-r--r--winit/src/multi_window.rs1185
-rw-r--r--winit/src/multi_window/state.rs218
-rw-r--r--winit/src/position.rs22
-rw-r--r--winit/src/profiler.rs (renamed from winit/src/application/profiler.rs)0
-rw-r--r--winit/src/window.rs0
33 files changed, 2596 insertions, 90 deletions
diff --git a/Cargo.toml b/Cargo.toml
index 070cd0ce..4a82c923 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -41,6 +41,8 @@ system = ["iced_winit/system"]
web-colors = ["iced_renderer/web-colors"]
# Enables the advanced module
advanced = []
+# Enables experimental multi-window support for iced_winit + wgpu.
+multi-window = ["iced_winit/multi-window"]
[badges]
maintenance = { status = "actively-developed" }
diff --git a/core/src/event.rs b/core/src/event.rs
index 953cd73f..870b3074 100644
--- a/core/src/event.rs
+++ b/core/src/event.rs
@@ -19,7 +19,7 @@ pub enum Event {
Mouse(mouse::Event),
/// A window event
- Window(window::Event),
+ Window(window::Id, window::Event),
/// A touch event
Touch(touch::Event),
diff --git a/core/src/widget/tree.rs b/core/src/widget/tree.rs
index 0af40c33..da269632 100644
--- a/core/src/widget/tree.rs
+++ b/core/src/widget/tree.rs
@@ -67,7 +67,7 @@ impl Tree {
}
}
- /// Reconciliates the children of the tree with the provided list of widgets.
+ /// Reconciles the children of the tree with the provided list of widgets.
pub fn diff_children<'a, Message, Renderer>(
&mut self,
new_children: &[impl Borrow<dyn Widget<Message, Renderer> + 'a>],
diff --git a/core/src/window/id.rs b/core/src/window/id.rs
new file mode 100644
index 00000000..0a11b1aa
--- /dev/null
+++ b/core/src/window/id.rs
@@ -0,0 +1,28 @@
+use std::collections::hash_map::DefaultHasher;
+use std::fmt::{Display, Formatter};
+use std::hash::{Hash, Hasher};
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
+/// The ID of the window.
+///
+/// Internally Iced uses `window::Id::MAIN` as the first window spawned.
+pub struct Id(u64);
+
+impl Id {
+ /// The reserved window ID for the primary window in an Iced application.
+ pub const MAIN: Self = Id(0);
+
+ /// Creates a new unique window ID.
+ pub fn new(id: impl Hash) -> Id {
+ let mut hasher = DefaultHasher::new();
+ id.hash(&mut hasher);
+
+ Id(hasher.finish())
+ }
+}
+
+impl Display for Id {
+ fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
+ write!(f, "Id({})", self.0)
+ }
+}
diff --git a/core/src/window/position.rs b/core/src/window/position.rs
new file mode 100644
index 00000000..e69de29b
--- /dev/null
+++ b/core/src/window/position.rs
diff --git a/src/window/settings.rs b/core/src/window/settings.rs
index 458b9232..458b9232 100644
--- a/src/window/settings.rs
+++ b/core/src/window/settings.rs
diff --git a/examples/events/src/main.rs b/examples/events/src/main.rs
index 7f3a5e1d..70659f52 100644
--- a/examples/events/src/main.rs
+++ b/examples/events/src/main.rs
@@ -26,7 +26,7 @@ struct Events {
enum Message {
EventOccurred(Event),
Toggled(bool),
- Exit,
+ Exit(window::Id),
}
impl Application for Events {
@@ -55,8 +55,8 @@ impl Application for Events {
Command::none()
}
Message::EventOccurred(event) => {
- if let Event::Window(window::Event::CloseRequested) = event {
- window::close()
+ if let Event::Window(id, window::Event::CloseRequested) = event {
+ window::close(id)
} else {
Command::none()
}
@@ -66,7 +66,7 @@ impl Application for Events {
Command::none()
}
- Message::Exit => window::close(),
+ Message::Exit(id) => window::close(id),
}
}
diff --git a/examples/integration/src/main.rs b/examples/integration/src/main.rs
index 342d4c69..a560959a 100644
--- a/examples/integration/src/main.rs
+++ b/examples/integration/src/main.rs
@@ -182,6 +182,7 @@ pub fn main() -> Result<(), Box<dyn std::error::Error>> {
// Map window event to iced event
if let Some(event) = iced_winit::conversion::window_event(
+ window::Id::MAIN,
&event,
window.scale_factor(),
modifiers,
diff --git a/examples/integration_opengl/src/main.rs b/examples/integration_opengl/src/main.rs
new file mode 100644
index 00000000..e69de29b
--- /dev/null
+++ b/examples/integration_opengl/src/main.rs
diff --git a/examples/multi_window/Cargo.toml b/examples/multi_window/Cargo.toml
new file mode 100644
index 00000000..0cb5d546
--- /dev/null
+++ b/examples/multi_window/Cargo.toml
@@ -0,0 +1,9 @@
+[package]
+name = "multi_window"
+version = "0.1.0"
+authors = ["Bingus <shankern@protonmail.com>"]
+edition = "2021"
+publish = false
+
+[dependencies]
+iced = { path = "../..", features = ["debug", "multi-window"] } \ No newline at end of file
diff --git a/examples/multi_window/src/main.rs b/examples/multi_window/src/main.rs
new file mode 100644
index 00000000..5699ece0
--- /dev/null
+++ b/examples/multi_window/src/main.rs
@@ -0,0 +1,170 @@
+use iced::multi_window::{self, Application};
+use iced::widget::{button, column, container, scrollable, text, text_input};
+use iced::{
+ executor, window, Alignment, Command, Element, Length, Settings, Theme,
+};
+use std::collections::HashMap;
+
+fn main() -> iced::Result {
+ Example::run(Settings::default())
+}
+
+#[derive(Default)]
+struct Example {
+ windows_count: usize,
+ windows: HashMap<window::Id, Window>,
+}
+
+struct Window {
+ id: window::Id,
+ title: String,
+ scale_input: String,
+ current_scale: f64,
+}
+
+#[derive(Debug, Clone)]
+enum Message {
+ ScaleInputChanged(window::Id, String),
+ ScaleChanged(window::Id, String),
+ TitleChanged(window::Id, String),
+ CloseWindow(window::Id),
+ NewWindow,
+}
+
+impl multi_window::Application for Example {
+ type Executor = executor::Default;
+ type Message = Message;
+ type Theme = Theme;
+ type Flags = ();
+
+ fn new(_flags: ()) -> (Self, Command<Message>) {
+ (
+ Example {
+ windows_count: 0,
+ windows: HashMap::from([(
+ window::Id::MAIN,
+ Window::new(window::Id::MAIN),
+ )]),
+ },
+ Command::none(),
+ )
+ }
+
+ fn title(&self, window: window::Id) -> String {
+ self.windows
+ .get(&window)
+ .map(|window| window.title.clone())
+ .unwrap_or("Example".to_string())
+ }
+
+ fn update(&mut self, message: Message) -> Command<Message> {
+ match message {
+ Message::ScaleInputChanged(id, scale) => {
+ let window =
+ self.windows.get_mut(&id).expect("Window not found!");
+ window.scale_input = scale;
+ }
+ Message::ScaleChanged(id, scale) => {
+ let window =
+ self.windows.get_mut(&id).expect("Window not found!");
+
+ window.current_scale = scale
+ .parse::<f64>()
+ .unwrap_or(window.current_scale)
+ .clamp(0.5, 5.0);
+ }
+ Message::TitleChanged(id, title) => {
+ let window =
+ self.windows.get_mut(&id).expect("Window not found.");
+
+ window.title = title;
+ }
+ Message::CloseWindow(id) => {
+ return window::close(id);
+ }
+ Message::NewWindow => {
+ self.windows_count += 1;
+ let id = window::Id::new(self.windows_count);
+ self.windows.insert(id, Window::new(id));
+
+ return window::spawn(id, window::Settings::default());
+ }
+ }
+
+ Command::none()
+ }
+
+ fn view(&self, window: window::Id) -> Element<Message> {
+ let window = self
+ .windows
+ .get(&window)
+ .map(|window| window.view())
+ .unwrap();
+
+ container(window)
+ .width(Length::Fill)
+ .height(Length::Fill)
+ .center_x()
+ .center_y()
+ .into()
+ }
+
+ fn scale_factor(&self, window: window::Id) -> f64 {
+ self.windows
+ .get(&window)
+ .map(|window| window.current_scale)
+ .unwrap_or(1.0)
+ }
+
+ fn close_requested(&self, window: window::Id) -> Self::Message {
+ Message::CloseWindow(window)
+ }
+}
+
+impl Window {
+ fn new(id: window::Id) -> Self {
+ Self {
+ id,
+ title: "Window".to_string(),
+ scale_input: "1.0".to_string(),
+ current_scale: 1.0,
+ }
+ }
+
+ fn view(&self) -> Element<Message> {
+ window_view(self.id, &self.scale_input, &self.title)
+ }
+}
+
+fn window_view<'a>(
+ id: window::Id,
+ scale_input: &'a str,
+ title: &'a str,
+) -> Element<'a, Message> {
+ let scale_input = column![
+ text("Window scale factor:"),
+ text_input("Window Scale", scale_input, move |msg| {
+ Message::ScaleInputChanged(id, msg)
+ })
+ .on_submit(Message::ScaleChanged(id, scale_input.to_string()))
+ ];
+
+ let title_input = column![
+ text("Window title:"),
+ text_input("Window Title", title, move |msg| {
+ Message::TitleChanged(id, msg)
+ })
+ ];
+
+ let new_window_button =
+ button(text("New Window")).on_press(Message::NewWindow);
+
+ let content = scrollable(
+ column![scale_input, title_input, new_window_button]
+ .spacing(50)
+ .width(Length::Fill)
+ .align_items(Alignment::Center),
+ );
+
+ container(content).width(200).center_x().into()
+}
diff --git a/examples/multi_window_panes/Cargo.toml b/examples/multi_window_panes/Cargo.toml
new file mode 100644
index 00000000..1b3f3ec6
--- /dev/null
+++ b/examples/multi_window_panes/Cargo.toml
@@ -0,0 +1,12 @@
+[package]
+name = "multi_window_panes"
+version = "0.1.0"
+authors = ["Richard Custodio <richardsoncusto@gmail.com>"]
+edition = "2021"
+publish = false
+
+[dependencies]
+iced = { path = "../..", features = ["debug", "multi-window", "tokio"] }
+env_logger = "0.10.0"
+iced_native = { path = "../../native" }
+iced_lazy = { path = "../../lazy" }
diff --git a/examples/multi_window_panes/src/main.rs b/examples/multi_window_panes/src/main.rs
new file mode 100644
index 00000000..b1d0a3bc
--- /dev/null
+++ b/examples/multi_window_panes/src/main.rs
@@ -0,0 +1,639 @@
+use iced::alignment::{self, Alignment};
+use iced::keyboard;
+use iced::multi_window::Application;
+use iced::theme::{self, Theme};
+use iced::widget::pane_grid::{self, PaneGrid};
+use iced::widget::{
+ button, column, container, pick_list, row, scrollable, text, text_input,
+};
+use iced::window;
+use iced::{executor, time};
+use iced::{Color, Command, Element, Length, Settings, Size, Subscription};
+use iced_lazy::responsive;
+use iced_native::{event, subscription, Event};
+
+use iced_native::widget::scrollable::{Properties, RelativeOffset};
+use iced_native::window::Id;
+use std::collections::HashMap;
+use std::time::{Duration, Instant};
+
+pub fn main() -> iced::Result {
+ env_logger::init();
+
+ Example::run(Settings::default())
+}
+
+struct Example {
+ windows: HashMap<window::Id, Window>,
+ panes_created: usize,
+ count: usize,
+ _focused: window::Id,
+}
+
+#[derive(Debug)]
+struct Window {
+ title: String,
+ scale: f64,
+ theme: Theme,
+ panes: pane_grid::State<Pane>,
+ focus: Option<pane_grid::Pane>,
+}
+
+#[derive(Debug, Clone)]
+enum Message {
+ Window(window::Id, WindowMessage),
+ CountIncremented(Instant),
+}
+
+#[derive(Debug, Clone)]
+enum WindowMessage {
+ Split(pane_grid::Axis, pane_grid::Pane),
+ SplitFocused(pane_grid::Axis),
+ FocusAdjacent(pane_grid::Direction),
+ Clicked(pane_grid::Pane),
+ Dragged(pane_grid::DragEvent),
+ PopOut(pane_grid::Pane),
+ Resized(pane_grid::ResizeEvent),
+ TitleChanged(String),
+ ToggleMoving(pane_grid::Pane),
+ TogglePin(pane_grid::Pane),
+ Close(pane_grid::Pane),
+ CloseFocused,
+ SelectedWindow(pane_grid::Pane, SelectableWindow),
+ CloseWindow,
+ SnapToggle,
+}
+
+impl Application for Example {
+ type Executor = executor::Default;
+ type Message = Message;
+ type Theme = Theme;
+ type Flags = ();
+
+ fn new(_flags: ()) -> (Self, Command<Message>) {
+ let (panes, _) =
+ pane_grid::State::new(Pane::new(0, pane_grid::Axis::Horizontal));
+ let window = Window {
+ panes,
+ focus: None,
+ title: String::from("Default window"),
+ scale: 1.0,
+ theme: Theme::default(),
+ };
+
+ (
+ Example {
+ windows: HashMap::from([(window::Id::MAIN, window)]),
+ panes_created: 1,
+ count: 0,
+ _focused: window::Id::MAIN,
+ },
+ Command::none(),
+ )
+ }
+
+ fn title(&self, window: window::Id) -> String {
+ self.windows
+ .get(&window)
+ .map(|w| w.title.clone())
+ .unwrap_or(String::from("New Window"))
+ }
+
+ fn update(&mut self, message: Message) -> Command<Message> {
+ match message {
+ Message::Window(id, message) => match message {
+ WindowMessage::SnapToggle => {
+ let window = self.windows.get_mut(&id).unwrap();
+
+ if let Some(focused) = &window.focus {
+ let pane = window.panes.get_mut(focused).unwrap();
+
+ let cmd = scrollable::snap_to(
+ pane.scrollable_id.clone(),
+ if pane.snapped {
+ RelativeOffset::START
+ } else {
+ RelativeOffset::END
+ },
+ );
+
+ pane.snapped = !pane.snapped;
+ return cmd;
+ }
+ }
+ WindowMessage::Split(axis, pane) => {
+ let window = self.windows.get_mut(&id).unwrap();
+ let result = window.panes.split(
+ axis,
+ &pane,
+ Pane::new(self.panes_created, axis),
+ );
+
+ if let Some((pane, _)) = result {
+ window.focus = Some(pane);
+ }
+
+ self.panes_created += 1;
+ }
+ WindowMessage::SplitFocused(axis) => {
+ let window = self.windows.get_mut(&id).unwrap();
+ if let Some(pane) = window.focus {
+ let result = window.panes.split(
+ axis,
+ &pane,
+ Pane::new(self.panes_created, axis),
+ );
+
+ if let Some((pane, _)) = result {
+ window.focus = Some(pane);
+ }
+
+ self.panes_created += 1;
+ }
+ }
+ WindowMessage::FocusAdjacent(direction) => {
+ let window = self.windows.get_mut(&id).unwrap();
+ if let Some(pane) = window.focus {
+ if let Some(adjacent) =
+ window.panes.adjacent(&pane, direction)
+ {
+ window.focus = Some(adjacent);
+ }
+ }
+ }
+ WindowMessage::Clicked(pane) => {
+ let window = self.windows.get_mut(&id).unwrap();
+ window.focus = Some(pane);
+ }
+ WindowMessage::CloseWindow => {
+ let _ = self.windows.remove(&id);
+ return window::close(id);
+ }
+ WindowMessage::Resized(pane_grid::ResizeEvent {
+ split,
+ ratio,
+ }) => {
+ let window = self.windows.get_mut(&id).unwrap();
+ window.panes.resize(&split, ratio);
+ }
+ WindowMessage::SelectedWindow(pane, selected) => {
+ let window = self.windows.get_mut(&id).unwrap();
+ let (mut pane, _) = window.panes.close(&pane).unwrap();
+ pane.is_moving = false;
+
+ if let Some(window) = self.windows.get_mut(&selected.0) {
+ let (&first_pane, _) =
+ window.panes.iter().next().unwrap();
+ let result =
+ window.panes.split(pane.axis, &first_pane, pane);
+
+ if let Some((pane, _)) = result {
+ window.focus = Some(pane);
+ }
+ }
+ }
+ WindowMessage::ToggleMoving(pane) => {
+ let window = self.windows.get_mut(&id).unwrap();
+ if let Some(pane) = window.panes.get_mut(&pane) {
+ pane.is_moving = !pane.is_moving;
+ }
+ }
+ WindowMessage::TitleChanged(title) => {
+ let window = self.windows.get_mut(&id).unwrap();
+ window.title = title;
+ }
+ WindowMessage::PopOut(pane) => {
+ let window = self.windows.get_mut(&id).unwrap();
+ if let Some((popped, sibling)) = window.panes.close(&pane) {
+ window.focus = Some(sibling);
+
+ let (panes, _) = pane_grid::State::new(popped);
+ let window = Window {
+ panes,
+ focus: None,
+ title: format!(
+ "New window ({})",
+ self.windows.len()
+ ),
+ scale: 1.0 + (self.windows.len() as f64 / 10.0),
+ theme: if self.windows.len() % 2 == 0 {
+ Theme::Light
+ } else {
+ Theme::Dark
+ },
+ };
+
+ let window_id = window::Id::new(self.windows.len());
+ self.windows.insert(window_id, window);
+ return window::spawn(window_id, Default::default());
+ }
+ }
+ WindowMessage::Dragged(pane_grid::DragEvent::Dropped {
+ pane,
+ target,
+ }) => {
+ let window = self.windows.get_mut(&id).unwrap();
+ window.panes.swap(&pane, &target);
+ }
+ WindowMessage::Dragged(_) => {}
+ WindowMessage::TogglePin(pane) => {
+ let window = self.windows.get_mut(&id).unwrap();
+ if let Some(Pane { is_pinned, .. }) =
+ window.panes.get_mut(&pane)
+ {
+ *is_pinned = !*is_pinned;
+ }
+ }
+ WindowMessage::Close(pane) => {
+ let window = self.windows.get_mut(&id).unwrap();
+ if let Some((_, sibling)) = window.panes.close(&pane) {
+ window.focus = Some(sibling);
+ }
+ }
+ WindowMessage::CloseFocused => {
+ let window = self.windows.get_mut(&id).unwrap();
+ if let Some(pane) = window.focus {
+ if let Some(Pane { is_pinned, .. }) =
+ window.panes.get(&pane)
+ {
+ if !is_pinned {
+ if let Some((_, sibling)) =
+ window.panes.close(&pane)
+ {
+ window.focus = Some(sibling);
+ }
+ }
+ }
+ }
+ }
+ },
+ Message::CountIncremented(_) => {
+ self.count += 1;
+ }
+ }
+
+ Command::none()
+ }
+
+ fn subscription(&self) -> Subscription<Message> {
+ Subscription::batch(vec![
+ subscription::events_with(|event, status| {
+ if let event::Status::Captured = status {
+ return None;
+ }
+
+ match event {
+ Event::Keyboard(keyboard::Event::KeyPressed {
+ modifiers,
+ key_code,
+ }) if modifiers.command() => {
+ handle_hotkey(key_code).map(|message| {
+ Message::Window(window::Id::new(0usize), message)
+ })
+ } // TODO(derezzedex)
+ _ => None,
+ }
+ }),
+ time::every(Duration::from_secs(1)).map(Message::CountIncremented),
+ ])
+ }
+
+ fn view(&self, window: window::Id) -> Element<Message> {
+ let window_id = window;
+
+ if let Some(window) = self.windows.get(&window) {
+ let focus = window.focus;
+ let total_panes = window.panes.len();
+
+ let window_controls = row![
+ text_input(
+ "Window title",
+ &window.title,
+ WindowMessage::TitleChanged,
+ ),
+ button(text("Close"))
+ .on_press(WindowMessage::CloseWindow)
+ .style(theme::Button::Destructive),
+ ]
+ .spacing(5)
+ .align_items(Alignment::Center);
+
+ let pane_grid = PaneGrid::new(&window.panes, |id, pane, _| {
+ let is_focused = focus == Some(id);
+
+ let pin_button = button(
+ text(if pane.is_pinned { "Unpin" } else { "Pin" }).size(14),
+ )
+ .on_press(WindowMessage::TogglePin(id))
+ .padding(3);
+
+ let title = row![
+ pin_button,
+ "Pane",
+ text(pane.id.to_string()).style(if is_focused {
+ PANE_ID_COLOR_FOCUSED
+ } else {
+ PANE_ID_COLOR_UNFOCUSED
+ }),
+ ]
+ .spacing(5);
+
+ let title_bar = pane_grid::TitleBar::new(title)
+ .controls(view_controls(
+ id,
+ total_panes,
+ pane.is_pinned,
+ pane.is_moving,
+ &window.title,
+ window_id,
+ &self.windows,
+ ))
+ .padding(10)
+ .style(if is_focused {
+ style::title_bar_focused
+ } else {
+ style::title_bar_active
+ });
+
+ pane_grid::Content::new(responsive(move |size| {
+ view_content(
+ id,
+ pane.scrollable_id.clone(),
+ self.count,
+ total_panes,
+ pane.is_pinned,
+ size,
+ )
+ }))
+ .title_bar(title_bar)
+ .style(if is_focused {
+ style::pane_focused
+ } else {
+ style::pane_active
+ })
+ })
+ .width(Length::Fill)
+ .height(Length::Fill)
+ .spacing(10)
+ .on_click(WindowMessage::Clicked)
+ .on_drag(WindowMessage::Dragged)
+ .on_resize(10, WindowMessage::Resized);
+
+ let content: Element<_> = column![window_controls, pane_grid]
+ .width(Length::Fill)
+ .height(Length::Fill)
+ .padding(10)
+ .into();
+
+ return content
+ .map(move |message| Message::Window(window_id, message));
+ }
+
+ container(text("This shouldn't be possible!").size(20))
+ .center_x()
+ .center_y()
+ .into()
+ }
+
+ fn close_requested(&self, window: window::Id) -> Self::Message {
+ Message::Window(window, WindowMessage::CloseWindow)
+ }
+
+ fn scale_factor(&self, window: Id) -> f64 {
+ self.windows.get(&window).map(|w| w.scale).unwrap_or(1.0)
+ }
+
+ fn theme(&self, window: Id) -> Theme {
+ self.windows.get(&window).expect("Window not found!").theme.clone()
+ }
+}
+
+const PANE_ID_COLOR_UNFOCUSED: Color = Color::from_rgb(
+ 0xFF as f32 / 255.0,
+ 0xC7 as f32 / 255.0,
+ 0xC7 as f32 / 255.0,
+);
+const PANE_ID_COLOR_FOCUSED: Color = Color::from_rgb(
+ 0xFF as f32 / 255.0,
+ 0x47 as f32 / 255.0,
+ 0x47 as f32 / 255.0,
+);
+
+fn handle_hotkey(key_code: keyboard::KeyCode) -> Option<WindowMessage> {
+ use keyboard::KeyCode;
+ use pane_grid::{Axis, Direction};
+
+ let direction = match key_code {
+ KeyCode::Up => Some(Direction::Up),
+ KeyCode::Down => Some(Direction::Down),
+ KeyCode::Left => Some(Direction::Left),
+ KeyCode::Right => Some(Direction::Right),
+ _ => None,
+ };
+
+ match key_code {
+ KeyCode::V => Some(WindowMessage::SplitFocused(Axis::Vertical)),
+ KeyCode::H => Some(WindowMessage::SplitFocused(Axis::Horizontal)),
+ KeyCode::W => Some(WindowMessage::CloseFocused),
+ _ => direction.map(WindowMessage::FocusAdjacent),
+ }
+}
+
+#[derive(Debug, Clone)]
+struct SelectableWindow(window::Id, String);
+
+impl PartialEq for SelectableWindow {
+ fn eq(&self, other: &Self) -> bool {
+ self.0 == other.0
+ }
+}
+
+impl Eq for SelectableWindow {}
+
+impl std::fmt::Display for SelectableWindow {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ self.1.fmt(f)
+ }
+}
+
+#[derive(Debug)]
+struct Pane {
+ id: usize,
+ pub scrollable_id: scrollable::Id,
+ pub axis: pane_grid::Axis,
+ pub is_pinned: bool,
+ pub is_moving: bool,
+ pub snapped: bool,
+}
+
+impl Pane {
+ fn new(id: usize, axis: pane_grid::Axis) -> Self {
+ Self {
+ id,
+ scrollable_id: scrollable::Id::unique(),
+ axis,
+ is_pinned: false,
+ is_moving: false,
+ snapped: false,
+ }
+ }
+}
+
+fn view_content<'a>(
+ pane: pane_grid::Pane,
+ scrollable_id: scrollable::Id,
+ count: usize,
+ total_panes: usize,
+ is_pinned: bool,
+ size: Size,
+) -> Element<'a, WindowMessage> {
+ let button = |label, message| {
+ button(
+ text(label)
+ .width(Length::Fill)
+ .horizontal_alignment(alignment::Horizontal::Center)
+ .size(16),
+ )
+ .width(Length::Fill)
+ .padding(8)
+ .on_press(message)
+ };
+
+ let mut controls = column![
+ button(
+ "Split horizontally",
+ WindowMessage::Split(pane_grid::Axis::Horizontal, pane),
+ ),
+ button(
+ "Split vertically",
+ WindowMessage::Split(pane_grid::Axis::Vertical, pane),
+ ),
+ button("Snap", WindowMessage::SnapToggle,)
+ ]
+ .spacing(5)
+ .max_width(150);
+
+ if total_panes > 1 && !is_pinned {
+ controls = controls.push(
+ button("Close", WindowMessage::Close(pane))
+ .style(theme::Button::Destructive),
+ );
+ }
+
+ let content = column![
+ text(format!("{}x{}", size.width, size.height)).size(24),
+ controls,
+ text(format!("{count}")).size(48),
+ ]
+ .width(Length::Fill)
+ .height(800)
+ .spacing(10)
+ .align_items(Alignment::Center);
+
+ container(
+ scrollable(content)
+ .height(Length::Fill)
+ .vertical_scroll(Properties::new())
+ .id(scrollable_id),
+ )
+ .width(Length::Fill)
+ .height(Length::Fill)
+ .padding(5)
+ .center_y()
+ .into()
+}
+
+fn view_controls<'a>(
+ pane: pane_grid::Pane,
+ total_panes: usize,
+ is_pinned: bool,
+ is_moving: bool,
+ window_title: &'a str,
+ window_id: window::Id,
+ windows: &HashMap<window::Id, Window>,
+) -> Element<'a, WindowMessage> {
+ let window_selector = {
+ let options: Vec<_> = windows
+ .iter()
+ .map(|(id, window)| SelectableWindow(*id, window.title.clone()))
+ .collect();
+ pick_list(
+ options,
+ Some(SelectableWindow(window_id, window_title.to_string())),
+ move |window| WindowMessage::SelectedWindow(pane, window),
+ )
+ };
+
+ let mut move_to = button(text("Move to").size(14)).padding(3);
+
+ let mut pop_out = button(text("Pop Out").size(14)).padding(3);
+
+ let mut close = button(text("Close").size(14))
+ .style(theme::Button::Destructive)
+ .padding(3);
+
+ if total_panes > 1 && !is_pinned {
+ close = close.on_press(WindowMessage::Close(pane));
+ pop_out = pop_out.on_press(WindowMessage::PopOut(pane));
+ }
+
+ if windows.len() > 1 && total_panes > 1 && !is_pinned {
+ move_to = move_to.on_press(WindowMessage::ToggleMoving(pane));
+ }
+
+ let mut content = row![].spacing(10);
+ if is_moving {
+ content = content.push(pop_out).push(window_selector).push(close);
+ } else {
+ content = content.push(pop_out).push(move_to).push(close);
+ }
+
+ content.into()
+}
+
+mod style {
+ use iced::widget::container;
+ use iced::Theme;
+
+ pub fn title_bar_active(theme: &Theme) -> container::Appearance {
+ let palette = theme.extended_palette();
+
+ container::Appearance {
+ text_color: Some(palette.background.strong.text),
+ background: Some(palette.background.strong.color.into()),
+ ..Default::default()
+ }
+ }
+
+ pub fn title_bar_focused(theme: &Theme) -> container::Appearance {
+ let palette = theme.extended_palette();
+
+ container::Appearance {
+ text_color: Some(palette.primary.strong.text),
+ background: Some(palette.primary.strong.color.into()),
+ ..Default::default()
+ }
+ }
+
+ pub fn pane_active(theme: &Theme) -> container::Appearance {
+ let palette = theme.extended_palette();
+
+ container::Appearance {
+ background: Some(palette.background.weak.color.into()),
+ border_width: 2.0,
+ border_color: palette.background.strong.color,
+ ..Default::default()
+ }
+ }
+
+ pub fn pane_focused(theme: &Theme) -> container::Appearance {
+ let palette = theme.extended_palette();
+
+ container::Appearance {
+ background: Some(palette.background.weak.color.into()),
+ border_width: 2.0,
+ border_color: palette.primary.strong.color,
+ ..Default::default()
+ }
+ }
+}
diff --git a/glutin/src/application.rs b/glutin/src/application.rs
new file mode 100644
index 00000000..e69de29b
--- /dev/null
+++ b/glutin/src/application.rs
diff --git a/native/src/subscription.rs b/native/src/subscription.rs
new file mode 100644
index 00000000..e69de29b
--- /dev/null
+++ b/native/src/subscription.rs
diff --git a/native/src/window.rs b/native/src/window.rs
new file mode 100644
index 00000000..e69de29b
--- /dev/null
+++ b/native/src/window.rs
diff --git a/runtime/src/command/action.rs b/runtime/src/command/action.rs
index 6c74f0ef..b2594379 100644
--- a/runtime/src/command/action.rs
+++ b/runtime/src/command/action.rs
@@ -22,7 +22,7 @@ pub enum Action<T> {
Clipboard(clipboard::Action<T>),
/// Run a window action.
- Window(window::Action<T>),
+ Window(window::Id, window::Action<T>),
/// Run a system action.
System(system::Action<T>),
@@ -57,7 +57,7 @@ impl<T> Action<T> {
match self {
Self::Future(future) => Action::Future(Box::pin(future.map(f))),
Self::Clipboard(action) => Action::Clipboard(action.map(f)),
- Self::Window(window) => Action::Window(window.map(f)),
+ Self::Window(id, window) => Action::Window(id, window.map(f)),
Self::System(system) => Action::System(system.map(f)),
Self::Widget(operation) => {
Action::Widget(Box::new(widget::operation::map(operation, f)))
@@ -77,7 +77,9 @@ impl<T> fmt::Debug for Action<T> {
Self::Clipboard(action) => {
write!(f, "Action::Clipboard({action:?})")
}
- Self::Window(action) => write!(f, "Action::Window({action:?})"),
+ Self::Window(id, action) => {
+ write!(f, "Action::Window({id:?}, {action:?})")
+ }
Self::System(action) => write!(f, "Action::System({action:?})"),
Self::Widget(_action) => write!(f, "Action::Widget"),
Self::LoadFont { .. } => write!(f, "Action::LoadFont"),
diff --git a/runtime/src/window/action.rs b/runtime/src/window/action.rs
index b6964e36..cebec4ae 100644
--- a/runtime/src/window/action.rs
+++ b/runtime/src/window/action.rs
@@ -1,4 +1,4 @@
-use crate::core::window::{Icon, Level, Mode, UserAttention};
+use crate::core::window::{Icon, Level, Mode, UserAttention, Settings};
use crate::core::Size;
use crate::futures::MaybeSend;
use crate::window::Screenshot;
@@ -15,6 +15,11 @@ pub enum Action<T> {
/// There’s no guarantee that this will work unless the left mouse
/// button was pressed immediately before this function is called.
Drag,
+ /// Spawns a new window with the provided [`window::Settings`].
+ Spawn {
+ /// The settings of the [`Window`].
+ settings: Settings,
+ },
/// Resize the window.
Resize(Size<u32>),
/// Fetch the current size of the window.
@@ -104,6 +109,7 @@ impl<T> Action<T> {
match self {
Self::Close => Action::Close,
Self::Drag => Action::Drag,
+ Self::Spawn { settings } => Action::Spawn { settings },
Self::Resize(size) => Action::Resize(size),
Self::FetchSize(o) => Action::FetchSize(Box::new(move |s| f(o(s)))),
Self::Maximize(maximized) => Action::Maximize(maximized),
@@ -134,6 +140,9 @@ impl<T> fmt::Debug for Action<T> {
match self {
Self::Close => write!(f, "Action::Close"),
Self::Drag => write!(f, "Action::Drag"),
+ Self::Spawn { settings } => {
+ write!(f, "Action::Spawn {{ settings: {:?} }}", settings)
+ }
Self::Resize(size) => write!(f, "Action::Resize({size:?})"),
Self::FetchSize(_) => write!(f, "Action::FetchSize"),
Self::Maximize(maximized) => {
diff --git a/src/lib.rs b/src/lib.rs
index ce6c513d..4ddcd9d8 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -184,6 +184,9 @@ pub mod window;
#[cfg(feature = "advanced")]
pub mod advanced;
+#[cfg(feature = "multi-window")]
+pub mod multi_window;
+
pub use style::theme;
pub use crate::core::alignment;
diff --git a/src/multi_window.rs b/src/multi_window.rs
new file mode 100644
index 00000000..5b7a00b4
--- /dev/null
+++ b/src/multi_window.rs
@@ -0,0 +1,4 @@
+//! Leverage multi-window support in your application.
+mod application;
+
+pub use application::Application;
diff --git a/src/multi_window/application.rs b/src/multi_window/application.rs
new file mode 100644
index 00000000..9974128c
--- /dev/null
+++ b/src/multi_window/application.rs
@@ -0,0 +1,256 @@
+use crate::window;
+use crate::{Command, Element, Executor, Settings, Subscription};
+
+pub use iced_native::application::{Appearance, StyleSheet};
+
+/// An interactive cross-platform multi-window application.
+///
+/// This trait is the main entrypoint of Iced. Once implemented, you can run
+/// your GUI application by simply calling [`run`](#method.run).
+///
+/// An [`Application`] can execute asynchronous actions by returning a
+/// [`Command`] in some of its methods. For example, to spawn a new window, you
+/// can use the `iced_winit::window::spawn()` [`Command`].
+///
+/// When using an [`Application`] with the `debug` feature enabled, a debug view
+/// can be toggled by pressing `F12`.
+///
+/// ## A simple "Hello, world!"
+///
+/// If you just want to get started, here is a simple [`Application`] that
+/// says "Hello, world!":
+///
+/// ```no_run
+/// use iced::executor;
+/// use iced::multi_window::Application;
+/// use iced::window;
+/// use iced::{Command, Element, Settings, Theme};
+///
+/// pub fn main() -> iced::Result {
+/// Hello::run(Settings::default())
+/// }
+///
+/// struct Hello;
+///
+/// impl Application for Hello {
+/// type Executor = executor::Default;
+/// type Message = ();
+/// type Theme = Theme;
+/// type Flags = ();
+///
+/// fn new(_flags: ()) -> (Hello, Command<Self::Message>) {
+/// (Hello, Command::none())
+/// }
+///
+/// fn title(&self, window: window::Id) -> String {
+/// String::from("A cool application")
+/// }
+///
+/// fn update(&mut self, _message: Self::Message) -> Command<Self::Message> {
+/// Command::none()
+/// }
+///
+/// fn view(&self, window: window::Id) -> Element<Self::Message> {
+/// "Hello, world!".into()
+/// }
+///
+/// fn close_requested(&self, window: window::Id) -> Self::Message {
+/// ()
+/// }
+/// }
+/// ```
+pub trait Application: Sized {
+ /// The [`Executor`] that will run commands and subscriptions.
+ ///
+ /// The [default executor] can be a good starting point!
+ ///
+ /// [`Executor`]: Self::Executor
+ /// [default executor]: crate::executor::Default
+ type Executor: Executor;
+
+ /// The type of __messages__ your [`Application`] will produce.
+ type Message: std::fmt::Debug + Send;
+
+ /// The theme of your [`Application`].
+ type Theme: Default + StyleSheet;
+
+ /// The data needed to initialize your [`Application`].
+ type Flags;
+
+ /// Initializes the [`Application`] with the flags provided to
+ /// [`run`] as part of the [`Settings`].
+ ///
+ /// Here is where you should return the initial state of your app.
+ ///
+ /// Additionally, you can return a [`Command`] if you need to perform some
+ /// async action in the background on startup. This is useful if you want to
+ /// load state from a file, perform an initial HTTP request, etc.
+ ///
+ /// [`run`]: Self::run
+ fn new(flags: Self::Flags) -> (Self, Command<Self::Message>);
+
+ /// Returns the current title of the [`Application`].
+ ///
+ /// This title can be dynamic! The runtime will automatically update the
+ /// title of your application when necessary.
+ fn title(&self, window: window::Id) -> String;
+
+ /// Handles a __message__ and updates the state of the [`Application`].
+ ///
+ /// This is where you define your __update logic__. All the __messages__,
+ /// produced by either user interactions or commands, will be handled by
+ /// this method.
+ ///
+ /// Any [`Command`] returned will be executed immediately in the background.
+ fn update(&mut self, message: Self::Message) -> Command<Self::Message>;
+
+ /// Returns the current [`Theme`] of the [`Application`].
+ ///
+ /// [`Theme`]: Self::Theme
+ #[allow(unused_variables)]
+ fn theme(&self, window: window::Id) -> Self::Theme {
+ Self::Theme::default()
+ }
+
+ /// Returns the current [`Style`] of the [`Theme`].
+ ///
+ /// [`Style`]: <Self::Theme as StyleSheet>::Style
+ /// [`Theme`]: Self::Theme
+ fn style(&self) -> <Self::Theme as StyleSheet>::Style {
+ <Self::Theme as StyleSheet>::Style::default()
+ }
+
+ /// Returns the event [`Subscription`] for the current state of the
+ /// application.
+ ///
+ /// A [`Subscription`] will be kept alive as long as you keep returning it,
+ /// and the __messages__ produced will be handled by
+ /// [`update`](#tymethod.update).
+ ///
+ /// By default, this method returns an empty [`Subscription`].
+ fn subscription(&self) -> Subscription<Self::Message> {
+ Subscription::none()
+ }
+
+ /// Returns the widgets to display in the [`Application`].
+ ///
+ /// These widgets can produce __messages__ based on user interaction.
+ fn view(
+ &self,
+ window: window::Id,
+ ) -> Element<'_, Self::Message, crate::Renderer<Self::Theme>>;
+
+ /// Returns the scale factor of the `window` of the [`Application`].
+ ///
+ /// It can be used to dynamically control the size of the UI at runtime
+ /// (i.e. zooming).
+ ///
+ /// For instance, a scale factor of `2.0` will make widgets twice as big,
+ /// while a scale factor of `0.5` will shrink them to half their size.
+ ///
+ /// By default, it returns `1.0`.
+ #[allow(unused_variables)]
+ fn scale_factor(&self, window: window::Id) -> f64 {
+ 1.0
+ }
+
+ /// Returns whether the [`Application`] should be terminated.
+ ///
+ /// By default, it returns `false`.
+ fn should_exit(&self) -> bool {
+ false
+ }
+
+ /// Returns the `Self::Message` that should be processed when a `window` is requested to
+ /// be closed.
+ fn close_requested(&self, window: window::Id) -> Self::Message;
+
+ /// Runs the [`Application`].
+ ///
+ /// On native platforms, this method will take control of the current thread
+ /// until the [`Application`] exits.
+ ///
+ /// On the web platform, this method __will NOT return__ unless there is an
+ /// [`Error`] during startup.
+ ///
+ /// [`Error`]: crate::Error
+ fn run(settings: Settings<Self::Flags>) -> crate::Result
+ where
+ Self: 'static,
+ {
+ #[allow(clippy::needless_update)]
+ let renderer_settings = crate::renderer::Settings {
+ default_font: settings.default_font,
+ default_text_size: settings.default_text_size,
+ text_multithreading: settings.text_multithreading,
+ antialiasing: if settings.antialiasing {
+ Some(crate::renderer::settings::Antialiasing::MSAAx4)
+ } else {
+ None
+ },
+ ..crate::renderer::Settings::from_env()
+ };
+
+ Ok(crate::runtime::multi_window::run::<
+ Instance<Self>,
+ Self::Executor,
+ crate::renderer::window::Compositor<Self::Theme>,
+ >(settings.into(), renderer_settings)?)
+ }
+}
+
+struct Instance<A: Application>(A);
+
+impl<A> crate::runtime::multi_window::Application for Instance<A>
+where
+ A: Application,
+{
+ type Flags = A::Flags;
+ type Renderer = crate::Renderer<A::Theme>;
+ type Message = A::Message;
+
+ fn update(&mut self, message: Self::Message) -> Command<Self::Message> {
+ self.0.update(message)
+ }
+
+ fn view(
+ &self,
+ window: window::Id,
+ ) -> Element<'_, Self::Message, Self::Renderer> {
+ self.0.view(window)
+ }
+
+ fn new(flags: Self::Flags) -> (Self, Command<A::Message>) {
+ let (app, command) = A::new(flags);
+
+ (Instance(app), command)
+ }
+
+ fn title(&self, window: window::Id) -> String {
+ self.0.title(window)
+ }
+
+ fn theme(&self, window: window::Id) -> A::Theme {
+ self.0.theme(window)
+ }
+
+ fn style(&self) -> <A::Theme as StyleSheet>::Style {
+ self.0.style()
+ }
+
+ fn subscription(&self) -> Subscription<Self::Message> {
+ self.0.subscription()
+ }
+
+ fn scale_factor(&self, window: window::Id) -> f64 {
+ self.0.scale_factor(window)
+ }
+
+ fn should_exit(&self) -> bool {
+ self.0.should_exit()
+ }
+
+ fn close_requested(&self, window: window::Id) -> Self::Message {
+ self.0.close_requested(window)
+ }
+}
diff --git a/src/window/position.rs b/src/window/position.rs
deleted file mode 100644
index 6b9fac41..00000000
--- a/src/window/position.rs
+++ /dev/null
@@ -1,32 +0,0 @@
-/// The position of a window in a given screen.
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-pub enum Position {
- /// The platform-specific default position for a new window.
- Default,
- /// The window is completely centered on the screen.
- Centered,
- /// The window is positioned with specific coordinates: `(X, Y)`.
- ///
- /// When the decorations of the window are enabled, Windows 10 will add some
- /// invisible padding to the window. This padding gets included in the
- /// position. So if you have decorations enabled and want the window to be
- /// at (0, 0) you would have to set the position to
- /// `(PADDING_X, PADDING_Y)`.
- Specific(i32, i32),
-}
-
-impl Default for Position {
- fn default() -> Self {
- Self::Default
- }
-}
-
-impl From<Position> for iced_winit::Position {
- fn from(position: Position) -> Self {
- match position {
- Position::Default => Self::Default,
- Position::Centered => Self::Centered,
- Position::Specific(x, y) => Self::Specific(x, y),
- }
- }
-}
diff --git a/widget/src/text_input.rs b/widget/src/text_input.rs
index 272263f9..03bcb86a 100644
--- a/widget/src/text_input.rs
+++ b/widget/src/text_input.rs
@@ -919,7 +919,7 @@ where
state.keyboard_modifiers = modifiers;
}
- Event::Window(window::Event::RedrawRequested(now)) => {
+ Event::Window(_, window::Event::RedrawRequested(now)) => {
let state = state();
if let Some(focus) = &mut state.is_focused {
diff --git a/winit/Cargo.toml b/winit/Cargo.toml
index de7c1c62..a4c0a402 100644
--- a/winit/Cargo.toml
+++ b/winit/Cargo.toml
@@ -21,6 +21,7 @@ x11 = ["winit/x11"]
wayland = ["winit/wayland"]
wayland-dlopen = ["winit/wayland-dlopen"]
wayland-csd-adwaita = ["winit/wayland-csd-adwaita"]
+multi-window = []
[dependencies]
window_clipboard = "0.3"
diff --git a/winit/src/application.rs b/winit/src/application.rs
index d1689452..ab7b2495 100644
--- a/winit/src/application.rs
+++ b/winit/src/application.rs
@@ -1,6 +1,4 @@
//! Create interactive, native cross-platform applications.
-#[cfg(feature = "trace")]
-mod profiler;
mod state;
pub use state::State;
@@ -28,7 +26,7 @@ use futures::channel::mpsc;
use std::mem::ManuallyDrop;
#[cfg(feature = "trace")]
-pub use profiler::Profiler;
+pub use crate::Profiler;
#[cfg(feature = "trace")]
use tracing::{info_span, instrument::Instrument};
@@ -419,6 +417,7 @@ async fn run_instance<A, E, C>(
// Then, we can use the `interface_state` here to decide if a redraw
// is needed right away, or simply wait until a specific time.
let redraw_event = Event::Window(
+ window::Id::MAIN,
window::Event::RedrawRequested(Instant::now()),
);
@@ -571,6 +570,7 @@ async fn run_instance<A, E, C>(
state.update(&window, &window_event, &mut debug);
if let Some(event) = conversion::window_event(
+ window::Id::MAIN,
&window_event,
state.scale_factor(),
state.modifiers(),
@@ -741,13 +741,18 @@ pub fn run_command<A, C, E>(
clipboard.write(contents);
}
},
- command::Action::Window(action) => match action {
+ command::Action::Window(_, action) => match action {
window::Action::Close => {
*should_exit = true;
}
window::Action::Drag => {
let _res = window.drag_window();
}
+ window::Action::Spawn { .. } => {
+ log::info!(
+ "Spawning a window is only available with `multi_window::Application`s."
+ )
+ }
window::Action::Resize(size) => {
window.set_inner_size(winit::dpi::LogicalSize {
width: size.width,
diff --git a/winit/src/conversion.rs b/winit/src/conversion.rs
index dcae7074..fe0fce19 100644
--- a/winit/src/conversion.rs
+++ b/winit/src/conversion.rs
@@ -11,6 +11,7 @@ use crate::Position;
/// Converts a winit window event into an iced event.
pub fn window_event(
+ id: window::Id,
event: &winit::event::WindowEvent<'_>,
scale_factor: f64,
modifiers: winit::event::ModifiersState,
@@ -21,21 +22,27 @@ pub fn window_event(
WindowEvent::Resized(new_size) => {
let logical_size = new_size.to_logical(scale_factor);
- Some(Event::Window(window::Event::Resized {
- width: logical_size.width,
- height: logical_size.height,
- }))
+ Some(Event::Window(
+ id,
+ window::Event::Resized {
+ width: logical_size.width,
+ height: logical_size.height,
+ },
+ ))
}
WindowEvent::ScaleFactorChanged { new_inner_size, .. } => {
let logical_size = new_inner_size.to_logical(scale_factor);
- Some(Event::Window(window::Event::Resized {
- width: logical_size.width,
- height: logical_size.height,
- }))
+ Some(Event::Window(
+ id,
+ window::Event::Resized {
+ width: logical_size.width,
+ height: logical_size.height,
+ },
+ ))
}
WindowEvent::CloseRequested => {
- Some(Event::Window(window::Event::CloseRequested))
+ Some(Event::Window(id, window::Event::CloseRequested))
}
WindowEvent::CursorMoved { position, .. } => {
let position = position.to_logical::<f64>(scale_factor);
@@ -113,19 +120,22 @@ pub fn window_event(
WindowEvent::ModifiersChanged(new_modifiers) => Some(Event::Keyboard(
keyboard::Event::ModifiersChanged(self::modifiers(*new_modifiers)),
)),
- WindowEvent::Focused(focused) => Some(Event::Window(if *focused {
- window::Event::Focused
- } else {
- window::Event::Unfocused
- })),
+ WindowEvent::Focused(focused) => Some(Event::Window(
+ id,
+ if *focused {
+ window::Event::Focused
+ } else {
+ window::Event::Unfocused
+ },
+ )),
WindowEvent::HoveredFile(path) => {
- Some(Event::Window(window::Event::FileHovered(path.clone())))
+ Some(Event::Window(id, window::Event::FileHovered(path.clone())))
}
WindowEvent::DroppedFile(path) => {
- Some(Event::Window(window::Event::FileDropped(path.clone())))
+ Some(Event::Window(id, window::Event::FileDropped(path.clone())))
}
WindowEvent::HoveredFileCancelled => {
- Some(Event::Window(window::Event::FilesHoveredLeft))
+ Some(Event::Window(id, window::Event::FilesHoveredLeft))
}
WindowEvent::Touch(touch) => {
Some(Event::Touch(touch_event(*touch, scale_factor)))
@@ -134,7 +144,7 @@ pub fn window_event(
let winit::dpi::LogicalPosition { x, y } =
position.to_logical(scale_factor);
- Some(Event::Window(window::Event::Moved { x, y }))
+ Some(Event::Window(id, window::Event::Moved { x, y }))
}
_ => None,
}
diff --git a/src/window/icon.rs b/winit/src/icon.rs
index 0fe010ca..0fe010ca 100644
--- a/src/window/icon.rs
+++ b/winit/src/icon.rs
diff --git a/winit/src/lib.rs b/winit/src/lib.rs
index 4776ea2c..dc163430 100644
--- a/winit/src/lib.rs
+++ b/winit/src/lib.rs
@@ -38,6 +38,9 @@ pub use iced_runtime::futures;
pub use iced_style as style;
pub use winit;
+#[cfg(feature = "multi-window")]
+pub mod multi_window;
+
#[cfg(feature = "application")]
pub mod application;
pub mod clipboard;
@@ -48,17 +51,20 @@ pub mod settings;
pub mod system;
mod error;
-mod position;
+mod icon;
mod proxy;
+#[cfg(feature = "trace")]
+mod profiler;
#[cfg(feature = "application")]
pub use application::Application;
#[cfg(feature = "trace")]
-pub use application::Profiler;
+pub use profiler::Profiler;
pub use clipboard::Clipboard;
pub use error::Error;
-pub use position::Position;
+pub use icon::Icon;
pub use proxy::Proxy;
pub use settings::Settings;
pub use iced_graphics::Viewport;
+pub use iced_native::window::Position;
diff --git a/winit/src/multi_window.rs b/winit/src/multi_window.rs
new file mode 100644
index 00000000..9b395c1d
--- /dev/null
+++ b/winit/src/multi_window.rs
@@ -0,0 +1,1185 @@
+//! Create interactive, native cross-platform applications for WGPU.
+mod state;
+
+pub use state::State;
+
+use crate::clipboard::{self, Clipboard};
+use crate::conversion;
+use crate::mouse;
+use crate::renderer;
+use crate::settings;
+use crate::widget::operation;
+use crate::window;
+use crate::{
+ Command, Debug, Element, Error, Executor, Proxy, Renderer, Runtime,
+ Settings, Size, Subscription,
+};
+
+use iced_futures::futures::channel::mpsc;
+use iced_futures::futures::{self, FutureExt};
+use iced_graphics::compositor;
+use iced_native::user_interface::{self, UserInterface};
+
+pub use iced_native::application::{Appearance, StyleSheet};
+
+use std::collections::HashMap;
+use std::mem::ManuallyDrop;
+use std::time::Instant;
+
+#[cfg(feature = "trace")]
+pub use crate::Profiler;
+#[cfg(feature = "trace")]
+use tracing::{info_span, instrument::Instrument};
+
+/// This is a wrapper around the `Application::Message` associate type
+/// to allows the `shell` to create internal messages, while still having
+/// the current user-specified custom messages.
+#[derive(Debug)]
+pub enum Event<Message> {
+ /// An [`Application`] generated message
+ Application(Message),
+ /// A message which spawns a new window.
+ NewWindow {
+ /// The [window::Id] of the newly spawned [`Window`].
+ id: window::Id,
+ /// The [settings::Window] of the newly spawned [`Window`].
+ settings: settings::Window,
+ /// The title of the newly spawned [`Window`].
+ title: String,
+ },
+ /// Close a window.
+ CloseWindow(window::Id),
+ /// A message for when the window has finished being created.
+ WindowCreated(window::Id, winit::window::Window),
+}
+
+/// An interactive, native, cross-platform, multi-windowed application.
+///
+/// This trait is the main entrypoint of multi-window Iced. Once implemented, you can run
+/// your GUI application by simply calling [`run`]. It will run in
+/// its own window.
+///
+/// An [`Application`] can execute asynchronous actions by returning a
+/// [`Command`] in some of its methods.
+///
+/// When using an [`Application`] with the `debug` feature enabled, a debug view
+/// can be toggled by pressing `F12`.
+pub trait Application: Sized
+where
+ <Self::Renderer as crate::Renderer>::Theme: StyleSheet,
+{
+ /// The data needed to initialize your [`Application`].
+ type Flags;
+
+ /// The graphics backend to use to draw the [`Program`].
+ type Renderer: Renderer;
+
+ /// The type of __messages__ your [`Program`] will produce.
+ type Message: std::fmt::Debug + Send;
+
+ /// Handles a __message__ and updates the state of the [`Program`].
+ ///
+ /// This is where you define your __update logic__. All the __messages__,
+ /// produced by either user interactions or commands, will be handled by
+ /// this method.
+ ///
+ /// Any [`Command`] returned will be executed immediately in the
+ /// background by shells.
+ fn update(&mut self, message: Self::Message) -> Command<Self::Message>;
+
+ /// Returns the widgets to display for the `window` in the [`Program`].
+ ///
+ /// These widgets can produce __messages__ based on user interaction.
+ fn view(
+ &self,
+ window: window::Id,
+ ) -> Element<'_, Self::Message, Self::Renderer>;
+
+ /// Initializes the [`Application`] with the flags provided to
+ /// [`run`] as part of the [`Settings`].
+ ///
+ /// Here is where you should return the initial state of your app.
+ ///
+ /// Additionally, you can return a [`Command`] if you need to perform some
+ /// async action in the background on startup. This is useful if you want to
+ /// load state from a file, perform an initial HTTP request, etc.
+ fn new(flags: Self::Flags) -> (Self, Command<Self::Message>);
+
+ /// Returns the current title of each window of the [`Application`].
+ ///
+ /// This title can be dynamic! The runtime will automatically update the
+ /// title of your application when necessary.
+ fn title(&self, window: window::Id) -> String;
+
+ /// Returns the current [`Theme`] of the [`Application`].
+ fn theme(&self, window: window::Id) -> <Self::Renderer as crate::Renderer>::Theme;
+
+ /// Returns the [`Style`] variation of the [`Theme`].
+ fn style(
+ &self,
+ ) -> <<Self::Renderer as crate::Renderer>::Theme as StyleSheet>::Style {
+ Default::default()
+ }
+
+ /// Returns the event `Subscription` for the current state of the
+ /// application.
+ ///
+ /// The messages produced by the `Subscription` will be handled by
+ /// [`update`](#tymethod.update).
+ ///
+ /// A `Subscription` will be kept alive as long as you keep returning it!
+ ///
+ /// By default, it returns an empty subscription.
+ fn subscription(&self) -> Subscription<Self::Message> {
+ Subscription::none()
+ }
+
+ /// Returns the scale factor of the window of the [`Application`].
+ ///
+ /// It can be used to dynamically control the size of the UI at runtime
+ /// (i.e. zooming).
+ ///
+ /// For instance, a scale factor of `2.0` will make widgets twice as big,
+ /// while a scale factor of `0.5` will shrink them to half their size.
+ ///
+ /// By default, it returns `1.0`.
+ #[allow(unused_variables)]
+ fn scale_factor(&self, window: window::Id) -> f64 {
+ 1.0
+ }
+
+ /// Returns whether the [`Application`] should be terminated.
+ ///
+ /// By default, it returns `false`.
+ fn should_exit(&self) -> bool {
+ false
+ }
+
+ /// Returns the `Self::Message` that should be processed when a `window` is requested to
+ /// be closed.
+ fn close_requested(&self, window: window::Id) -> Self::Message;
+}
+
+/// Runs an [`Application`] with an executor, compositor, and the provided
+/// settings.
+pub fn run<A, E, C>(
+ settings: Settings<A::Flags>,
+ compositor_settings: C::Settings,
+) -> Result<(), Error>
+where
+ A: Application + 'static,
+ E: Executor + 'static,
+ C: iced_graphics::window::Compositor<Renderer = A::Renderer> + 'static,
+ <A::Renderer as crate::Renderer>::Theme: StyleSheet,
+{
+ use futures::task;
+ use futures::Future;
+ use winit::event_loop::EventLoopBuilder;
+
+ #[cfg(feature = "trace")]
+ let _guard = Profiler::init();
+
+ let mut debug = Debug::new();
+ debug.startup_started();
+
+ #[cfg(feature = "trace")]
+ let _ = info_span!("Application", "RUN").entered();
+
+ let event_loop = EventLoopBuilder::with_user_event().build();
+ let proxy = event_loop.create_proxy();
+
+ let runtime = {
+ let proxy = Proxy::new(event_loop.create_proxy());
+ let executor = E::new().map_err(Error::ExecutorCreationFailed)?;
+
+ Runtime::new(executor, proxy)
+ };
+
+ let (application, init_command) = {
+ let flags = settings.flags;
+
+ runtime.enter(|| A::new(flags))
+ };
+
+ let builder = settings.window.into_builder(
+ &application.title(window::Id::MAIN),
+ event_loop.primary_monitor(),
+ settings.id,
+ );
+
+ log::info!("Window builder: {:#?}", builder);
+
+ let window = builder
+ .build(&event_loop)
+ .map_err(Error::WindowCreationFailed)?;
+
+ let windows: HashMap<window::Id, winit::window::Window> =
+ HashMap::from([(window::Id::MAIN, window)]);
+
+ let window = windows.values().next().expect("No window found");
+
+ #[cfg(target_arch = "wasm32")]
+ {
+ use winit::platform::web::WindowExtWebSys;
+
+ let canvas = window.canvas();
+
+ let window = web_sys::window().unwrap();
+ let document = window.document().unwrap();
+ let body = document.body().unwrap();
+
+ let _ = body
+ .append_child(&canvas)
+ .expect("Append canvas to HTML body");
+ }
+
+ let (compositor, renderer) = C::new(compositor_settings, Some(&window))?;
+
+ let (mut event_sender, event_receiver) = mpsc::unbounded();
+ let (control_sender, mut control_receiver) = mpsc::unbounded();
+
+ let mut instance = Box::pin({
+ let run_instance = run_instance::<A, E, C>(
+ application,
+ compositor,
+ renderer,
+ runtime,
+ proxy,
+ debug,
+ event_receiver,
+ control_sender,
+ init_command,
+ windows,
+ settings.exit_on_close_request,
+ );
+
+ #[cfg(feature = "trace")]
+ let run_instance =
+ run_instance.instrument(info_span!("Application", "LOOP"));
+
+ run_instance
+ });
+
+ let mut context = task::Context::from_waker(task::noop_waker_ref());
+
+ platform::run(event_loop, move |event, event_loop, control_flow| {
+ use winit::event_loop::ControlFlow;
+
+ if let ControlFlow::ExitWithCode(_) = control_flow {
+ return;
+ }
+
+ let event = match event {
+ winit::event::Event::WindowEvent {
+ event:
+ winit::event::WindowEvent::ScaleFactorChanged {
+ new_inner_size,
+ ..
+ },
+ window_id,
+ } => Some(winit::event::Event::WindowEvent {
+ event: winit::event::WindowEvent::Resized(*new_inner_size),
+ window_id,
+ }),
+ winit::event::Event::UserEvent(Event::NewWindow {
+ id,
+ settings,
+ title,
+ }) => {
+ let window = settings
+ .into_builder(&title, event_loop.primary_monitor(), None)
+ .build(event_loop)
+ .expect("Failed to build window");
+
+ Some(winit::event::Event::UserEvent(Event::WindowCreated(
+ id, window,
+ )))
+ }
+ _ => event.to_static(),
+ };
+
+ if let Some(event) = event {
+ event_sender.start_send(event).expect("Send event");
+
+ let poll = instance.as_mut().poll(&mut context);
+
+ match poll {
+ task::Poll::Pending => {
+ if let Ok(Some(flow)) = control_receiver.try_next() {
+ *control_flow = flow;
+ }
+ }
+ task::Poll::Ready(_) => {
+ *control_flow = ControlFlow::Exit;
+ }
+ };
+ }
+ })
+}
+
+async fn run_instance<A, E, C>(
+ mut application: A,
+ mut compositor: C,
+ mut renderer: A::Renderer,
+ mut runtime: Runtime<E, Proxy<Event<A::Message>>, Event<A::Message>>,
+ mut proxy: winit::event_loop::EventLoopProxy<Event<A::Message>>,
+ mut debug: Debug,
+ mut event_receiver: mpsc::UnboundedReceiver<
+ winit::event::Event<'_, Event<A::Message>>,
+ >,
+ mut control_sender: mpsc::UnboundedSender<winit::event_loop::ControlFlow>,
+ init_command: Command<A::Message>,
+ mut windows: HashMap<window::Id, winit::window::Window>,
+ _exit_on_close_request: bool,
+) where
+ A: Application + 'static,
+ E: Executor + 'static,
+ C: iced_graphics::window::Compositor<Renderer = A::Renderer> + 'static,
+ <A::Renderer as crate::Renderer>::Theme: StyleSheet,
+{
+ use iced_futures::futures::stream::StreamExt;
+ use winit::event;
+ use winit::event_loop::ControlFlow;
+
+ let mut clipboard =
+ Clipboard::connect(windows.values().next().expect("No window found"));
+ let mut caches = HashMap::new();
+ let mut window_ids: HashMap<_, _> = windows
+ .iter()
+ .map(|(&id, window)| (window.id(), id))
+ .collect();
+
+ let mut states = HashMap::new();
+ let mut surfaces = HashMap::new();
+ let mut interfaces = ManuallyDrop::new(HashMap::new());
+
+ for (&id, window) in windows.keys().zip(windows.values()) {
+ let mut surface = compositor.create_surface(window);
+ let state = State::new(&application, id, window);
+ let physical_size = state.physical_size();
+
+ compositor.configure_surface(
+ &mut surface,
+ physical_size.width,
+ physical_size.height,
+ );
+
+ let user_interface = build_user_interface(
+ &application,
+ user_interface::Cache::default(),
+ &mut renderer,
+ state.logical_size(),
+ &mut debug,
+ id,
+ );
+
+ let _ = states.insert(id, state);
+ let _ = surfaces.insert(id, surface);
+ let _ = interfaces.insert(id, user_interface);
+ let _ = caches.insert(id, user_interface::Cache::default());
+ }
+
+ run_command(
+ &application,
+ &mut caches,
+ &states,
+ &mut renderer,
+ init_command,
+ &mut runtime,
+ &mut clipboard,
+ &mut proxy,
+ &mut debug,
+ &windows,
+ || compositor.fetch_information(),
+ );
+
+ runtime.track(application.subscription().map(Event::Application));
+
+ let mut mouse_interaction = mouse::Interaction::default();
+ let mut events = Vec::new();
+ let mut messages = Vec::new();
+ let mut redraw_pending = false;
+
+ debug.startup_finished();
+
+ 'main: while let Some(event) = event_receiver.next().await {
+ match event {
+ event::Event::NewEvents(start_cause) => {
+ redraw_pending = matches!(
+ start_cause,
+ event::StartCause::Init
+ | event::StartCause::Poll
+ | event::StartCause::ResumeTimeReached { .. }
+ );
+ }
+ event::Event::MainEventsCleared => {
+ for id in states.keys().copied().collect::<Vec<_>>() {
+ // Partition events into only events for this window
+ let (filtered, remaining): (Vec<_>, Vec<_>) =
+ events.iter().cloned().partition(
+ |(window_id, _event): &(
+ Option<window::Id>,
+ iced_native::event::Event,
+ )| {
+ *window_id == Some(id) || *window_id == None
+ },
+ );
+
+ // Only retain events which have not been processed for next iteration
+ events.retain(|el| remaining.contains(el));
+
+ let window_events: Vec<_> = filtered
+ .into_iter()
+ .map(|(_id, event)| event)
+ .collect();
+
+ if !redraw_pending
+ && window_events.is_empty()
+ && messages.is_empty()
+ {
+ continue;
+ }
+
+ // Process winit events for window
+ debug.event_processing_started();
+ let cursor_position =
+ states.get(&id).unwrap().cursor_position();
+
+ let (interface_state, statuses) = {
+ let user_interface = interfaces.get_mut(&id).unwrap();
+ user_interface.update(
+ &window_events,
+ cursor_position,
+ &mut renderer,
+ &mut clipboard,
+ &mut messages,
+ )
+ };
+
+ for event in
+ window_events.into_iter().zip(statuses.into_iter())
+ {
+ runtime.broadcast(event);
+ }
+ debug.event_processing_finished();
+
+ // Update application with app messages
+ // Unless we implement some kind of diffing, we must redraw all windows as we
+ // cannot know what changed.
+ if !messages.is_empty()
+ || matches!(
+ interface_state,
+ user_interface::State::Outdated,
+ )
+ {
+ let mut cached_interfaces: HashMap<_, _> =
+ ManuallyDrop::into_inner(interfaces)
+ .drain()
+ .map(
+ |(id, interface): (
+ window::Id,
+ UserInterface<'_, _, _>,
+ )| {
+ (id, interface.into_cache())
+ },
+ )
+ .collect();
+
+ // Update application
+ update(
+ &mut application,
+ &mut cached_interfaces,
+ &states,
+ &mut renderer,
+ &mut runtime,
+ &mut clipboard,
+ &mut proxy,
+ &mut debug,
+ &mut messages,
+ &windows,
+ || compositor.fetch_information(),
+ );
+
+ // synchronize window states with application states.
+ for (id, state) in states.iter_mut() {
+ state.synchronize(
+ &application,
+ *id,
+ windows
+ .get(id)
+ .expect("No window found with ID."),
+ );
+ }
+
+ interfaces = ManuallyDrop::new(build_user_interfaces(
+ &application,
+ &mut renderer,
+ &mut debug,
+ &states,
+ cached_interfaces,
+ ));
+
+ if application.should_exit() {
+ break 'main;
+ }
+ }
+
+ // TODO: Avoid redrawing all the time by forcing widgets to
+ // request redraws on state changes
+ //
+ // Then, we can use the `interface_state` here to decide if a redraw
+ // is needed right away, or simply wait until a specific time.
+ let redraw_event = iced_native::Event::Window(
+ id,
+ window::Event::RedrawRequested(Instant::now()),
+ );
+
+ let (interface_state, _) =
+ interfaces.get_mut(&id).unwrap().update(
+ &[redraw_event.clone()],
+ cursor_position,
+ &mut renderer,
+ &mut clipboard,
+ &mut messages,
+ );
+
+ debug.draw_started();
+ let new_mouse_interaction = {
+ let state = states.get(&id).unwrap();
+
+ interfaces.get_mut(&id).unwrap().draw(
+ &mut renderer,
+ state.theme(),
+ &renderer::Style {
+ text_color: state.text_color(),
+ },
+ state.cursor_position(),
+ )
+ };
+ debug.draw_finished();
+
+ let window = windows.get(&id).unwrap();
+
+ if new_mouse_interaction != mouse_interaction {
+ window.set_cursor_icon(conversion::mouse_interaction(
+ new_mouse_interaction,
+ ));
+
+ mouse_interaction = new_mouse_interaction;
+ }
+
+ for window in windows.values() {
+ window.request_redraw();
+ }
+
+ runtime.broadcast((
+ redraw_event.clone(),
+ crate::event::Status::Ignored,
+ ));
+
+ let _ = control_sender.start_send(match interface_state {
+ user_interface::State::Updated {
+ redraw_request: Some(redraw_request),
+ } => match redraw_request {
+ window::RedrawRequest::NextFrame => {
+ ControlFlow::Poll
+ }
+ window::RedrawRequest::At(at) => {
+ ControlFlow::WaitUntil(at)
+ }
+ },
+ _ => ControlFlow::Wait,
+ });
+
+ redraw_pending = false;
+ }
+ }
+ event::Event::PlatformSpecific(event::PlatformSpecific::MacOS(
+ event::MacOS::ReceivedUrl(url),
+ )) => {
+ use iced_native::event;
+ events.push((
+ None,
+ iced_native::Event::PlatformSpecific(
+ event::PlatformSpecific::MacOS(
+ event::MacOS::ReceivedUrl(url),
+ ),
+ ),
+ ));
+ }
+ event::Event::UserEvent(event) => match event {
+ Event::Application(message) => {
+ messages.push(message);
+ }
+ Event::WindowCreated(id, window) => {
+ let mut surface = compositor.create_surface(&window);
+ let state = State::new(&application, id, &window);
+ let physical_size = state.physical_size();
+
+ compositor.configure_surface(
+ &mut surface,
+ physical_size.width,
+ physical_size.height,
+ );
+
+ let user_interface = build_user_interface(
+ &application,
+ user_interface::Cache::default(),
+ &mut renderer,
+ state.logical_size(),
+ &mut debug,
+ id,
+ );
+
+ let _ = states.insert(id, state);
+ let _ = surfaces.insert(id, surface);
+ let _ = interfaces.insert(id, user_interface);
+ let _ = window_ids.insert(window.id(), id);
+ let _ = windows.insert(id, window);
+ let _ = caches.insert(id, user_interface::Cache::default());
+ }
+ Event::CloseWindow(id) => {
+ if let Some(window) = windows.get(&id) {
+ if window_ids.remove(&window.id()).is_none() {
+ log::error!("Failed to remove window with id {:?} from window_ids.", window.id());
+ }
+ } else {
+ log::error!(
+ "Could not find window with id {:?} in windows.",
+ id
+ );
+ }
+ if states.remove(&id).is_none() {
+ log::error!(
+ "Failed to remove window {:?} from states.",
+ id
+ );
+ }
+ if interfaces.remove(&id).is_none() {
+ log::error!(
+ "Failed to remove window {:?} from interfaces.",
+ id
+ );
+ }
+ if windows.remove(&id).is_none() {
+ log::error!(
+ "Failed to remove window {:?} from windows.",
+ id
+ );
+ }
+ if surfaces.remove(&id).is_none() {
+ log::error!(
+ "Failed to remove window {:?} from surfaces.",
+ id
+ );
+ }
+
+ if windows.is_empty() {
+ log::info!(
+ "All windows are closed. Terminating program."
+ );
+ break 'main;
+ } else {
+ log::info!("Remaining windows: {:?}", windows.len());
+ }
+ }
+ Event::NewWindow { .. } => unreachable!(),
+ },
+ event::Event::RedrawRequested(id) => {
+ #[cfg(feature = "trace")]
+ let _ = info_span!("Application", "FRAME").entered();
+
+ let state = window_ids
+ .get(&id)
+ .and_then(|id| states.get_mut(id))
+ .unwrap();
+ let surface = window_ids
+ .get(&id)
+ .and_then(|id| surfaces.get_mut(id))
+ .unwrap();
+ let physical_size = state.physical_size();
+
+ if physical_size.width == 0 || physical_size.height == 0 {
+ continue;
+ }
+
+ debug.render_started();
+
+ if state.viewport_changed() {
+ let mut user_interface = window_ids
+ .get(&id)
+ .and_then(|id| interfaces.remove(id))
+ .unwrap();
+
+ let logical_size = state.logical_size();
+
+ debug.layout_started();
+ user_interface =
+ user_interface.relayout(logical_size, &mut renderer);
+ debug.layout_finished();
+
+ debug.draw_started();
+ let new_mouse_interaction = {
+ let state = &state;
+
+ user_interface.draw(
+ &mut renderer,
+ state.theme(),
+ &renderer::Style {
+ text_color: state.text_color(),
+ },
+ state.cursor_position(),
+ )
+ };
+
+ let window = window_ids
+ .get(&id)
+ .and_then(|id| windows.get(id))
+ .unwrap();
+ if new_mouse_interaction != mouse_interaction {
+ window.set_cursor_icon(conversion::mouse_interaction(
+ new_mouse_interaction,
+ ));
+
+ mouse_interaction = new_mouse_interaction;
+ }
+ debug.draw_finished();
+
+ let _ = interfaces
+ .insert(*window_ids.get(&id).unwrap(), user_interface);
+
+ compositor.configure_surface(
+ surface,
+ physical_size.width,
+ physical_size.height,
+ );
+ }
+
+ match compositor.present(
+ &mut renderer,
+ surface,
+ state.viewport(),
+ state.background_color(),
+ &debug.overlay(),
+ ) {
+ Ok(()) => {
+ debug.render_finished();
+
+ // TODO: Handle animations!
+ // Maybe we can use `ControlFlow::WaitUntil` for this.
+ }
+ Err(error) => match error {
+ // This is an unrecoverable error.
+ compositor::SurfaceError::OutOfMemory => {
+ panic!("{:?}", error);
+ }
+ _ => {
+ debug.render_finished();
+ log::error!("Error {error:?} when presenting surface.");
+
+ // Try rendering windows again next frame.
+ for window in windows.values() {
+ window.request_redraw();
+ }
+ }
+ },
+ }
+ }
+ event::Event::WindowEvent {
+ event: window_event,
+ window_id,
+ } => {
+ if let (Some(window), Some(state)) = (
+ window_ids.get(&window_id).and_then(|id| windows.get(id)),
+ window_ids
+ .get(&window_id)
+ .and_then(|id| states.get_mut(id)),
+ ) {
+ if crate::application::requests_exit(&window_event, state.modifiers()) {
+ if let Some(id) = window_ids.get(&window_id).cloned() {
+ let message = application.close_requested(id);
+ messages.push(message);
+ }
+ }
+
+ state.update(window, &window_event, &mut debug);
+
+ if let Some(event) = conversion::window_event(
+ *window_ids.get(&window_id).unwrap(),
+ &window_event,
+ state.scale_factor(),
+ state.modifiers(),
+ ) {
+ events
+ .push((window_ids.get(&window_id).cloned(), event));
+ }
+ } else {
+ log::error!(
+ "Could not find window or state for id: {window_id:?}"
+ );
+ }
+ }
+ _ => {}
+ }
+ }
+
+ // Manually drop the user interfaces
+ drop(ManuallyDrop::into_inner(interfaces));
+}
+
+/// Builds a window's [`UserInterface`] for the [`Application`].
+pub fn build_user_interface<'a, A: Application>(
+ application: &'a A,
+ cache: user_interface::Cache,
+ renderer: &mut A::Renderer,
+ size: Size,
+ debug: &mut Debug,
+ id: window::Id,
+) -> UserInterface<'a, A::Message, A::Renderer>
+where
+ <A::Renderer as crate::Renderer>::Theme: StyleSheet,
+{
+ #[cfg(feature = "trace")]
+ let view_span = info_span!("Application", "VIEW").entered();
+
+ debug.view_started();
+ let view = application.view(id);
+
+ #[cfg(feature = "trace")]
+ let _ = view_span.exit();
+ debug.view_finished();
+
+ #[cfg(feature = "trace")]
+ let layout_span = info_span!("Application", "LAYOUT").entered();
+ debug.layout_started();
+
+ let user_interface = UserInterface::build(view, size, cache, renderer);
+
+ #[cfg(feature = "trace")]
+ let _ = layout_span.exit();
+ debug.layout_finished();
+
+ user_interface
+}
+
+/// Updates an [`Application`] by feeding it messages, spawning any
+/// resulting [`Command`], and tracking its [`Subscription`].
+pub fn update<A: Application, E: Executor>(
+ application: &mut A,
+ caches: &mut HashMap<window::Id, user_interface::Cache>,
+ states: &HashMap<window::Id, State<A>>,
+ renderer: &mut A::Renderer,
+ runtime: &mut Runtime<E, Proxy<Event<A::Message>>, Event<A::Message>>,
+ clipboard: &mut Clipboard,
+ proxy: &mut winit::event_loop::EventLoopProxy<Event<A::Message>>,
+ debug: &mut Debug,
+ messages: &mut Vec<A::Message>,
+ windows: &HashMap<window::Id, winit::window::Window>,
+ graphics_info: impl FnOnce() -> compositor::Information + Copy,
+) where
+ A: Application + 'static,
+ <A::Renderer as crate::Renderer>::Theme: StyleSheet,
+{
+ for message in messages.drain(..) {
+ #[cfg(feature = "trace")]
+ let update_span = info_span!("Application", "UPDATE").entered();
+
+ debug.log_message(&message);
+
+ debug.update_started();
+
+ let command = runtime.enter(|| application.update(message));
+
+ #[cfg(feature = "trace")]
+ let _ = update_span.exit();
+ debug.update_finished();
+
+ run_command(
+ application,
+ caches,
+ states,
+ renderer,
+ command,
+ runtime,
+ clipboard,
+ proxy,
+ debug,
+ windows,
+ graphics_info,
+ );
+ }
+
+ let subscription = application.subscription().map(Event::Application);
+ runtime.track(subscription);
+}
+
+/// Runs the actions of a [`Command`].
+pub fn run_command<A, E>(
+ application: &A,
+ caches: &mut HashMap<window::Id, user_interface::Cache>,
+ states: &HashMap<window::Id, State<A>>,
+ renderer: &mut A::Renderer,
+ command: Command<A::Message>,
+ runtime: &mut Runtime<E, Proxy<Event<A::Message>>, Event<A::Message>>,
+ clipboard: &mut Clipboard,
+ proxy: &mut winit::event_loop::EventLoopProxy<Event<A::Message>>,
+ debug: &mut Debug,
+ windows: &HashMap<window::Id, winit::window::Window>,
+ _graphics_info: impl FnOnce() -> compositor::Information + Copy,
+) where
+ A: Application + 'static,
+ E: Executor,
+ <A::Renderer as crate::Renderer>::Theme: StyleSheet,
+{
+ use iced_native::command;
+ use iced_native::system;
+ use iced_native::window;
+
+ for action in command.actions() {
+ match action {
+ command::Action::Future(future) => {
+ runtime.spawn(Box::pin(future.map(Event::Application)));
+ }
+ command::Action::Clipboard(action) => match action {
+ clipboard::Action::Read(tag) => {
+ let message = tag(clipboard.read());
+
+ proxy
+ .send_event(Event::Application(message))
+ .expect("Send message to event loop");
+ }
+ clipboard::Action::Write(contents) => {
+ clipboard.write(contents);
+ }
+ },
+ command::Action::Window(id, action) => match action {
+ window::Action::Spawn { settings } => {
+ proxy
+ .send_event(Event::NewWindow {
+ id,
+ settings: settings.into(),
+ title: application.title(id),
+ })
+ .expect("Send message to event loop");
+ }
+ window::Action::Close => {
+ proxy
+ .send_event(Event::CloseWindow(id))
+ .expect("Send message to event loop");
+ }
+ window::Action::Drag => {
+ let window = windows.get(&id).expect("No window found");
+ let _res = window.drag_window();
+ }
+ window::Action::Resize { width, height } => {
+ let window = windows.get(&id).expect("No window found");
+ window.set_inner_size(winit::dpi::LogicalSize {
+ width,
+ height,
+ });
+ }
+ window::Action::Move { x, y } => {
+ let window = windows.get(&id).expect("No window found");
+ window.set_outer_position(winit::dpi::LogicalPosition {
+ x,
+ y,
+ });
+ }
+ window::Action::ChangeMode(mode) => {
+ let window = windows.get(&id).expect("No window found");
+ window.set_visible(conversion::visible(mode));
+ window.set_fullscreen(conversion::fullscreen(
+ window.current_monitor(),
+ mode,
+ ));
+ }
+ window::Action::FetchMode(tag) => {
+ let window = windows.get(&id).expect("No window found");
+ let mode = if window.is_visible().unwrap_or(true) {
+ conversion::mode(window.fullscreen())
+ } else {
+ window::Mode::Hidden
+ };
+
+ proxy
+ .send_event(Event::Application(tag(mode)))
+ .expect("Send message to event loop");
+ }
+ window::Action::Maximize(value) => {
+ let window = windows.get(&id).expect("No window found!");
+ window.set_maximized(value);
+ }
+ window::Action::Minimize(value) => {
+ let window = windows.get(&id).expect("No window found!");
+ window.set_minimized(value);
+ }
+ window::Action::ToggleMaximize => {
+ let window = windows.get(&id).expect("No window found!");
+ window.set_maximized(!window.is_maximized());
+ }
+ window::Action::ToggleDecorations => {
+ let window = windows.get(&id).expect("No window found!");
+ window.set_decorations(!window.is_decorated());
+ }
+ window::Action::RequestUserAttention(attention_type) => {
+ let window = windows.get(&id).expect("No window found!");
+ window.request_user_attention(
+ attention_type.map(conversion::user_attention),
+ );
+ }
+ window::Action::GainFocus => {
+ let window = windows.get(&id).expect("No window found!");
+ window.focus_window();
+ }
+ window::Action::ChangeAlwaysOnTop(on_top) => {
+ let window = windows.get(&id).expect("No window found!");
+ window.set_always_on_top(on_top);
+ }
+ window::Action::FetchId(tag) => {
+ let window = windows.get(&id).expect("No window found!");
+
+ proxy
+ .send_event(Event::Application(tag(window.id().into())))
+ .expect("Send message to event loop.")
+ }
+ },
+ command::Action::System(action) => match action {
+ system::Action::QueryInformation(_tag) => {
+ #[cfg(feature = "system")]
+ {
+ let graphics_info = _graphics_info();
+ let proxy = proxy.clone();
+
+ let _ = std::thread::spawn(move || {
+ let information =
+ crate::system::information(graphics_info);
+
+ let message = _tag(information);
+
+ proxy
+ .send_event(Event::Application(message))
+ .expect("Send message to event loop")
+ });
+ }
+ }
+ },
+ command::Action::Widget(action) => {
+ let mut current_caches = std::mem::take(caches);
+ let mut current_operation = Some(action.into_operation());
+
+ let mut user_interfaces = build_user_interfaces(
+ application,
+ renderer,
+ debug,
+ states,
+ current_caches,
+ );
+
+ while let Some(mut operation) = current_operation.take() {
+ for user_interface in user_interfaces.values_mut() {
+ user_interface.operate(renderer, operation.as_mut());
+
+ match operation.finish() {
+ operation::Outcome::None => {}
+ operation::Outcome::Some(message) => {
+ proxy
+ .send_event(Event::Application(message))
+ .expect("Send message to event loop");
+ }
+ operation::Outcome::Chain(next) => {
+ current_operation = Some(next);
+ }
+ }
+ }
+ }
+
+ let user_interfaces: HashMap<_, _> = user_interfaces
+ .drain()
+ .map(|(id, interface)| (id, interface.into_cache()))
+ .collect();
+
+ current_caches = user_interfaces;
+ *caches = current_caches;
+ }
+ }
+ }
+}
+
+/// Build the user interfaces for every window.
+pub fn build_user_interfaces<'a, A>(
+ application: &'a A,
+ renderer: &mut A::Renderer,
+ debug: &mut Debug,
+ states: &HashMap<window::Id, State<A>>,
+ mut cached_user_interfaces: HashMap<window::Id, user_interface::Cache>,
+) -> HashMap<
+ window::Id,
+ UserInterface<
+ 'a,
+ <A as Application>::Message,
+ <A as Application>::Renderer,
+ >,
+>
+where
+ A: Application + 'static,
+ <A::Renderer as crate::Renderer>::Theme: StyleSheet,
+{
+ let mut interfaces = HashMap::new();
+
+ for (id, cache) in cached_user_interfaces.drain() {
+ let state = &states.get(&id).unwrap();
+
+ let user_interface = build_user_interface(
+ application,
+ cache,
+ renderer,
+ state.logical_size(),
+ debug,
+ id,
+ );
+
+ let _ = interfaces.insert(id, user_interface);
+ }
+
+ interfaces
+}
+
+#[cfg(not(target_arch = "wasm32"))]
+mod platform {
+ pub fn run<T, F>(
+ mut event_loop: winit::event_loop::EventLoop<T>,
+ event_handler: F,
+ ) -> Result<(), super::Error>
+ where
+ F: 'static
+ + FnMut(
+ winit::event::Event<'_, T>,
+ &winit::event_loop::EventLoopWindowTarget<T>,
+ &mut winit::event_loop::ControlFlow,
+ ),
+ {
+ use winit::platform::run_return::EventLoopExtRunReturn;
+
+ let _ = event_loop.run_return(event_handler);
+
+ Ok(())
+ }
+}
+
+#[cfg(target_arch = "wasm32")]
+mod platform {
+ pub fn run<T, F>(
+ event_loop: winit::event_loop::EventLoop<T>,
+ event_handler: F,
+ ) -> !
+ where
+ F: 'static
+ + FnMut(
+ winit::event::Event<'_, T>,
+ &winit::event_loop::EventLoopWindowTarget<T>,
+ &mut winit::event_loop::ControlFlow,
+ ),
+ {
+ event_loop.run(event_handler)
+ }
+}
diff --git a/winit/src/multi_window/state.rs b/winit/src/multi_window/state.rs
new file mode 100644
index 00000000..54a114ad
--- /dev/null
+++ b/winit/src/multi_window/state.rs
@@ -0,0 +1,218 @@
+use crate::application::{self, StyleSheet as _};
+use crate::conversion;
+use crate::multi_window::Application;
+use crate::window;
+use crate::{Color, Debug, Point, Size, Viewport};
+
+use std::marker::PhantomData;
+use winit::event::{Touch, WindowEvent};
+use winit::window::Window;
+
+/// The state of a multi-windowed [`Application`].
+#[allow(missing_debug_implementations)]
+pub struct State<A: Application>
+where
+ <A::Renderer as crate::Renderer>::Theme: application::StyleSheet,
+{
+ title: String,
+ scale_factor: f64,
+ viewport: Viewport,
+ viewport_changed: bool,
+ cursor_position: winit::dpi::PhysicalPosition<f64>,
+ modifiers: winit::event::ModifiersState,
+ theme: <A::Renderer as crate::Renderer>::Theme,
+ appearance: application::Appearance,
+ application: PhantomData<A>,
+}
+
+impl<A: Application> State<A>
+where
+ <A::Renderer as crate::Renderer>::Theme: application::StyleSheet,
+{
+ /// Creates a new [`State`] for the provided [`Application`]'s `window`.
+ pub fn new(
+ application: &A,
+ window_id: window::Id,
+ window: &Window,
+ ) -> Self {
+ let title = application.title(window_id);
+ let scale_factor = application.scale_factor(window_id);
+ let theme = application.theme(window_id);
+ let appearance = theme.appearance(&application.style());
+
+ let viewport = {
+ let physical_size = window.inner_size();
+
+ Viewport::with_physical_size(
+ Size::new(physical_size.width, physical_size.height),
+ window.scale_factor() * scale_factor,
+ )
+ };
+
+ Self {
+ title,
+ scale_factor,
+ viewport,
+ viewport_changed: false,
+ // TODO: Encode cursor availability in the type-system
+ cursor_position: winit::dpi::PhysicalPosition::new(-1.0, -1.0),
+ modifiers: winit::event::ModifiersState::default(),
+ theme,
+ appearance,
+ application: PhantomData,
+ }
+ }
+
+ /// Returns the current [`Viewport`] of the [`State`].
+ pub fn viewport(&self) -> &Viewport {
+ &self.viewport
+ }
+
+ /// Returns whether or not the viewport changed.
+ pub fn viewport_changed(&self) -> bool {
+ self.viewport_changed
+ }
+
+ /// Returns the physical [`Size`] of the [`Viewport`] of the [`State`].
+ pub fn physical_size(&self) -> Size<u32> {
+ self.viewport.physical_size()
+ }
+
+ /// Returns the logical [`Size`] of the [`Viewport`] of the [`State`].
+ pub fn logical_size(&self) -> Size<f32> {
+ self.viewport.logical_size()
+ }
+
+ /// Returns the current scale factor of the [`Viewport`] of the [`State`].
+ pub fn scale_factor(&self) -> f64 {
+ self.viewport.scale_factor()
+ }
+
+ /// Returns the current cursor position of the [`State`].
+ pub fn cursor_position(&self) -> Point {
+ conversion::cursor_position(
+ self.cursor_position,
+ self.viewport.scale_factor(),
+ )
+ }
+
+ /// Returns the current keyboard modifiers of the [`State`].
+ pub fn modifiers(&self) -> winit::event::ModifiersState {
+ self.modifiers
+ }
+
+ /// Returns the current theme of the [`State`].
+ pub fn theme(&self) -> &<A::Renderer as crate::Renderer>::Theme {
+ &self.theme
+ }
+
+ /// Returns the current background [`Color`] of the [`State`].
+ pub fn background_color(&self) -> Color {
+ self.appearance.background_color
+ }
+
+ /// Returns the current text [`Color`] of the [`State`].
+ pub fn text_color(&self) -> Color {
+ self.appearance.text_color
+ }
+
+ /// Processes the provided window event and updates the [`State`] accordingly.
+ pub fn update(
+ &mut self,
+ window: &Window,
+ event: &WindowEvent<'_>,
+ _debug: &mut Debug,
+ ) {
+ match event {
+ WindowEvent::Resized(new_size) => {
+ let size = Size::new(new_size.width, new_size.height);
+
+ self.viewport = Viewport::with_physical_size(
+ size,
+ window.scale_factor() * self.scale_factor,
+ );
+
+ self.viewport_changed = true;
+ }
+ WindowEvent::ScaleFactorChanged {
+ scale_factor: new_scale_factor,
+ new_inner_size,
+ } => {
+ let size =
+ Size::new(new_inner_size.width, new_inner_size.height);
+
+ self.viewport = Viewport::with_physical_size(
+ size,
+ new_scale_factor * self.scale_factor,
+ );
+
+ self.viewport_changed = true;
+ }
+ WindowEvent::CursorMoved { position, .. }
+ | WindowEvent::Touch(Touch {
+ location: position, ..
+ }) => {
+ self.cursor_position = *position;
+ }
+ WindowEvent::CursorLeft { .. } => {
+ // TODO: Encode cursor availability in the type-system
+ self.cursor_position =
+ winit::dpi::PhysicalPosition::new(-1.0, -1.0);
+ }
+ WindowEvent::ModifiersChanged(new_modifiers) => {
+ self.modifiers = *new_modifiers;
+ }
+ #[cfg(feature = "debug")]
+ WindowEvent::KeyboardInput {
+ input:
+ winit::event::KeyboardInput {
+ virtual_keycode: Some(winit::event::VirtualKeyCode::F12),
+ state: winit::event::ElementState::Pressed,
+ ..
+ },
+ ..
+ } => _debug.toggle(),
+ _ => {}
+ }
+ }
+
+ /// Synchronizes the [`State`] with its [`Application`] and its respective
+ /// window.
+ ///
+ /// Normally, an [`Application`] should be synchronized with its [`State`]
+ /// and window after calling [`Application::update`].
+ ///
+ /// [`Application::update`]: crate::Program::update
+ pub fn synchronize(
+ &mut self,
+ application: &A,
+ window_id: window::Id,
+ window: &Window,
+ ) {
+ // Update window title
+ let new_title = application.title(window_id);
+
+ if self.title != new_title {
+ window.set_title(&new_title);
+ self.title = new_title;
+ }
+
+ // Update scale factor
+ let new_scale_factor = application.scale_factor(window_id);
+
+ if self.scale_factor != new_scale_factor {
+ let size = window.inner_size();
+
+ self.viewport = Viewport::with_physical_size(
+ Size::new(size.width, size.height),
+ window.scale_factor() * new_scale_factor,
+ );
+
+ self.scale_factor = new_scale_factor;
+ }
+
+ // Update theme and appearance
+ self.theme = application.theme(window_id);
+ self.appearance = self.theme.appearance(&application.style());
+ }
+}
diff --git a/winit/src/position.rs b/winit/src/position.rs
deleted file mode 100644
index c260c29e..00000000
--- a/winit/src/position.rs
+++ /dev/null
@@ -1,22 +0,0 @@
-/// The position of a window in a given screen.
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-pub enum Position {
- /// The platform-specific default position for a new window.
- Default,
- /// The window is completely centered on the screen.
- Centered,
- /// The window is positioned with specific coordinates: `(X, Y)`.
- ///
- /// When the decorations of the window are enabled, Windows 10 will add some
- /// invisible padding to the window. This padding gets included in the
- /// position. So if you have decorations enabled and want the window to be
- /// at (0, 0) you would have to set the position to
- /// `(PADDING_X, PADDING_Y)`.
- Specific(i32, i32),
-}
-
-impl Default for Position {
- fn default() -> Self {
- Self::Default
- }
-}
diff --git a/winit/src/application/profiler.rs b/winit/src/profiler.rs
index 7031507a..7031507a 100644
--- a/winit/src/application/profiler.rs
+++ b/winit/src/profiler.rs
diff --git a/winit/src/window.rs b/winit/src/window.rs
new file mode 100644
index 00000000..e69de29b
--- /dev/null
+++ b/winit/src/window.rs