diff options
Diffstat (limited to 'src')
-rw-r--r-- | src/application.rs | 251 | ||||
-rw-r--r-- | src/element.rs | 2 | ||||
-rw-r--r-- | src/error.rs | 34 | ||||
-rw-r--r-- | src/executor.rs | 30 | ||||
-rw-r--r-- | src/keyboard.rs | 2 | ||||
-rw-r--r-- | src/lib.rs | 62 | ||||
-rw-r--r-- | src/mouse.rs | 2 | ||||
-rw-r--r-- | src/result.rs | 6 | ||||
-rw-r--r-- | src/sandbox.rs | 171 | ||||
-rw-r--r-- | src/settings.rs | 64 | ||||
-rw-r--r-- | src/time.rs | 12 | ||||
-rw-r--r-- | src/widget.rs | 53 | ||||
-rw-r--r-- | src/window.rs | 3 | ||||
-rw-r--r-- | src/window/icon.rs | 132 | ||||
-rw-r--r-- | src/window/settings.rs | 43 |
15 files changed, 634 insertions, 233 deletions
diff --git a/src/application.rs b/src/application.rs index 2ee3337f..3b690a7c 100644 --- a/src/application.rs +++ b/src/application.rs @@ -1,4 +1,5 @@ -use crate::{window, Command, Element, Executor, Settings, Subscription}; +use crate::window; +use crate::{Color, Command, Element, Executor, Settings, Subscription}; /// An interactive cross-platform application. /// @@ -9,109 +10,114 @@ use crate::{window, Command, Element, Executor, Settings, Subscription}; /// - On the web, it will take control of the `<title>` and the `<body>` of the /// document. /// -/// An [`Application`](trait.Application.html) can execute asynchronous actions -/// by returning a [`Command`](struct.Command.html) in some of its methods. If -/// you do not intend to perform any background work in your program, the -/// [`Sandbox`](trait.Sandbox.html) trait offers a simplified interface. +/// An [`Application`] can execute asynchronous actions by returning a +/// [`Command`] in some of its methods. If you do not intend to perform any +/// background work in your program, the [`Sandbox`] trait offers a simplified +/// interface. /// -/// # Example -/// Let's say we want to run the [`Counter` example we implemented -/// before](index.html#overview). We just need to fill in the gaps: +/// When using an [`Application`] with the `debug` feature enabled, a debug view +/// can be toggled by pressing `F12`. /// -/// ```no_run -/// use iced::{button, executor, Application, Button, Column, Command, Element, Settings, Text}; +/// # Examples +/// [The repository has a bunch of examples] that use the [`Application`] trait: /// -/// pub fn main() { -/// Counter::run(Settings::default()) -/// } +/// - [`clock`], an application that uses the [`Canvas`] widget to draw a clock +/// and its hands to display the current time. +/// - [`download_progress`], a basic application that asynchronously downloads +/// a dummy file of 100 MB and tracks the download progress. +/// - [`events`], a log of native events displayed using a conditional +/// [`Subscription`]. +/// - [`game_of_life`], an interactive version of the [Game of Life], invented +/// by [John Horton Conway]. +/// - [`pokedex`], an application that displays a random Pokédex entry (sprite +/// included!) by using the [PokéAPI]. +/// - [`solar_system`], an animated solar system drawn using the [`Canvas`] widget +/// and showcasing how to compose different transforms. +/// - [`stopwatch`], a watch with start/stop and reset buttons showcasing how +/// to listen to time. +/// - [`todos`], a todos tracker inspired by [TodoMVC]. /// -/// #[derive(Default)] -/// struct Counter { -/// value: i32, -/// increment_button: button::State, -/// decrement_button: button::State, -/// } +/// [The repository has a bunch of examples]: https://github.com/hecrj/iced/tree/0.2/examples +/// [`clock`]: https://github.com/hecrj/iced/tree/0.2/examples/clock +/// [`download_progress`]: https://github.com/hecrj/iced/tree/0.2/examples/download_progress +/// [`events`]: https://github.com/hecrj/iced/tree/0.2/examples/events +/// [`game_of_life`]: https://github.com/hecrj/iced/tree/0.2/examples/game_of_life +/// [`pokedex`]: https://github.com/hecrj/iced/tree/0.2/examples/pokedex +/// [`solar_system`]: https://github.com/hecrj/iced/tree/0.2/examples/solar_system +/// [`stopwatch`]: https://github.com/hecrj/iced/tree/0.2/examples/stopwatch +/// [`todos`]: https://github.com/hecrj/iced/tree/0.2/examples/todos +/// [`Sandbox`]: crate::Sandbox +/// [`Canvas`]: crate::widget::Canvas +/// [PokéAPI]: https://pokeapi.co/ +/// [TodoMVC]: http://todomvc.com/ +/// +/// ## 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, Application, Command, Element, Settings, Text}; /// -/// #[derive(Debug, Clone, Copy)] -/// enum Message { -/// IncrementPressed, -/// DecrementPressed, +/// pub fn main() -> iced::Result { +/// Hello::run(Settings::default()) /// } /// -/// impl Application for Counter { -/// type Executor = executor::Null; -/// type Message = Message; +/// struct Hello; /// -/// fn new() -> (Self, Command<Message>) { -/// (Self::default(), Command::none()) +/// impl Application for Hello { +/// type Executor = executor::Default; +/// type Message = (); +/// type Flags = (); +/// +/// fn new(_flags: ()) -> (Hello, Command<Self::Message>) { +/// (Hello, Command::none()) /// } /// /// fn title(&self) -> String { -/// String::from("A simple counter") +/// String::from("A cool application") /// } /// -/// fn update(&mut self, message: Message) -> Command<Message> { -/// match message { -/// Message::IncrementPressed => { -/// self.value += 1; -/// } -/// Message::DecrementPressed => { -/// self.value -= 1; -/// } -/// } -/// +/// fn update(&mut self, _message: Self::Message) -> Command<Self::Message> { /// Command::none() /// } /// -/// fn view(&mut self) -> Element<Message> { -/// Column::new() -/// .push( -/// Button::new(&mut self.increment_button, Text::new("Increment")) -/// .on_press(Message::IncrementPressed), -/// ) -/// .push( -/// Text::new(self.value.to_string()).size(50), -/// ) -/// .push( -/// Button::new(&mut self.decrement_button, Text::new("Decrement")) -/// .on_press(Message::DecrementPressed), -/// ) -/// .into() +/// fn view(&mut self) -> Element<Self::Message> { +/// Text::new("Hello, world!").into() /// } /// } /// ``` pub trait Application: Sized { /// The [`Executor`] that will run commands and subscriptions. /// - /// The [`executor::Default`] can be a good starting point! + /// The [default executor] can be a good starting point! /// - /// [`Executor`]: trait.Executor.html - /// [`executor::Default`]: executor/struct.Default.html + /// [`Executor`]: Self::Executor + /// [default executor]: crate::executor::Default type Executor: Executor; /// The type of __messages__ your [`Application`] will produce. - /// - /// [`Application`]: trait.Application.html type Message: std::fmt::Debug + Send; - /// Initializes the [`Application`]. + /// 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`](struct.Command.html) 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. + /// 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. /// - /// [`Application`]: trait.Application.html - fn new() -> (Self, Command<Self::Message>); + /// [`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. - /// - /// [`Application`]: trait.Application.html fn title(&self) -> String; /// Handles a __message__ and updates the state of the [`Application`]. @@ -121,9 +127,6 @@ pub trait Application: Sized { /// this method. /// /// Any [`Command`] returned will be executed immediately in the background. - /// - /// [`Application`]: trait.Application.html - /// [`Command`]: struct.Command.html fn update(&mut self, message: Self::Message) -> Command<Self::Message>; /// Returns the event [`Subscription`] for the current state of the @@ -134,8 +137,6 @@ pub trait Application: Sized { /// [`update`](#tymethod.update). /// /// By default, this method returns an empty [`Subscription`]. - /// - /// [`Subscription`]: struct.Subscription.html fn subscription(&self) -> Subscription<Self::Message> { Subscription::none() } @@ -143,8 +144,6 @@ pub trait Application: Sized { /// Returns the widgets to display in the [`Application`]. /// /// These widgets can produce __messages__ based on user interaction. - /// - /// [`Application`]: trait.Application.html fn view(&mut self) -> Element<'_, Self::Message>; /// Returns the current [`Application`] mode. @@ -155,56 +154,99 @@ pub trait Application: Sized { /// Currently, the mode only has an effect in native platforms. /// /// By default, an application will run in windowed mode. - /// - /// [`Application`]: trait.Application.html fn mode(&self) -> window::Mode { window::Mode::Windowed } + /// Returns the background color of the [`Application`]. + /// + /// By default, it returns [`Color::WHITE`]. + fn background_color(&self) -> Color { + Color::WHITE + } + + /// Returns the scale factor 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`. + fn scale_factor(&self) -> f64 { + 1.0 + } + /// Runs the [`Application`]. /// - /// This method will take control of the current thread and __will NOT - /// return__. + /// On native platforms, this method will take control of the current thread + /// and __will NOT return__ unless there is an [`Error`] during startup. /// /// It should probably be that last thing you call in your `main` function. /// - /// [`Application`]: trait.Application.html - fn run(_settings: Settings) + /// [`Error`]: crate::Error + fn run(settings: Settings<Self::Flags>) -> crate::Result where Self: 'static, { #[cfg(not(target_arch = "wasm32"))] - <Instance<Self> as iced_winit::Application>::run( - _settings.into(), - iced_wgpu::Settings { - default_font: _settings.default_font, - antialiasing: if _settings.antialiasing { - Some(iced_wgpu::settings::Antialiasing::MSAAx4) + { + let renderer_settings = crate::renderer::Settings { + default_font: settings.default_font, + default_text_size: settings.default_text_size, + antialiasing: if settings.antialiasing { + Some(crate::renderer::settings::Antialiasing::MSAAx4) } else { None }, - ..iced_wgpu::Settings::default() - }, - ); + ..crate::renderer::Settings::default() + }; + + Ok(crate::runtime::application::run::< + Instance<Self>, + Self::Executor, + crate::renderer::window::Compositor, + >(settings.into(), renderer_settings)?) + } #[cfg(target_arch = "wasm32")] - <Instance<Self> as iced_web::Application>::run(); + { + <Instance<Self> as iced_web::Application>::run(settings.flags); + + Ok(()) + } } } struct Instance<A: Application>(A); #[cfg(not(target_arch = "wasm32"))] -impl<A> iced_winit::Application for Instance<A> +impl<A> iced_winit::Program for Instance<A> where A: Application, { - type Backend = iced_wgpu::window::Backend; - type Executor = A::Executor; + type Renderer = crate::renderer::Renderer; type Message = A::Message; - fn new() -> (Self, Command<A::Message>) { - let (app, command) = A::new(); + fn update(&mut self, message: Self::Message) -> Command<Self::Message> { + self.0.update(message) + } + + fn view(&mut self) -> Element<'_, Self::Message> { + self.0.view() + } +} + +#[cfg(not(target_arch = "wasm32"))] +impl<A> crate::runtime::Application for Instance<A> +where + A: Application, +{ + type Flags = A::Flags; + + fn new(flags: Self::Flags) -> (Self, Command<A::Message>) { + let (app, command) = A::new(flags); (Instance(app), command) } @@ -220,16 +262,16 @@ where } } - fn update(&mut self, message: Self::Message) -> Command<Self::Message> { - self.0.update(message) - } - fn subscription(&self) -> Subscription<Self::Message> { self.0.subscription() } - fn view(&mut self) -> Element<'_, Self::Message> { - self.0.view() + fn background_color(&self) -> Color { + self.0.background_color() + } + + fn scale_factor(&self) -> f64 { + self.0.scale_factor() } } @@ -238,11 +280,12 @@ impl<A> iced_web::Application for Instance<A> where A: Application, { - type Message = A::Message; type Executor = A::Executor; + type Message = A::Message; + type Flags = A::Flags; - fn new() -> (Self, Command<A::Message>) { - let (app, command) = A::new(); + fn new(flags: Self::Flags) -> (Self, Command<A::Message>) { + let (app, command) = A::new(flags); (Instance(app), command) } diff --git a/src/element.rs b/src/element.rs index e5356fb6..6f47c701 100644 --- a/src/element.rs +++ b/src/element.rs @@ -3,7 +3,7 @@ /// This is an alias of an `iced_native` element with a default `Renderer`. #[cfg(not(target_arch = "wasm32"))] pub type Element<'a, Message> = - iced_winit::Element<'a, Message, iced_wgpu::Renderer>; + crate::runtime::Element<'a, Message, crate::renderer::Renderer>; #[cfg(target_arch = "wasm32")] pub use iced_web::Element; diff --git a/src/error.rs b/src/error.rs new file mode 100644 index 00000000..31b87d17 --- /dev/null +++ b/src/error.rs @@ -0,0 +1,34 @@ +use iced_futures::futures; + +/// An error that occurred while running an application. +#[derive(Debug, thiserror::Error)] +pub enum Error { + /// The futures executor could not be created. + #[error("the futures executor could not be created")] + ExecutorCreationFailed(futures::io::Error), + + /// The application window could not be created. + #[error("the application window could not be created")] + WindowCreationFailed(Box<dyn std::error::Error>), + + /// A suitable graphics adapter or device could not be found. + #[error("a suitable graphics adapter or device could not be found")] + GraphicsAdapterNotFound, +} + +#[cfg(not(target_arch = "wasm32"))] +impl From<iced_winit::Error> for Error { + fn from(error: iced_winit::Error) -> Error { + match error { + iced_winit::Error::ExecutorCreationFailed(error) => { + Error::ExecutorCreationFailed(error) + } + iced_winit::Error::WindowCreationFailed(error) => { + Error::WindowCreationFailed(Box::new(error)) + } + iced_winit::Error::GraphicsAdapterNotFound => { + Error::GraphicsAdapterNotFound + } + } + } +} diff --git a/src/executor.rs b/src/executor.rs index b4be5264..0333bc1d 100644 --- a/src/executor.rs +++ b/src/executor.rs @@ -1,5 +1,5 @@ //! Choose your preferred executor to power your application. -pub use crate::common::{executor::Null, Executor}; +pub use crate::runtime::Executor; pub use platform::Default; @@ -7,13 +7,23 @@ pub use platform::Default; mod platform { use iced_futures::{executor, futures}; - #[cfg(feature = "tokio")] + #[cfg(feature = "tokio_old")] + type Executor = executor::TokioOld; + + #[cfg(all(not(feature = "tokio_old"), feature = "tokio"))] type Executor = executor::Tokio; - #[cfg(all(not(feature = "tokio"), feature = "async-std"))] + #[cfg(all( + not(any(feature = "tokio_old", feature = "tokio")), + feature = "async-std" + ))] type Executor = executor::AsyncStd; - #[cfg(not(any(feature = "tokio", feature = "async-std")))] + #[cfg(not(any( + feature = "tokio_old", + feature = "tokio", + feature = "async-std" + )))] type Executor = executor::ThreadPool; /// A default cross-platform executor. @@ -40,7 +50,7 @@ mod platform { } fn enter<R>(&self, f: impl FnOnce() -> R) -> R { - self.0.enter(f) + super::Executor::enter(&self.0, f) } } } @@ -51,7 +61,11 @@ mod platform { /// A default cross-platform executor. /// - /// - On native platforms, it will use `iced_futures::executor::ThreadPool`. + /// - On native platforms, it will use: + /// - `iced_futures::executor::Tokio` when the `tokio` feature is enabled. + /// - `iced_futures::executor::AsyncStd` when the `async-std` feature is + /// enabled. + /// - `iced_futures::executor::ThreadPool` otherwise. /// - On the Web, it will use `iced_futures::executor::WasmBindgen`. #[derive(Debug)] pub struct Default(WasmBindgen); @@ -64,5 +78,9 @@ mod platform { fn spawn(&self, future: impl futures::Future<Output = ()> + 'static) { self.0.spawn(future); } + + fn enter<R>(&self, f: impl FnOnce() -> R) -> R { + self.0.enter(f) + } } } diff --git a/src/keyboard.rs b/src/keyboard.rs new file mode 100644 index 00000000..2134a66b --- /dev/null +++ b/src/keyboard.rs @@ -0,0 +1,2 @@ +//! Listen and react to keyboard events. +pub use crate::runtime::keyboard::{Event, KeyCode, Modifiers}; @@ -30,7 +30,7 @@ //! [windowing shell]: https://github.com/hecrj/iced/tree/master/winit //! [`dodrio`]: https://github.com/fitzgen/dodrio //! [web runtime]: https://github.com/hecrj/iced/tree/master/web -//! [examples]: https://github.com/hecrj/iced/tree/master/examples +//! [examples]: https://github.com/hecrj/iced/tree/0.2/examples //! [repository]: https://github.com/hecrj/iced //! //! # Overview @@ -166,43 +166,79 @@ //! 1. Draw the resulting user interface. //! //! # Usage -//! Take a look at the [`Application`] trait, which streamlines all the process -//! described above for you! +//! The [`Application`] and [`Sandbox`] traits should get you started quickly, +//! streamlining all the process described above! //! //! [Elm]: https://elm-lang.org/ //! [The Elm Architecture]: https://guide.elm-lang.org/architecture/ -//! [examples]: https://github.com/hecrj/iced/tree/master/examples -//! [`Application`]: trait.Application.html #![deny(missing_docs)] #![deny(missing_debug_implementations)] #![deny(unused_results)] #![forbid(unsafe_code)] #![forbid(rust_2018_idioms)] +#![cfg_attr(docsrs, feature(doc_cfg))] mod application; mod element; +mod error; +mod result; mod sandbox; pub mod executor; +pub mod keyboard; +pub mod mouse; pub mod settings; pub mod widget; pub mod window; +#[cfg(all( + any(feature = "tokio", feature = "tokio_old", feature = "async-std"), + not(target_arch = "wasm32") +))] +#[cfg_attr( + docsrs, + doc(cfg(any( + feature = "tokio", + feature = "tokio_old", + feature = "async-std" + ))) +)] +pub mod time; + +#[cfg(all( + not(target_arch = "wasm32"), + not(feature = "glow"), + feature = "wgpu" +))] +use iced_winit as runtime; + +#[cfg(all(not(target_arch = "wasm32"), feature = "glow"))] +use iced_glutin as runtime; + +#[cfg(all( + not(target_arch = "wasm32"), + not(feature = "glow"), + feature = "wgpu" +))] +use iced_wgpu as renderer; + +#[cfg(all(not(target_arch = "wasm32"), feature = "glow"))] +use iced_glow as renderer; + +#[cfg(target_arch = "wasm32")] +use iced_web as runtime; + #[doc(no_inline)] pub use widget::*; pub use application::Application; pub use element::Element; +pub use error::Error; pub use executor::Executor; +pub use result::Result; pub use sandbox::Sandbox; pub use settings::Settings; -#[cfg(not(target_arch = "wasm32"))] -use iced_winit as common; - -#[cfg(target_arch = "wasm32")] -use iced_web as common; - -pub use common::{ +pub use runtime::{ futures, Align, Background, Color, Command, Font, HorizontalAlignment, - Length, Point, Size, Space, Subscription, Vector, VerticalAlignment, + Length, Point, Rectangle, Size, Subscription, Vector, VerticalAlignment, }; diff --git a/src/mouse.rs b/src/mouse.rs new file mode 100644 index 00000000..d61ed09a --- /dev/null +++ b/src/mouse.rs @@ -0,0 +1,2 @@ +//! Listen and react to mouse events. +pub use crate::runtime::mouse::{Button, Event, Interaction, ScrollDelta}; diff --git a/src/result.rs b/src/result.rs new file mode 100644 index 00000000..ef565bd6 --- /dev/null +++ b/src/result.rs @@ -0,0 +1,6 @@ +use crate::Error; + +/// The result of running an [`Application`]. +/// +/// [`Application`]: crate::Application +pub type Result = std::result::Result<(), Error>; diff --git a/src/sandbox.rs b/src/sandbox.rs index 2c0332ff..dbaa02f1 100644 --- a/src/sandbox.rs +++ b/src/sandbox.rs @@ -1,127 +1,143 @@ -use crate::{executor, Application, Command, Element, Settings, Subscription}; +use crate::{ + Application, Color, Command, Element, Error, Settings, Subscription, +}; /// A sandboxed [`Application`]. /// -/// A [`Sandbox`] is just an [`Application`] that cannot run any asynchronous -/// actions. +/// If you are a just getting started with the library, this trait offers a +/// simpler interface than [`Application`]. /// -/// If you do not need to leverage a [`Command`], you can use a [`Sandbox`] -/// instead of returning a [`Command::none`] everywhere. +/// Unlike an [`Application`], a [`Sandbox`] cannot run any asynchronous +/// actions or be initialized with some external flags. However, both traits +/// are very similar and upgrading from a [`Sandbox`] is very straightforward. /// -/// [`Application`]: trait.Application.html -/// [`Sandbox`]: trait.Sandbox.html -/// [`Command`]: struct.Command.html -/// [`Command::none`]: struct.Command.html#method.none +/// Therefore, it is recommended to always start by implementing this trait and +/// upgrade only once necessary. /// -/// # Example -/// We can use a [`Sandbox`] to run the [`Counter` example we implemented -/// before](index.html#overview), instead of an [`Application`]. We just need -/// to remove the use of [`Command`]: +/// # Examples +/// [The repository has a bunch of examples] that use the [`Sandbox`] trait: /// -/// ```no_run -/// use iced::{button, Button, Column, Element, Sandbox, Settings, Text}; +/// - [`bezier_tool`], a Paint-like tool for drawing Bézier curves using +/// [`lyon`]. +/// - [`counter`], the classic counter example explained in [the overview]. +/// - [`custom_widget`], a demonstration of how to build a custom widget that +/// draws a circle. +/// - [`geometry`], a custom widget showcasing how to draw geometry with the +/// `Mesh2D` primitive in [`iced_wgpu`]. +/// - [`pane_grid`], a grid of panes that can be split, resized, and +/// reorganized. +/// - [`progress_bar`], a simple progress bar that can be filled by using a +/// slider. +/// - [`styling`], an example showcasing custom styling with a light and dark +/// theme. +/// - [`svg`], an application that renders the [Ghostscript Tiger] by leveraging +/// the [`Svg` widget]. +/// - [`tour`], a simple UI tour that can run both on native platforms and the +/// web! /// -/// pub fn main() { -/// Counter::run(Settings::default()) -/// } +/// [The repository has a bunch of examples]: https://github.com/hecrj/iced/tree/0.2/examples +/// [`bezier_tool`]: https://github.com/hecrj/iced/tree/0.2/examples/bezier_tool +/// [`counter`]: https://github.com/hecrj/iced/tree/0.2/examples/counter +/// [`custom_widget`]: https://github.com/hecrj/iced/tree/0.2/examples/custom_widget +/// [`geometry`]: https://github.com/hecrj/iced/tree/0.2/examples/geometry +/// [`pane_grid`]: https://github.com/hecrj/iced/tree/0.2/examples/pane_grid +/// [`progress_bar`]: https://github.com/hecrj/iced/tree/0.2/examples/progress_bar +/// [`styling`]: https://github.com/hecrj/iced/tree/0.2/examples/styling +/// [`svg`]: https://github.com/hecrj/iced/tree/0.2/examples/svg +/// [`tour`]: https://github.com/hecrj/iced/tree/0.2/examples/tour +/// [`lyon`]: https://github.com/nical/lyon +/// [the overview]: index.html#overview +/// [`iced_wgpu`]: https://github.com/hecrj/iced/tree/0.2/wgpu +/// [`Svg` widget]: crate::widget::Svg +/// [Ghostscript Tiger]: https://commons.wikimedia.org/wiki/File:Ghostscript_Tiger.svg /// -/// #[derive(Default)] -/// struct Counter { -/// value: i32, -/// increment_button: button::State, -/// decrement_button: button::State, -/// } +/// ## A simple "Hello, world!" +/// +/// If you just want to get started, here is a simple [`Sandbox`] that +/// says "Hello, world!": /// -/// #[derive(Debug, Clone, Copy)] -/// enum Message { -/// IncrementPressed, -/// DecrementPressed, +/// ```no_run +/// use iced::{Element, Sandbox, Settings, Text}; +/// +/// pub fn main() -> iced::Result { +/// Hello::run(Settings::default()) /// } /// -/// impl Sandbox for Counter { -/// type Message = Message; +/// struct Hello; +/// +/// impl Sandbox for Hello { +/// type Message = (); /// -/// fn new() -> Self { -/// Self::default() +/// fn new() -> Hello { +/// Hello /// } /// /// fn title(&self) -> String { -/// String::from("A simple counter") +/// String::from("A cool application") /// } /// -/// fn update(&mut self, message: Message) { -/// match message { -/// Message::IncrementPressed => { -/// self.value += 1; -/// } -/// Message::DecrementPressed => { -/// self.value -= 1; -/// } -/// } +/// fn update(&mut self, _message: Self::Message) { +/// // This application has no interactions /// } /// -/// fn view(&mut self) -> Element<Message> { -/// Column::new() -/// .push( -/// Button::new(&mut self.increment_button, Text::new("Increment")) -/// .on_press(Message::IncrementPressed), -/// ) -/// .push( -/// Text::new(self.value.to_string()).size(50), -/// ) -/// .push( -/// Button::new(&mut self.decrement_button, Text::new("Decrement")) -/// .on_press(Message::DecrementPressed), -/// ) -/// .into() +/// fn view(&mut self) -> Element<Self::Message> { +/// Text::new("Hello, world!").into() /// } /// } /// ``` pub trait Sandbox { /// The type of __messages__ your [`Sandbox`] will produce. - /// - /// [`Sandbox`]: trait.Sandbox.html type Message: std::fmt::Debug + Send; /// Initializes the [`Sandbox`]. /// /// Here is where you should return the initial state of your app. - /// - /// [`Sandbox`]: trait.Sandbox.html fn new() -> Self; /// Returns the current title of the [`Sandbox`]. /// /// This title can be dynamic! The runtime will automatically update the /// title of your application when necessary. - /// - /// [`Sandbox`]: trait.Sandbox.html fn title(&self) -> String; /// Handles a __message__ and updates the state of the [`Sandbox`]. /// /// This is where you define your __update logic__. All the __messages__, /// produced by user interactions, will be handled by this method. - /// - /// [`Sandbox`]: trait.Sandbox.html fn update(&mut self, message: Self::Message); /// Returns the widgets to display in the [`Sandbox`]. /// /// These widgets can produce __messages__ based on user interaction. - /// - /// [`Sandbox`]: trait.Sandbox.html fn view(&mut self) -> Element<'_, Self::Message>; + /// Returns the background color of the [`Sandbox`]. + /// + /// By default, it returns [`Color::WHITE`]. + fn background_color(&self) -> Color { + Color::WHITE + } + + /// Returns the scale factor of the [`Sandbox`]. + /// + /// 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`. + fn scale_factor(&self) -> f64 { + 1.0 + } + /// Runs the [`Sandbox`]. /// - /// This method will take control of the current thread and __will NOT - /// return__. + /// On native platforms, this method will take control of the current thread + /// and __will NOT return__. /// /// It should probably be that last thing you call in your `main` function. - /// - /// [`Sandbox`]: trait.Sandbox.html - fn run(settings: Settings) + fn run(settings: Settings<()>) -> Result<(), Error> where Self: 'static + Sized, { @@ -133,10 +149,11 @@ impl<T> Application for T where T: Sandbox, { - type Executor = executor::Null; + type Executor = crate::runtime::executor::Null; + type Flags = (); type Message = T::Message; - fn new() -> (Self, Command<T::Message>) { + fn new(_flags: ()) -> (Self, Command<T::Message>) { (T::new(), Command::none()) } @@ -157,4 +174,12 @@ where fn view(&mut self) -> Element<'_, T::Message> { T::view(self) } + + fn background_color(&self) -> Color { + T::background_color(self) + } + + fn scale_factor(&self) -> f64 { + T::scale_factor(self) + } } diff --git a/src/settings.rs b/src/settings.rs index 32ec583c..c82a1354 100644 --- a/src/settings.rs +++ b/src/settings.rs @@ -2,41 +2,79 @@ use crate::window; /// The settings of an application. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] -pub struct Settings { +#[derive(Debug, Clone)] +pub struct Settings<Flags> { /// The window settings. /// /// They will be ignored on the Web. - /// - /// [`Window`]: struct.Window.html pub window: window::Settings, + /// The data needed to initialize an [`Application`]. + /// + /// [`Application`]: crate::Application + pub flags: Flags, + /// The bytes of the font that will be used by default. /// /// If `None` is provided, a default system font will be chosen. // TODO: Add `name` for web compatibility pub default_font: Option<&'static [u8]>, + /// The text size that will be used by default. + /// + /// The default value is 20. + pub default_text_size: u16, + /// If set to true, the renderer will try to perform antialiasing for some /// primitives. /// /// Enabling it can produce a smoother result in some widgets, like the - /// `Canvas`, at a performance cost. + /// [`Canvas`], at a performance cost. /// /// By default, it is disabled. + /// + /// [`Canvas`]: crate::widget::Canvas pub antialiasing: bool, } +impl<Flags> Settings<Flags> { + /// Initialize [`Application`] settings using the given data. + /// + /// [`Application`]: crate::Application + pub fn with_flags(flags: Flags) -> Self { + let default_settings = Settings::<()>::default(); + + Self { + flags, + antialiasing: default_settings.antialiasing, + default_font: default_settings.default_font, + default_text_size: default_settings.default_text_size, + window: default_settings.window, + } + } +} + +impl<Flags> Default for Settings<Flags> +where + Flags: Default, +{ + fn default() -> Self { + Self { + flags: Default::default(), + antialiasing: Default::default(), + default_font: Default::default(), + default_text_size: 20, + window: Default::default(), + } + } +} + #[cfg(not(target_arch = "wasm32"))] -impl From<Settings> for iced_winit::Settings { - fn from(settings: Settings) -> iced_winit::Settings { +impl<Flags> From<Settings<Flags>> for iced_winit::Settings<Flags> { + fn from(settings: Settings<Flags>) -> iced_winit::Settings<Flags> { iced_winit::Settings { - window: iced_winit::settings::Window { - size: settings.window.size, - resizable: settings.window.resizable, - decorations: settings.window.decorations, - platform_specific: Default::default(), - }, + window: settings.window.into(), + flags: settings.flags, } } } diff --git a/src/time.rs b/src/time.rs new file mode 100644 index 00000000..b8432895 --- /dev/null +++ b/src/time.rs @@ -0,0 +1,12 @@ +//! Listen and react to time. +use crate::Subscription; + +/// Returns a [`Subscription`] that produces messages at a set interval. +/// +/// The first message is produced after a `duration`, and then continues to +/// produce more messages every `duration` after that. +pub fn every( + duration: std::time::Duration, +) -> Subscription<std::time::Instant> { + iced_futures::time::every(duration) +} diff --git a/src/widget.rs b/src/widget.rs index 7d3a1cef..b9b65499 100644 --- a/src/widget.rs +++ b/src/widget.rs @@ -13,43 +13,54 @@ //! //! These widgets have their own module with a `State` type. For instance, a //! [`TextInput`] has some [`text_input::State`]. -//! -//! [`TextInput`]: text_input/struct.TextInput.html -//! [`text_input::State`]: text_input/struct.State.html #[cfg(not(target_arch = "wasm32"))] mod platform { - pub use iced_wgpu::widget::*; + pub use crate::renderer::widget::{ + button, checkbox, container, pane_grid, pick_list, progress_bar, radio, + rule, scrollable, slider, text_input, Column, Row, Space, Text, + }; + + #[cfg(any(feature = "canvas", feature = "glow_canvas"))] + #[cfg_attr( + docsrs, + doc(cfg(any(feature = "canvas", feature = "glow_canvas"))) + )] + pub use crate::renderer::widget::canvas; + + #[cfg(any(feature = "qr_code", feature = "glow_qr_code"))] + #[cfg_attr( + docsrs, + doc(cfg(any(feature = "qr_code", feature = "glow_qr_code"))) + )] + pub use crate::renderer::widget::qr_code; + #[cfg_attr(docsrs, doc(cfg(feature = "image")))] pub mod image { //! Display images in your user interface. - pub use iced_winit::image::{Handle, Image}; + pub use crate::runtime::image::{Handle, Image}; } + #[cfg_attr(docsrs, doc(cfg(feature = "svg")))] pub mod svg { //! Display vector graphics in your user interface. - pub use iced_winit::svg::{Handle, Svg}; + pub use crate::runtime::svg::{Handle, Svg}; } - pub use iced_winit::Text; - #[doc(no_inline)] pub use { button::Button, checkbox::Checkbox, container::Container, image::Image, - progress_bar::ProgressBar, radio::Radio, scrollable::Scrollable, - slider::Slider, svg::Svg, text_input::TextInput, + pane_grid::PaneGrid, pick_list::PickList, progress_bar::ProgressBar, + radio::Radio, rule::Rule, scrollable::Scrollable, slider::Slider, + svg::Svg, text_input::TextInput, }; - /// A container that distributes its contents vertically. - /// - /// This is an alias of an `iced_native` column with a default `Renderer`. - pub type Column<'a, Message> = - iced_winit::Column<'a, Message, iced_wgpu::Renderer>; - - /// A container that distributes its contents horizontally. - /// - /// This is an alias of an `iced_native` row with a default `Renderer`. - pub type Row<'a, Message> = - iced_winit::Row<'a, Message, iced_wgpu::Renderer>; + #[cfg(any(feature = "canvas", feature = "glow_canvas"))] + #[doc(no_inline)] + pub use canvas::Canvas; + + #[cfg(any(feature = "qr_code", feature = "glow_qr_code"))] + #[doc(no_inline)] + pub use qr_code::QRCode; } #[cfg(target_arch = "wasm32")] diff --git a/src/window.rs b/src/window.rs index 54ea2a02..a2883b62 100644 --- a/src/window.rs +++ b/src/window.rs @@ -2,5 +2,8 @@ mod mode; mod settings; +pub mod icon; + +pub use icon::Icon; pub use mode::Mode; pub use settings::Settings; diff --git a/src/window/icon.rs b/src/window/icon.rs new file mode 100644 index 00000000..0d27b00e --- /dev/null +++ b/src/window/icon.rs @@ -0,0 +1,132 @@ +//! Attach an icon to the window of your application. +use std::fmt; +use std::io; + +/// The icon of a window. +#[cfg(not(target_arch = "wasm32"))] +#[derive(Debug, Clone)] +pub struct Icon(iced_winit::winit::window::Icon); + +/// The icon of a window. +#[cfg(target_arch = "wasm32")] +#[derive(Debug, Clone)] +pub struct Icon; + +impl Icon { + /// Creates an icon from 32bpp RGBA data. + #[cfg(not(target_arch = "wasm32"))] + pub fn from_rgba( + rgba: Vec<u8>, + width: u32, + height: u32, + ) -> Result<Self, Error> { + let raw = + iced_winit::winit::window::Icon::from_rgba(rgba, width, height)?; + + Ok(Icon(raw)) + } + + /// Creates an icon from 32bpp RGBA data. + #[cfg(target_arch = "wasm32")] + pub fn from_rgba( + _rgba: Vec<u8>, + _width: u32, + _height: u32, + ) -> Result<Self, Error> { + Ok(Icon) + } +} + +/// An error produced when using `Icon::from_rgba` with invalid arguments. +#[derive(Debug)] +pub enum Error { + /// The provided RGBA data isn't divisble by 4. + /// + /// Therefore, it cannot be safely interpreted as 32bpp RGBA pixels. + InvalidData { + /// The length of the provided RGBA data. + byte_count: usize, + }, + + /// The number of RGBA pixels does not match the provided dimensions. + DimensionsMismatch { + /// The provided width. + width: u32, + /// The provided height. + height: u32, + /// The amount of pixels of the provided RGBA data. + pixel_count: usize, + }, + + /// The underlying OS failed to create the icon. + OsError(io::Error), +} + +#[cfg(not(target_arch = "wasm32"))] +impl From<iced_winit::winit::window::BadIcon> for Error { + fn from(error: iced_winit::winit::window::BadIcon) -> Self { + use iced_winit::winit::window::BadIcon; + + match error { + BadIcon::ByteCountNotDivisibleBy4 { byte_count } => { + Error::InvalidData { byte_count } + } + BadIcon::DimensionsVsPixelCount { + width, + height, + pixel_count, + .. + } => Error::DimensionsMismatch { + width, + height, + pixel_count, + }, + BadIcon::OsError(os_error) => Error::OsError(os_error), + } + } +} + +#[cfg(not(target_arch = "wasm32"))] +impl From<Icon> for iced_winit::winit::window::Icon { + fn from(icon: Icon) -> Self { + icon.0 + } +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Error::InvalidData { byte_count } => { + write!(f, + "The provided RGBA data (with length {:?}) isn't divisble by \ + 4. Therefore, it cannot be safely interpreted as 32bpp RGBA \ + pixels.", + byte_count, + ) + } + Error::DimensionsMismatch { + width, + height, + pixel_count, + } => { + write!(f, + "The number of RGBA pixels ({:?}) does not match the provided \ + dimensions ({:?}x{:?}).", + pixel_count, width, height, + ) + } + Error::OsError(e) => write!( + f, + "The underlying OS failed to create the window \ + icon: {:?}", + e + ), + } + } +} + +impl std::error::Error for Error { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + Some(self) + } +} diff --git a/src/window/settings.rs b/src/window/settings.rs index a31d2af2..6b5d2985 100644 --- a/src/window/settings.rs +++ b/src/window/settings.rs @@ -1,22 +1,61 @@ +use crate::window::Icon; + /// The window settings of an application. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone)] pub struct Settings { - /// The size of the window. + /// The initial size of the window. pub size: (u32, u32), + /// The minimum size of the window. + pub min_size: Option<(u32, u32)>, + + /// The maximum size of the window. + pub max_size: Option<(u32, u32)>, + /// Whether the window should be resizable or not. pub resizable: bool, /// Whether the window should have a border, a title bar, etc. or not. pub decorations: bool, + + /// Whether the window should be transparent. + pub transparent: bool, + + /// Whether the window will always be on top of other windows. + pub always_on_top: bool, + + /// The icon of the window. + pub icon: Option<Icon>, } impl Default for Settings { fn default() -> Settings { Settings { size: (1024, 768), + min_size: None, + max_size: None, resizable: true, decorations: true, + transparent: false, + always_on_top: false, + icon: None, + } + } +} + +#[cfg(not(target_arch = "wasm32"))] +impl From<Settings> for iced_winit::settings::Window { + fn from(settings: Settings) -> Self { + Self { + size: settings.size, + min_size: settings.min_size, + max_size: settings.max_size, + resizable: settings.resizable, + decorations: settings.decorations, + transparent: settings.transparent, + always_on_top: settings.always_on_top, + icon: settings.icon.map(Icon::into), + platform_specific: Default::default(), } } } |