Merge branch 'master' into beacon

This commit is contained in:
Héctor Ramón Jiménez 2025-03-04 19:11:37 +01:00
commit 8bd5de72ea
No known key found for this signature in database
GPG key ID: 7CC46565708259A7
371 changed files with 33138 additions and 12950 deletions

View file

@ -1,5 +1,19 @@
//! Leverage advanced concepts like custom widgets.
pub use crate::application::Application;
pub mod subscription {
//! Write your own subscriptions.
pub use crate::runtime::futures::subscription::{
Event, EventStream, Hasher, MacOS, PlatformSpecific, Recipe,
from_recipe, into_recipes,
};
}
pub mod widget {
//! Create custom widgets and operate on them.
pub use crate::core::widget::*;
pub use crate::runtime::task::widget as operate;
}
pub use crate::core::Shell;
pub use crate::core::clipboard::{self, Clipboard};
pub use crate::core::image;
pub use crate::core::layout::{self, Layout};
@ -8,14 +22,8 @@ pub use crate::core::overlay::{self, Overlay};
pub use crate::core::renderer::{self, Renderer};
pub use crate::core::svg;
pub use crate::core::text::{self, Text};
pub use crate::core::widget::{self, Widget};
pub use crate::core::Shell;
pub use crate::renderer::graphics;
pub use iced_debug as debug;
pub mod subscription {
//! Write your own subscriptions.
pub use crate::runtime::futures::subscription::{
EventStream, Hasher, Recipe,
};
}
pub use widget::Widget;

View file

@ -1,287 +1,485 @@
//! Build interactive cross-platform applications.
use crate::core::text;
use crate::graphics::compositor;
use crate::shell::application;
use crate::{Command, Element, Executor, Settings, Subscription};
//! Create and run iced applications step by step.
//!
//! # Example
//! ```no_run
//! use iced::widget::{button, column, text, Column};
//! use iced::Theme;
//!
//! pub fn main() -> iced::Result {
//! iced::application("A counter", update, view)
//! .theme(|_| Theme::Dark)
//! .centered()
//! .run()
//! }
//!
//! #[derive(Debug, Clone)]
//! enum Message {
//! Increment,
//! }
//!
//! fn update(value: &mut u64, message: Message) {
//! match message {
//! Message::Increment => *value += 1,
//! }
//! }
//!
//! fn view(value: &u64) -> Column<Message> {
//! column![
//! text(value),
//! button("+").on_press(Message::Increment),
//! ]
//! }
//! ```
use crate::program::{self, Program};
use crate::theme;
use crate::window;
use crate::{
Element, Executor, Font, Result, Settings, Size, Subscription, Task,
};
pub use application::{Appearance, DefaultStyle};
use std::borrow::Cow;
/// An interactive cross-platform application.
///
/// This trait is the main entrypoint of Iced. Once implemented, you can run
/// your GUI application by simply calling [`run`](#method.run).
///
/// - On native platforms, it will run in its own window.
/// - On the web, it will take control of the `<title>` and the `<body>` of the
/// document.
///
/// 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`.
///
/// # Examples
/// [The repository has a bunch of examples] that use the [`Application`] trait:
///
/// - [`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].
///
/// [The repository has a bunch of examples]: https://github.com/iced-rs/iced/tree/0.12/examples
/// [`clock`]: https://github.com/iced-rs/iced/tree/0.12/examples/clock
/// [`download_progress`]: https://github.com/iced-rs/iced/tree/0.12/examples/download_progress
/// [`events`]: https://github.com/iced-rs/iced/tree/0.12/examples/events
/// [`game_of_life`]: https://github.com/iced-rs/iced/tree/0.12/examples/game_of_life
/// [`pokedex`]: https://github.com/iced-rs/iced/tree/0.12/examples/pokedex
/// [`solar_system`]: https://github.com/iced-rs/iced/tree/0.12/examples/solar_system
/// [`stopwatch`]: https://github.com/iced-rs/iced/tree/0.12/examples/stopwatch
/// [`todos`]: https://github.com/iced-rs/iced/tree/0.12/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!":
/// Creates an iced [`Application`] given its title, update, and view logic.
///
/// # Example
/// ```no_run
/// use iced::advanced::Application;
/// use iced::executor;
/// use iced::{Command, Element, Settings, Theme, Renderer};
/// use iced::widget::{button, column, text, Column};
///
/// pub fn main() -> iced::Result {
/// Hello::run(Settings::default())
/// iced::application("A counter", update, view).run()
/// }
///
/// struct Hello;
/// #[derive(Debug, Clone)]
/// enum Message {
/// Increment,
/// }
///
/// impl Application for Hello {
/// type Executor = executor::Default;
/// type Flags = ();
/// type Message = ();
/// type Theme = Theme;
/// type Renderer = Renderer;
///
/// fn new(_flags: ()) -> (Hello, Command<Self::Message>) {
/// (Hello, Command::none())
/// fn update(value: &mut u64, message: Message) {
/// match message {
/// Message::Increment => *value += 1,
/// }
/// }
///
/// fn title(&self) -> String {
/// String::from("A cool application")
/// }
///
/// fn update(&mut self, _message: Self::Message) -> Command<Self::Message> {
/// Command::none()
/// }
///
/// fn view(&self) -> Element<Self::Message> {
/// "Hello, world!".into()
/// }
/// fn view(value: &u64) -> Column<Message> {
/// column![
/// text(value),
/// button("+").on_press(Message::Increment),
/// ]
/// }
/// ```
pub trait Application: Sized
pub fn application<State, Message, Theme, Renderer>(
title: impl Title<State>,
update: impl Update<State, Message>,
view: impl for<'a> self::View<'a, State, Message, Theme, Renderer>,
) -> Application<impl Program<State = State, Message = Message, Theme = Theme>>
where
Self::Theme: DefaultStyle,
State: 'static,
Message: Send + std::fmt::Debug + 'static,
Theme: Default + theme::Base,
Renderer: program::Renderer,
{
/// 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;
use std::marker::PhantomData;
/// The type of __messages__ your [`Application`] will produce.
type Message: std::fmt::Debug + Send;
/// The theme of your [`Application`].
type Theme: Default;
/// The renderer of your [`Application`].
type Renderer: text::Renderer + compositor::Default;
/// The data needed to initialize your [`Application`].
type Flags;
/// Returns the unique name of the [`Application`].
fn name() -> &'static str {
std::any::type_name::<Self>()
struct Instance<State, Message, Theme, Renderer, Update, View> {
update: Update,
view: View,
_state: PhantomData<State>,
_message: PhantomData<Message>,
_theme: PhantomData<Theme>,
_renderer: PhantomData<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.
///
/// [`run`]: Self::run
fn new(flags: Self::Flags) -> (Self, Command<Self::Message>);
impl<State, Message, Theme, Renderer, Update, View> Program
for Instance<State, Message, Theme, Renderer, Update, View>
where
Message: Send + std::fmt::Debug + 'static,
Theme: Default + theme::Base,
Renderer: program::Renderer,
Update: self::Update<State, Message>,
View: for<'a> self::View<'a, State, Message, Theme, Renderer>,
{
type State = State;
type Message = Message;
type Theme = Theme;
type Renderer = Renderer;
type Executor = iced_futures::backend::default::Executor;
/// 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) -> String;
fn update(
&self,
state: &mut Self::State,
message: Self::Message,
) -> Task<Self::Message> {
self.update.update(state, message).into()
}
/// 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 widgets to display in the [`Application`].
///
/// These widgets can produce __messages__ based on user interaction.
fn view(&self) -> Element<'_, Self::Message, Self::Theme, Self::Renderer>;
/// Returns the current [`Theme`] of the [`Application`].
///
/// [`Theme`]: Self::Theme
fn theme(&self) -> Self::Theme {
Self::Theme::default()
fn view<'a>(
&self,
state: &'a Self::State,
_window: window::Id,
) -> Element<'a, Self::Message, Self::Theme, Self::Renderer> {
self.view.view(state).into()
}
}
/// Returns the current [`Appearance`] of the [`Application`].
fn style(&self, theme: &Self::Theme) -> Appearance {
theme.default_style()
Application {
raw: Instance {
update,
view,
_state: PhantomData,
_message: PhantomData,
_theme: PhantomData,
_renderer: PhantomData,
},
settings: Settings::default(),
window: window::Settings::default(),
}
.title(title)
}
/// 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 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
}
/// The underlying definition and configuration of an iced application.
///
/// You can use this API to create and run iced applications
/// step by step—without coupling your logic to a trait
/// or a specific type.
///
/// You can create an [`Application`] with the [`application`] helper.
#[derive(Debug)]
pub struct Application<P: Program> {
raw: P,
settings: Settings,
window: window::Settings,
}
impl<P: Program> Application<P> {
/// Runs the [`Application`].
///
/// On native platforms, this method will take control of the current thread
/// until the [`Application`] exits.
/// The state of the [`Application`] must implement [`Default`].
/// If your state does not implement [`Default`], use [`run_with`]
/// instead.
///
/// 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
/// [`run_with`]: Self::run_with
pub fn run(self) -> Result
where
Self: 'static,
P::State: Default,
{
#[allow(clippy::needless_update)]
let renderer_settings = crate::graphics::Settings {
default_font: settings.default_font,
default_text_size: settings.default_text_size,
antialiasing: if settings.antialiasing {
Some(crate::graphics::Antialiasing::MSAAx4)
} else {
None
self.raw.run(self.settings, Some(self.window))
}
/// Runs the [`Application`] with a closure that creates the initial state.
pub fn run_with<I>(self, initialize: I) -> Result
where
Self: 'static,
I: FnOnce() -> (P::State, Task<P::Message>) + 'static,
{
self.raw
.run_with(self.settings, Some(self.window), initialize)
}
/// Sets the [`Settings`] that will be used to run the [`Application`].
pub fn settings(self, settings: Settings) -> Self {
Self { settings, ..self }
}
/// Sets the [`Settings::antialiasing`] of the [`Application`].
pub fn antialiasing(self, antialiasing: bool) -> Self {
Self {
settings: Settings {
antialiasing,
..self.settings
},
..crate::graphics::Settings::default()
};
..self
}
}
Ok(crate::shell::application::run::<
Instance<Self>,
Self::Executor,
<Self::Renderer as compositor::Default>::Compositor,
>(settings.into(), renderer_settings)?)
/// Sets the default [`Font`] of the [`Application`].
pub fn default_font(self, default_font: Font) -> Self {
Self {
settings: Settings {
default_font,
..self.settings
},
..self
}
}
/// Adds a font to the list of fonts that will be loaded at the start of the [`Application`].
pub fn font(mut self, font: impl Into<Cow<'static, [u8]>>) -> Self {
self.settings.fonts.push(font.into());
self
}
/// Sets the [`window::Settings`] of the [`Application`].
///
/// Overwrites any previous [`window::Settings`].
pub fn window(self, window: window::Settings) -> Self {
Self { window, ..self }
}
/// Sets the [`window::Settings::position`] to [`window::Position::Centered`] in the [`Application`].
pub fn centered(self) -> Self {
Self {
window: window::Settings {
position: window::Position::Centered,
..self.window
},
..self
}
}
/// Sets the [`window::Settings::exit_on_close_request`] of the [`Application`].
pub fn exit_on_close_request(self, exit_on_close_request: bool) -> Self {
Self {
window: window::Settings {
exit_on_close_request,
..self.window
},
..self
}
}
/// Sets the [`window::Settings::size`] of the [`Application`].
pub fn window_size(self, size: impl Into<Size>) -> Self {
Self {
window: window::Settings {
size: size.into(),
..self.window
},
..self
}
}
/// Sets the [`window::Settings::transparent`] of the [`Application`].
pub fn transparent(self, transparent: bool) -> Self {
Self {
window: window::Settings {
transparent,
..self.window
},
..self
}
}
/// Sets the [`window::Settings::resizable`] of the [`Application`].
pub fn resizable(self, resizable: bool) -> Self {
Self {
window: window::Settings {
resizable,
..self.window
},
..self
}
}
/// Sets the [`window::Settings::decorations`] of the [`Application`].
pub fn decorations(self, decorations: bool) -> Self {
Self {
window: window::Settings {
decorations,
..self.window
},
..self
}
}
/// Sets the [`window::Settings::position`] of the [`Application`].
pub fn position(self, position: window::Position) -> Self {
Self {
window: window::Settings {
position,
..self.window
},
..self
}
}
/// Sets the [`window::Settings::level`] of the [`Application`].
pub fn level(self, level: window::Level) -> Self {
Self {
window: window::Settings {
level,
..self.window
},
..self
}
}
/// Sets the [`Title`] of the [`Application`].
pub(crate) fn title(
self,
title: impl Title<P::State>,
) -> Application<
impl Program<State = P::State, Message = P::Message, Theme = P::Theme>,
> {
Application {
raw: program::with_title(self.raw, move |state, _window| {
title.title(state)
}),
settings: self.settings,
window: self.window,
}
}
/// Sets the subscription logic of the [`Application`].
pub fn subscription(
self,
f: impl Fn(&P::State) -> Subscription<P::Message>,
) -> Application<
impl Program<State = P::State, Message = P::Message, Theme = P::Theme>,
> {
Application {
raw: program::with_subscription(self.raw, f),
settings: self.settings,
window: self.window,
}
}
/// Sets the theme logic of the [`Application`].
pub fn theme(
self,
f: impl Fn(&P::State) -> P::Theme,
) -> Application<
impl Program<State = P::State, Message = P::Message, Theme = P::Theme>,
> {
Application {
raw: program::with_theme(self.raw, move |state, _window| f(state)),
settings: self.settings,
window: self.window,
}
}
/// Sets the style logic of the [`Application`].
pub fn style(
self,
f: impl Fn(&P::State, &P::Theme) -> theme::Style,
) -> Application<
impl Program<State = P::State, Message = P::Message, Theme = P::Theme>,
> {
Application {
raw: program::with_style(self.raw, f),
settings: self.settings,
window: self.window,
}
}
/// Sets the scale factor of the [`Application`].
pub fn scale_factor(
self,
f: impl Fn(&P::State) -> f64,
) -> Application<
impl Program<State = P::State, Message = P::Message, Theme = P::Theme>,
> {
Application {
raw: program::with_scale_factor(self.raw, move |state, _window| {
f(state)
}),
settings: self.settings,
window: self.window,
}
}
/// Sets the executor of the [`Application`].
pub fn executor<E>(
self,
) -> Application<
impl Program<State = P::State, Message = P::Message, Theme = P::Theme>,
>
where
E: Executor,
{
Application {
raw: program::with_executor::<P, E>(self.raw),
settings: self.settings,
window: self.window,
}
}
}
struct Instance<A>(A)
where
A: Application,
A::Theme: DefaultStyle;
/// The title logic of some [`Application`].
///
/// This trait is implemented both for `&static str` and
/// any closure `Fn(&State) -> String`.
///
/// This trait allows the [`application`] builder to take any of them.
pub trait Title<State> {
/// Produces the title of the [`Application`].
fn title(&self, state: &State) -> String;
}
impl<A> crate::runtime::Program for Instance<A>
impl<State> Title<State> for &'static str {
fn title(&self, _state: &State) -> String {
self.to_string()
}
}
impl<T, State> Title<State> for T
where
A: Application,
A::Theme: DefaultStyle,
T: Fn(&State) -> String,
{
type Message = A::Message;
type Theme = A::Theme;
type Renderer = A::Renderer;
fn update(&mut self, message: Self::Message) -> Command<Self::Message> {
self.0.update(message)
}
fn view(&self) -> Element<'_, Self::Message, Self::Theme, Self::Renderer> {
self.0.view()
fn title(&self, state: &State) -> String {
self(state)
}
}
impl<A> application::Application for Instance<A>
/// The update logic of some [`Application`].
///
/// This trait allows the [`application`] builder to take any closure that
/// returns any `Into<Task<Message>>`.
pub trait Update<State, Message> {
/// Processes the message and updates the state of the [`Application`].
fn update(
&self,
state: &mut State,
message: Message,
) -> impl Into<Task<Message>>;
}
impl<State, Message> Update<State, Message> for () {
fn update(
&self,
_state: &mut State,
_message: Message,
) -> impl Into<Task<Message>> {
}
}
impl<T, State, Message, C> Update<State, Message> for T
where
A: Application,
A::Theme: DefaultStyle,
T: Fn(&mut State, Message) -> C,
C: Into<Task<Message>>,
{
type Flags = A::Flags;
fn name() -> &'static str {
A::name()
}
fn new(flags: Self::Flags) -> (Self, Command<A::Message>) {
let (app, command) = A::new(flags);
(Instance(app), command)
}
fn title(&self) -> String {
self.0.title()
}
fn theme(&self) -> A::Theme {
self.0.theme()
}
fn style(&self, theme: &A::Theme) -> Appearance {
self.0.style(theme)
}
fn subscription(&self) -> Subscription<Self::Message> {
self.0.subscription()
}
fn scale_factor(&self) -> f64 {
self.0.scale_factor()
fn update(
&self,
state: &mut State,
message: Message,
) -> impl Into<Task<Message>> {
self(state, message)
}
}
/// The view logic of some [`Application`].
///
/// This trait allows the [`application`] builder to take any closure that
/// returns any `Into<Element<'_, Message>>`.
pub trait View<'a, State, Message, Theme, Renderer> {
/// Produces the widget of the [`Application`].
fn view(
&self,
state: &'a State,
) -> impl Into<Element<'a, Message, Theme, Renderer>>;
}
impl<'a, T, State, Message, Theme, Renderer, Widget>
View<'a, State, Message, Theme, Renderer> for T
where
T: Fn(&'a State) -> Widget,
State: 'static,
Widget: Into<Element<'a, Message, Theme, Renderer>>,
{
fn view(
&self,
state: &'a State,
) -> impl Into<Element<'a, Message, Theme, Renderer>> {
self(state)
}
}

295
src/daemon.rs Normal file
View file

@ -0,0 +1,295 @@
//! Create and run daemons that run in the background.
use crate::application;
use crate::program::{self, Program};
use crate::theme;
use crate::window;
use crate::{Element, Executor, Font, Result, Settings, Subscription, Task};
use std::borrow::Cow;
/// Creates an iced [`Daemon`] given its title, update, and view logic.
///
/// A [`Daemon`] will not open a window by default, but will run silently
/// instead until a [`Task`] from [`window::open`] is returned by its update logic.
///
/// Furthermore, a [`Daemon`] will not stop running when all its windows are closed.
/// In order to completely terminate a [`Daemon`], its process must be interrupted or
/// its update logic must produce a [`Task`] from [`exit`].
///
/// [`exit`]: crate::exit
pub fn daemon<State, Message, Theme, Renderer>(
title: impl Title<State>,
update: impl application::Update<State, Message>,
view: impl for<'a> self::View<'a, State, Message, Theme, Renderer>,
) -> Daemon<impl Program<State = State, Message = Message, Theme = Theme>>
where
State: 'static,
Message: Send + std::fmt::Debug + 'static,
Theme: Default + theme::Base,
Renderer: program::Renderer,
{
use std::marker::PhantomData;
struct Instance<State, Message, Theme, Renderer, Update, View> {
update: Update,
view: View,
_state: PhantomData<State>,
_message: PhantomData<Message>,
_theme: PhantomData<Theme>,
_renderer: PhantomData<Renderer>,
}
impl<State, Message, Theme, Renderer, Update, View> Program
for Instance<State, Message, Theme, Renderer, Update, View>
where
Message: Send + std::fmt::Debug + 'static,
Theme: Default + theme::Base,
Renderer: program::Renderer,
Update: application::Update<State, Message>,
View: for<'a> self::View<'a, State, Message, Theme, Renderer>,
{
type State = State;
type Message = Message;
type Theme = Theme;
type Renderer = Renderer;
type Executor = iced_futures::backend::default::Executor;
fn update(
&self,
state: &mut Self::State,
message: Self::Message,
) -> Task<Self::Message> {
self.update.update(state, message).into()
}
fn view<'a>(
&self,
state: &'a Self::State,
window: window::Id,
) -> Element<'a, Self::Message, Self::Theme, Self::Renderer> {
self.view.view(state, window).into()
}
}
Daemon {
raw: Instance {
update,
view,
_state: PhantomData,
_message: PhantomData,
_theme: PhantomData,
_renderer: PhantomData,
},
settings: Settings::default(),
}
.title(title)
}
/// The underlying definition and configuration of an iced daemon.
///
/// You can use this API to create and run iced applications
/// step by step—without coupling your logic to a trait
/// or a specific type.
///
/// You can create a [`Daemon`] with the [`daemon`] helper.
#[derive(Debug)]
pub struct Daemon<P: Program> {
raw: P,
settings: Settings,
}
impl<P: Program> Daemon<P> {
/// Runs the [`Daemon`].
///
/// The state of the [`Daemon`] must implement [`Default`].
/// If your state does not implement [`Default`], use [`run_with`]
/// instead.
///
/// [`run_with`]: Self::run_with
pub fn run(self) -> Result
where
Self: 'static,
P::State: Default,
{
self.raw.run(self.settings, None)
}
/// Runs the [`Daemon`] with a closure that creates the initial state.
pub fn run_with<I>(self, initialize: I) -> Result
where
Self: 'static,
I: FnOnce() -> (P::State, Task<P::Message>) + 'static,
{
self.raw.run_with(self.settings, None, initialize)
}
/// Sets the [`Settings`] that will be used to run the [`Daemon`].
pub fn settings(self, settings: Settings) -> Self {
Self { settings, ..self }
}
/// Sets the [`Settings::antialiasing`] of the [`Daemon`].
pub fn antialiasing(self, antialiasing: bool) -> Self {
Self {
settings: Settings {
antialiasing,
..self.settings
},
..self
}
}
/// Sets the default [`Font`] of the [`Daemon`].
pub fn default_font(self, default_font: Font) -> Self {
Self {
settings: Settings {
default_font,
..self.settings
},
..self
}
}
/// Adds a font to the list of fonts that will be loaded at the start of the [`Daemon`].
pub fn font(mut self, font: impl Into<Cow<'static, [u8]>>) -> Self {
self.settings.fonts.push(font.into());
self
}
/// Sets the [`Title`] of the [`Daemon`].
pub(crate) fn title(
self,
title: impl Title<P::State>,
) -> Daemon<
impl Program<State = P::State, Message = P::Message, Theme = P::Theme>,
> {
Daemon {
raw: program::with_title(self.raw, move |state, window| {
title.title(state, window)
}),
settings: self.settings,
}
}
/// Sets the subscription logic of the [`Daemon`].
pub fn subscription(
self,
f: impl Fn(&P::State) -> Subscription<P::Message>,
) -> Daemon<
impl Program<State = P::State, Message = P::Message, Theme = P::Theme>,
> {
Daemon {
raw: program::with_subscription(self.raw, f),
settings: self.settings,
}
}
/// Sets the theme logic of the [`Daemon`].
pub fn theme(
self,
f: impl Fn(&P::State, window::Id) -> P::Theme,
) -> Daemon<
impl Program<State = P::State, Message = P::Message, Theme = P::Theme>,
> {
Daemon {
raw: program::with_theme(self.raw, f),
settings: self.settings,
}
}
/// Sets the style logic of the [`Daemon`].
pub fn style(
self,
f: impl Fn(&P::State, &P::Theme) -> theme::Style,
) -> Daemon<
impl Program<State = P::State, Message = P::Message, Theme = P::Theme>,
> {
Daemon {
raw: program::with_style(self.raw, f),
settings: self.settings,
}
}
/// Sets the scale factor of the [`Daemon`].
pub fn scale_factor(
self,
f: impl Fn(&P::State, window::Id) -> f64,
) -> Daemon<
impl Program<State = P::State, Message = P::Message, Theme = P::Theme>,
> {
Daemon {
raw: program::with_scale_factor(self.raw, f),
settings: self.settings,
}
}
/// Sets the executor of the [`Daemon`].
pub fn executor<E>(
self,
) -> Daemon<
impl Program<State = P::State, Message = P::Message, Theme = P::Theme>,
>
where
E: Executor,
{
Daemon {
raw: program::with_executor::<P, E>(self.raw),
settings: self.settings,
}
}
}
/// The title logic of some [`Daemon`].
///
/// This trait is implemented both for `&static str` and
/// any closure `Fn(&State, window::Id) -> String`.
///
/// This trait allows the [`daemon`] builder to take any of them.
pub trait Title<State> {
/// Produces the title of the [`Daemon`].
fn title(&self, state: &State, window: window::Id) -> String;
}
impl<State> Title<State> for &'static str {
fn title(&self, _state: &State, _window: window::Id) -> String {
self.to_string()
}
}
impl<T, State> Title<State> for T
where
T: Fn(&State, window::Id) -> String,
{
fn title(&self, state: &State, window: window::Id) -> String {
self(state, window)
}
}
/// The view logic of some [`Daemon`].
///
/// This trait allows the [`daemon`] builder to take any closure that
/// returns any `Into<Element<'_, Message>>`.
pub trait View<'a, State, Message, Theme, Renderer> {
/// Produces the widget of the [`Daemon`].
fn view(
&self,
state: &'a State,
window: window::Id,
) -> impl Into<Element<'a, Message, Theme, Renderer>>;
}
impl<'a, T, State, Message, Theme, Renderer, Widget>
View<'a, State, Message, Theme, Renderer> for T
where
T: Fn(&'a State, window::Id) -> Widget,
State: 'static,
Widget: Into<Element<'a, Message, Theme, Renderer>>,
{
fn view(
&self,
state: &'a State,
window: window::Id,
) -> impl Into<Element<'a, Message, Theme, Renderer>> {
self(state, window)
}
}

View file

@ -1,170 +1,473 @@
//! Iced is a cross-platform GUI library focused on simplicity and type-safety.
//! iced is a cross-platform GUI library focused on simplicity and type-safety.
//! Inspired by [Elm].
//!
//! # Features
//! * Simple, easy-to-use, batteries-included API
//! * Type-safe, reactive programming model
//! * [Cross-platform support] (Windows, macOS, Linux, and the Web)
//! * Responsive layout
//! * Built-in widgets (including [text inputs], [scrollables], and more!)
//! * Custom widget support (create your own!)
//! * [Debug overlay with performance metrics]
//! * First-class support for async actions (use futures!)
//! * [Modular ecosystem] split into reusable parts:
//! * A [renderer-agnostic native runtime] enabling integration with existing
//! systems
//! * A [built-in renderer] supporting Vulkan, Metal, DX11, and DX12
//! * A [windowing shell]
//! * A [web runtime] leveraging the DOM
//! [Elm]: https://elm-lang.org/
//!
//! Check out the [repository] and the [examples] for more details!
//! # Disclaimer
//! iced is __experimental__ software. If you expect the documentation to hold your hand
//! as you learn the ropes, you are in for a frustrating experience.
//!
//! [Cross-platform support]: https://github.com/iced-rs/iced/blob/master/docs/images/todos_desktop.jpg?raw=true
//! [text inputs]: https://iced.rs/examples/text_input.mp4
//! [scrollables]: https://iced.rs/examples/scrollable.mp4
//! [Debug overlay with performance metrics]: https://iced.rs/examples/debug.mp4
//! [Modular ecosystem]: https://github.com/iced-rs/iced/blob/master/ECOSYSTEM.md
//! [renderer-agnostic native runtime]: https://github.com/iced-rs/iced/tree/0.12/runtime
//! [`wgpu`]: https://github.com/gfx-rs/wgpu-rs
//! [built-in renderer]: https://github.com/iced-rs/iced/tree/0.12/wgpu
//! [windowing shell]: https://github.com/iced-rs/iced/tree/0.12/winit
//! [`dodrio`]: https://github.com/fitzgen/dodrio
//! [web runtime]: https://github.com/iced-rs/iced_web
//! [examples]: https://github.com/iced-rs/iced/tree/0.12/examples
//! [repository]: https://github.com/iced-rs/iced
//! The library leverages Rust to its full extent: ownership, borrowing, lifetimes, futures,
//! streams, first-class functions, trait bounds, closures, and more. This documentation
//! is not meant to teach you any of these. Far from it, it will assume you have __mastered__
//! all of them.
//!
//! # Overview
//! Inspired by [The Elm Architecture], Iced expects you to split user
//! interfaces into four different concepts:
//! Furthermore—just like Rust—iced is very unforgiving. It will not let you easily cut corners.
//! The type signatures alone can be used to learn how to use most of the library.
//! Everything is connected.
//!
//! * __State__ — the state of your application
//! * __Messages__ — user interactions or meaningful events that you care
//! about
//! * __View logic__ — a way to display your __state__ as widgets that
//! may produce __messages__ on user interaction
//! * __Update logic__ — a way to react to __messages__ and update your
//! __state__
//! Therefore, iced is easy to learn for __advanced__ Rust programmers; but plenty of patient
//! beginners have learned it and had a good time with it. Since it leverages a lot of what
//! Rust has to offer in a type-safe way, it can be a great way to discover Rust itself.
//!
//! We can build something to see how this works! Let's say we want a simple
//! counter that can be incremented and decremented using two buttons.
//! If you don't like the sound of that, you expect to be spoonfed, or you feel frustrated
//! and struggle to use the library; then I recommend you to wait patiently until [the book]
//! is finished.
//!
//! We start by modelling the __state__ of our application:
//! [the book]: https://book.iced.rs
//!
//! ```
//! #[derive(Default)]
//! struct Counter {
//! // The counter value
//! value: i32,
//! # The Pocket Guide
//! Start by calling [`run`]:
//!
//! ```rust,no_run
//! pub fn main() -> iced::Result {
//! iced::run("A cool counter", update, view)
//! }
//! # fn update(state: &mut (), message: ()) {}
//! # fn view(state: &()) -> iced::Element<()> { iced::widget::text("").into() }
//! ```
//!
//! Next, we need to define the possible user interactions of our counter:
//! the button presses. These interactions are our __messages__:
//! Define an `update` function to __change__ your state:
//!
//! ```
//! #[derive(Debug, Clone, Copy)]
//! pub enum Message {
//! Increment,
//! Decrement,
//! }
//! ```
//!
//! Now, let's show the actual counter by putting it all together in our
//! __view logic__:
//!
//! ```
//! # struct Counter {
//! # // The counter value
//! # value: i32,
//! # }
//! #
//! # #[derive(Debug, Clone, Copy)]
//! # pub enum Message {
//! # Increment,
//! # Decrement,
//! # }
//! #
//! use iced::widget::{button, column, text, Column};
//!
//! impl Counter {
//! pub fn view(&self) -> Column<Message> {
//! // We use a column: a simple vertical layout
//! column![
//! // The increment button. We tell it to produce an
//! // `Increment` message when pressed
//! button("+").on_press(Message::Increment),
//!
//! // We show the value of the counter here
//! text(self.value).size(50),
//!
//! // The decrement button. We tell it to produce a
//! // `Decrement` message when pressed
//! button("-").on_press(Message::Decrement),
//! ]
//! ```rust
//! fn update(counter: &mut u64, message: Message) {
//! match message {
//! Message::Increment => *counter += 1,
//! }
//! }
//! # #[derive(Clone)]
//! # enum Message { Increment }
//! ```
//!
//! Finally, we need to be able to react to any produced __messages__ and change
//! our __state__ accordingly in our __update logic__:
//! Define a `view` function to __display__ your state:
//!
//! ```rust
//! use iced::widget::{button, text};
//! use iced::Element;
//!
//! fn view(counter: &u64) -> Element<Message> {
//! button(text(counter)).on_press(Message::Increment).into()
//! }
//! # #[derive(Clone)]
//! # enum Message { Increment }
//! ```
//! # struct Counter {
//! # // The counter value
//! # value: i32,
//! # }
//! #
//! # #[derive(Debug, Clone, Copy)]
//! # pub enum Message {
//! # Increment,
//! # Decrement,
//! # }
//! impl Counter {
//! // ...
//!
//! pub fn update(&mut self, message: Message) {
//! match message {
//! Message::Increment => {
//! self.value += 1;
//! And create a `Message` enum to __connect__ `view` and `update` together:
//!
//! ```rust
//! #[derive(Debug, Clone)]
//! enum Message {
//! Increment,
//! }
//! ```
//!
//! ## Custom State
//! You can define your own struct for your state:
//!
//! ```rust
//! #[derive(Default)]
//! struct Counter {
//! value: u64,
//! }
//! ```
//!
//! But you have to change `update` and `view` accordingly:
//!
//! ```rust
//! # struct Counter { value: u64 }
//! # #[derive(Clone)]
//! # enum Message { Increment }
//! # use iced::widget::{button, text};
//! # use iced::Element;
//! fn update(counter: &mut Counter, message: Message) {
//! match message {
//! Message::Increment => counter.value += 1,
//! }
//! }
//!
//! fn view(counter: &Counter) -> Element<Message> {
//! button(text(counter.value)).on_press(Message::Increment).into()
//! }
//! ```
//!
//! ## Widgets and Elements
//! The `view` function must return an [`Element`]. An [`Element`] is just a generic [`widget`].
//!
//! The [`widget`] module contains a bunch of functions to help you build
//! and use widgets.
//!
//! Widgets are configured using the builder pattern:
//!
//! ```rust
//! # struct Counter { value: u64 }
//! # #[derive(Clone)]
//! # enum Message { Increment }
//! use iced::widget::{button, column, text};
//! use iced::Element;
//!
//! fn view(counter: &Counter) -> Element<Message> {
//! column![
//! text(counter.value).size(20),
//! button("Increment").on_press(Message::Increment),
//! ]
//! .spacing(10)
//! .into()
//! }
//! ```
//!
//! A widget can be turned into an [`Element`] by calling `into`.
//!
//! Widgets and elements are generic over the message type they produce. The
//! [`Element`] returned by `view` must have the same `Message` type as
//! your `update`.
//!
//! ## Layout
//! There is no unified layout system in iced. Instead, each widget implements
//! its own layout strategy.
//!
//! Building your layout will often consist in using a combination of
//! [rows], [columns], and [containers]:
//!
//! ```rust
//! # struct State;
//! # enum Message {}
//! use iced::widget::{column, container, row};
//! use iced::{Fill, Element};
//!
//! fn view(state: &State) -> Element<Message> {
//! container(
//! column![
//! "Top",
//! row!["Left", "Right"].spacing(10),
//! "Bottom"
//! ]
//! .spacing(10)
//! )
//! .padding(10)
//! .center_x(Fill)
//! .center_y(Fill)
//! .into()
//! }
//! ```
//!
//! Rows and columns lay out their children horizontally and vertically,
//! respectively. [Spacing] can be easily added between elements.
//!
//! Containers position or align a single widget inside their bounds.
//!
//! [rows]: widget::Row
//! [columns]: widget::Column
//! [containers]: widget::Container
//! [Spacing]: widget::Column::spacing
//!
//! ## Sizing
//! The width and height of widgets can generally be defined using a [`Length`].
//!
//! - [`Fill`] will make the widget take all the available space in a given axis.
//! - [`Shrink`] will make the widget use its intrinsic size.
//!
//! Most widgets use a [`Shrink`] sizing strategy by default, but will inherit
//! a [`Fill`] strategy from their children.
//!
//! A fixed numeric [`Length`] in [`Pixels`] can also be used:
//!
//! ```rust
//! # struct State;
//! # enum Message {}
//! use iced::widget::container;
//! use iced::Element;
//!
//! fn view(state: &State) -> Element<Message> {
//! container("I am 300px tall!").height(300).into()
//! }
//! ```
//!
//! ## Theming
//! The default [`Theme`] of an application can be changed by defining a `theme`
//! function and leveraging the [`Application`] builder, instead of directly
//! calling [`run`]:
//!
//! ```rust,no_run
//! # #[derive(Default)]
//! # struct State;
//! use iced::Theme;
//!
//! pub fn main() -> iced::Result {
//! iced::application("A cool application", update, view)
//! .theme(theme)
//! .run()
//! }
//!
//! fn theme(state: &State) -> Theme {
//! Theme::TokyoNight
//! }
//! # fn update(state: &mut State, message: ()) {}
//! # fn view(state: &State) -> iced::Element<()> { iced::widget::text("").into() }
//! ```
//!
//! The `theme` function takes the current state of the application, allowing the
//! returned [`Theme`] to be completely dynamic—just like `view`.
//!
//! There are a bunch of built-in [`Theme`] variants at your disposal, but you can
//! also [create your own](Theme::custom).
//!
//! ## Styling
//! As with layout, iced does not have a unified styling system. However, all
//! of the built-in widgets follow the same styling approach.
//!
//! The appearance of a widget can be changed by calling its `style` method:
//!
//! ```rust
//! # struct State;
//! # enum Message {}
//! use iced::widget::container;
//! use iced::Element;
//!
//! fn view(state: &State) -> Element<Message> {
//! container("I am a rounded box!").style(container::rounded_box).into()
//! }
//! ```
//!
//! The `style` method of a widget takes a closure that, given the current active
//! [`Theme`], returns the widget style:
//!
//! ```rust
//! # struct State;
//! # #[derive(Clone)]
//! # enum Message {}
//! use iced::widget::button;
//! use iced::{Element, Theme};
//!
//! fn view(state: &State) -> Element<Message> {
//! button("I am a styled button!").style(|theme: &Theme, status| {
//! let palette = theme.extended_palette();
//!
//! match status {
//! button::Status::Active => {
//! button::Style::default()
//! .with_background(palette.success.strong.color)
//! }
//! Message::Decrement => {
//! self.value -= 1;
//! _ => button::primary(theme, status),
//! }
//! })
//! .into()
//! }
//! ```
//!
//! Widgets that can be in multiple different states will also provide the closure
//! with some [`Status`], allowing you to use a different style for each state.
//!
//! You can extract the [`Palette`] colors of a [`Theme`] with the [`palette`] or
//! [`extended_palette`] methods.
//!
//! Most widgets provide styling functions for your convenience in their respective modules;
//! like [`container::rounded_box`], [`button::primary`], or [`text::danger`].
//!
//! [`Status`]: widget::button::Status
//! [`palette`]: Theme::palette
//! [`extended_palette`]: Theme::extended_palette
//! [`container::rounded_box`]: widget::container::rounded_box
//! [`button::primary`]: widget::button::primary
//! [`text::danger`]: widget::text::danger
//!
//! ## Concurrent Tasks
//! The `update` function can _optionally_ return a [`Task`].
//!
//! A [`Task`] can be leveraged to perform asynchronous work, like running a
//! future or a stream:
//!
//! ```rust
//! # #[derive(Clone)]
//! # struct Weather;
//! use iced::Task;
//!
//! struct State {
//! weather: Option<Weather>,
//! }
//!
//! enum Message {
//! FetchWeather,
//! WeatherFetched(Weather),
//! }
//!
//! fn update(state: &mut State, message: Message) -> Task<Message> {
//! match message {
//! Message::FetchWeather => Task::perform(
//! fetch_weather(),
//! Message::WeatherFetched,
//! ),
//! Message::WeatherFetched(weather) => {
//! state.weather = Some(weather);
//!
//! Task::none()
//! }
//! }
//! }
//!
//! async fn fetch_weather() -> Weather {
//! // ...
//! # unimplemented!()
//! }
//! ```
//!
//! Tasks can also be used to interact with the iced runtime. Some modules
//! expose functions that create tasks for different purposes—like [changing
//! window settings](window#functions), [focusing a widget](widget::focus_next), or
//! [querying its visible bounds](widget::container::visible_bounds).
//!
//! Like futures and streams, tasks expose [a monadic interface](Task::then)—but they can also be
//! [mapped](Task::map), [chained](Task::chain), [batched](Task::batch), [canceled](Task::abortable),
//! and more.
//!
//! ## Passive Subscriptions
//! Applications can subscribe to passive sources of data—like time ticks or runtime events.
//!
//! You will need to define a `subscription` function and use the [`Application`] builder:
//!
//! ```rust,no_run
//! # #[derive(Default)]
//! # struct State;
//! use iced::window;
//! use iced::{Size, Subscription};
//!
//! #[derive(Debug)]
//! enum Message {
//! WindowResized(Size),
//! }
//!
//! pub fn main() -> iced::Result {
//! iced::application("A cool application", update, view)
//! .subscription(subscription)
//! .run()
//! }
//!
//! fn subscription(state: &State) -> Subscription<Message> {
//! window::resize_events().map(|(_id, size)| Message::WindowResized(size))
//! }
//! # fn update(state: &mut State, message: Message) {}
//! # fn view(state: &State) -> iced::Element<Message> { iced::widget::text("").into() }
//! ```
//!
//! A [`Subscription`] is [a _declarative_ builder of streams](Subscription#the-lifetime-of-a-subscription)
//! that are not allowed to end on their own. Only the `subscription` function
//! dictates the active subscriptions—just like `view` fully dictates the
//! visible widgets of your user interface, at every moment.
//!
//! As with tasks, some modules expose convenient functions that build a [`Subscription`] for you—like
//! [`time::every`] which can be used to listen to time, or [`keyboard::on_key_press`] which will notify you
//! of any key presses. But you can also create your own with [`Subscription::run`] and [`run_with`].
//!
//! [`run_with`]: Subscription::run_with
//!
//! ## Scaling Applications
//! The `update`, `view`, and `Message` triplet composes very nicely.
//!
//! A common pattern is to leverage this composability to split an
//! application into different screens:
//!
//! ```rust
//! # mod contacts {
//! # use iced::{Element, Task};
//! # pub struct Contacts;
//! # impl Contacts {
//! # pub fn update(&mut self, message: Message) -> Action { unimplemented!() }
//! # pub fn view(&self) -> Element<Message> { unimplemented!() }
//! # }
//! # #[derive(Debug)]
//! # pub enum Message {}
//! # pub enum Action { None, Run(Task<Message>), Chat(()) }
//! # }
//! # mod conversation {
//! # use iced::{Element, Task};
//! # pub struct Conversation;
//! # impl Conversation {
//! # pub fn new(contact: ()) -> (Self, Task<Message>) { unimplemented!() }
//! # pub fn update(&mut self, message: Message) -> Task<Message> { unimplemented!() }
//! # pub fn view(&self) -> Element<Message> { unimplemented!() }
//! # }
//! # #[derive(Debug)]
//! # pub enum Message {}
//! # }
//! use contacts::Contacts;
//! use conversation::Conversation;
//!
//! use iced::{Element, Task};
//!
//! struct State {
//! screen: Screen,
//! }
//!
//! enum Screen {
//! Contacts(Contacts),
//! Conversation(Conversation),
//! }
//!
//! enum Message {
//! Contacts(contacts::Message),
//! Conversation(conversation::Message)
//! }
//!
//! fn update(state: &mut State, message: Message) -> Task<Message> {
//! match message {
//! Message::Contacts(message) => {
//! if let Screen::Contacts(contacts) = &mut state.screen {
//! let action = contacts.update(message);
//!
//! match action {
//! contacts::Action::None => Task::none(),
//! contacts::Action::Run(task) => task.map(Message::Contacts),
//! contacts::Action::Chat(contact) => {
//! let (conversation, task) = Conversation::new(contact);
//!
//! state.screen = Screen::Conversation(conversation);
//!
//! task.map(Message::Conversation)
//! }
//! }
//! } else {
//! Task::none()
//! }
//! }
//! Message::Conversation(message) => {
//! if let Screen::Conversation(conversation) = &mut state.screen {
//! conversation.update(message).map(Message::Conversation)
//! } else {
//! Task::none()
//! }
//! }
//! }
//! }
//! ```
//!
//! And that's everything! We just wrote a whole user interface. Let's run it:
//!
//! ```no_run
//! # #[derive(Default)]
//! # struct Counter;
//! # impl Counter {
//! # fn update(&mut self, _message: ()) {}
//! # fn view(&self) -> iced::Element<()> { unimplemented!() }
//! # }
//! #
//! fn main() -> iced::Result {
//! iced::run("A cool counter", Counter::update, Counter::view)
//! fn view(state: &State) -> Element<Message> {
//! match &state.screen {
//! Screen::Contacts(contacts) => contacts.view().map(Message::Contacts),
//! Screen::Conversation(conversation) => conversation.view().map(Message::Conversation),
//! }
//! }
//! ```
//!
//! Iced will automatically:
//! The `update` method of a screen can return an `Action` enum that can be leveraged by the parent to
//! execute a task or transition to a completely different screen altogether. The variants of `Action` can
//! have associated data. For instance, in the example above, the `Conversation` screen is created when
//! `Contacts::update` returns an `Action::Chat` with the selected contact.
//!
//! 1. Take the result of our __view logic__ and layout its widgets.
//! 1. Process events from our system and produce __messages__ for our
//! __update logic__.
//! 1. Draw the resulting user interface.
//! Effectively, this approach lets you "tell a story" to connect different screens together in a type safe
//! way.
//!
//! # Usage
//! Use [`run`] or the [`program`] builder.
//!
//! [Elm]: https://elm-lang.org/
//! [The Elm Architecture]: https://guide.elm-lang.org/architecture/
//! [`program`]: program()
//! Furthermore, functor methods like [`Task::map`], [`Element::map`], and [`Subscription::map`] make composition
//! seamless.
#![doc(
html_logo_url = "https://raw.githubusercontent.com/iced-rs/iced/9ab6923e943f784985e9ef9ca28b10278297225d/docs/logo.svg"
html_logo_url = "https://raw.githubusercontent.com/iced-rs/iced/bdf0430880f5c29443f5f0a0ae4895866dfef4c6/docs/logo.svg"
)]
#![cfg_attr(docsrs, feature(doc_auto_cfg))]
#![cfg_attr(docsrs, feature(doc_cfg))]
@ -175,34 +478,51 @@ use iced_winit::core;
use iced_winit::runtime;
pub use iced_futures::futures;
pub use iced_futures::stream;
#[cfg(feature = "highlighter")]
pub use iced_highlighter as highlighter;
mod application;
mod error;
#[cfg(feature = "wgpu")]
pub use iced_renderer::wgpu::wgpu;
pub mod program;
pub mod settings;
mod error;
mod program;
pub mod application;
pub mod daemon;
pub mod time;
pub mod window;
#[cfg(feature = "advanced")]
pub mod advanced;
#[cfg(feature = "multi-window")]
pub mod multi_window;
pub use crate::core::alignment;
pub use crate::core::animation;
pub use crate::core::border;
pub use crate::core::color;
pub use crate::core::gradient;
pub use crate::core::padding;
pub use crate::core::theme;
pub use crate::core::{
Alignment, Background, Border, Color, ContentFit, Degrees, Gradient,
Length, Padding, Pixels, Point, Radians, Rectangle, Rotation, Shadow, Size,
Theme, Transformation, Vector,
Alignment, Animation, Background, Border, Color, ContentFit, Degrees,
Function, Gradient, Length, Padding, Pixels, Point, Radians, Rectangle,
Rotation, Settings, Shadow, Size, Theme, Transformation, Vector, never,
};
pub use crate::runtime::exit;
pub use iced_futures::Subscription;
pub use Alignment::Center;
pub use Length::{Fill, FillPortion, Shrink};
pub use alignment::Horizontal::{Left, Right};
pub use alignment::Vertical::{Bottom, Top};
pub mod task {
//! Create runtime tasks.
pub use crate::runtime::task::{
Handle, Never, Sipper, Straw, Task, sipper, stream,
};
}
pub mod clipboard {
//! Access the clipboard.
@ -236,8 +556,10 @@ pub mod font {
pub mod event {
//! Handle events of a user interface.
pub use crate::core::event::{Event, MacOS, PlatformSpecific, Status};
pub use iced_futures::event::{listen, listen_raw, listen_with};
pub use crate::core::event::{Event, Status};
pub use iced_futures::event::{
listen, listen_raw, listen_url, listen_with,
};
}
pub mod keyboard {
@ -254,18 +576,6 @@ pub mod mouse {
};
}
pub mod command {
//! Run asynchronous actions.
pub use crate::runtime::command::{channel, Command};
}
pub mod subscription {
//! Listen to external events in your application.
pub use iced_futures::subscription::{
channel, run, run_with_id, unfold, Subscription,
};
}
#[cfg(feature = "system")]
pub mod system {
//! Retrieve system information.
@ -310,15 +620,20 @@ pub mod widget {
mod runtime {}
}
pub use command::Command;
pub use application::Application;
pub use daemon::Daemon;
pub use error::Error;
pub use event::Event;
pub use executor::Executor;
pub use font::Font;
pub use program::Program;
pub use renderer::Renderer;
pub use settings::Settings;
pub use subscription::Subscription;
pub use task::Task;
#[doc(inline)]
pub use application::application;
#[doc(inline)]
pub use daemon::daemon;
/// A generic widget.
///
@ -330,15 +645,13 @@ pub type Element<
Renderer = crate::Renderer,
> = crate::core::Element<'a, Message, Theme, Renderer>;
/// The result of running a [`Program`].
/// The result of running an iced program.
pub type Result = std::result::Result<(), Error>;
/// Runs a basic iced application with default [`Settings`] given its title,
/// update, and view logic.
///
/// This is equivalent to chaining [`program`] with [`Program::run`].
///
/// [`program`]: program()
/// This is equivalent to chaining [`application()`] with [`Application::run`].
///
/// # Example
/// ```no_run
@ -367,18 +680,16 @@ pub type Result = std::result::Result<(), Error>;
/// }
/// ```
pub fn run<State, Message, Theme, Renderer>(
title: impl program::Title<State> + 'static,
update: impl program::Update<State, Message> + 'static,
view: impl for<'a> program::View<'a, State, Message, Theme, Renderer> + 'static,
title: impl application::Title<State> + 'static,
update: impl application::Update<State, Message> + 'static,
view: impl for<'a> application::View<'a, State, Message, Theme, Renderer>
+ 'static,
) -> Result
where
State: Default + 'static,
Message: std::fmt::Debug + Send + 'static,
Theme: Default + program::DefaultStyle + 'static,
Theme: Default + theme::Base + 'static,
Renderer: program::Renderer + 'static,
{
program(title, update, view).run()
application(title, update, view).run()
}
#[doc(inline)]
pub use program::program;

View file

@ -1,263 +0,0 @@
//! Leverage multi-window support in your application.
use crate::window;
use crate::{Command, Element, Executor, Settings, Subscription};
pub use crate::application::{Appearance, DefaultStyle};
/// 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).
///
/// - On native platforms, it will run in its own windows.
/// - On the web, it will take control of the `<title>` and the `<body>` of the
/// document and display only the contents of the `window::Id::MAIN` 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`.
///
/// # Examples
/// See the `examples/multi-window` example to see this multi-window `Application` trait in action.
///
/// ## 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, window};
/// use iced::{Command, Element, Settings, Theme};
/// use iced::multi_window::{self, Application};
///
/// pub fn main() -> iced::Result {
/// Hello::run(Settings::default())
/// }
///
/// struct Hello;
///
/// impl multi_window::Application for Hello {
/// type Executor = executor::Default;
/// type Flags = ();
/// type Message = ();
/// type Theme = Theme;
///
/// 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()
/// }
/// }
/// ```
///
/// [`Sandbox`]: crate::Sandbox
pub trait Application: Sized
where
Self::Theme: DefaultStyle,
{
/// 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;
/// The data needed to initialize your [`Application`].
type Flags;
/// Returns the unique name of the [`Application`].
fn name() -> &'static str {
std::any::type_name::<Self>()
}
/// 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 `window` of the [`Application`].
///
/// This title can be dynamic! The runtime will automatically update the
/// title of your window 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 widgets to display in the `window` of the [`Application`].
///
/// These widgets can produce __messages__ based on user interaction.
fn view(
&self,
window: window::Id,
) -> Element<'_, Self::Message, Self::Theme, crate::Renderer>;
/// Returns the current [`Theme`] of the `window` 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`].
///
/// [`Theme`]: Self::Theme
fn style(&self, theme: &Self::Theme) -> Appearance {
Self::Theme::default_style(theme)
}
/// 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 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
}
/// Runs the multi-window [`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::graphics::Settings {
default_font: settings.default_font,
default_text_size: settings.default_text_size,
antialiasing: if settings.antialiasing {
Some(crate::graphics::Antialiasing::MSAAx4)
} else {
None
},
..crate::graphics::Settings::default()
};
Ok(crate::shell::multi_window::run::<
Instance<Self>,
Self::Executor,
crate::renderer::Compositor,
>(settings.into(), renderer_settings)?)
}
}
struct Instance<A>(A)
where
A: Application,
A::Theme: DefaultStyle;
impl<A> crate::runtime::multi_window::Program for Instance<A>
where
A: Application,
A::Theme: DefaultStyle,
{
type Message = A::Message;
type Theme = A::Theme;
type Renderer = crate::Renderer;
fn update(&mut self, message: Self::Message) -> Command<Self::Message> {
self.0.update(message)
}
fn view(
&self,
window: window::Id,
) -> Element<'_, Self::Message, Self::Theme, Self::Renderer> {
self.0.view(window)
}
}
impl<A> crate::shell::multi_window::Application for Instance<A>
where
A: Application,
A::Theme: DefaultStyle,
{
type Flags = A::Flags;
fn new(flags: Self::Flags) -> (Self, Command<A::Message>) {
let (app, command) = A::new(flags);
(Instance(app), command)
}
fn name() -> &'static str {
A::name()
}
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, theme: &Self::Theme) -> Appearance {
self.0.style(theme)
}
fn subscription(&self) -> Subscription<Self::Message> {
self.0.subscription()
}
fn scale_factor(&self, window: window::Id) -> f64 {
self.0.scale_factor(window)
}
}

File diff suppressed because it is too large Load diff

View file

@ -1,98 +0,0 @@
//! Configure your application.
use crate::window;
use crate::{Font, Pixels};
use std::borrow::Cow;
/// The settings of an iced [`Program`].
///
/// [`Program`]: crate::Program
#[derive(Debug, Clone)]
pub struct Settings<Flags = ()> {
/// The identifier of the application.
///
/// If provided, this identifier may be used to identify the application or
/// communicate with it through the windowing system.
pub id: Option<String>,
/// The window settings.
///
/// They will be ignored on the Web.
pub window: window::Settings,
/// The data needed to initialize the [`Program`].
///
/// [`Program`]: crate::Program
pub flags: Flags,
/// The fonts to load on boot.
pub fonts: Vec<Cow<'static, [u8]>>,
/// The default [`Font`] to be used.
///
/// By default, it uses [`Family::SansSerif`](crate::font::Family::SansSerif).
pub default_font: Font,
/// The text size that will be used by default.
///
/// The default value is `16.0`.
pub default_text_size: Pixels,
/// 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.
///
/// By default, it is disabled.
///
/// [`Canvas`]: crate::widget::Canvas
pub antialiasing: bool,
}
impl<Flags> Settings<Flags> {
/// Initialize [`Program`] settings using the given data.
///
/// [`Program`]: crate::Program
pub fn with_flags(flags: Flags) -> Self {
let default_settings = Settings::<()>::default();
Self {
flags,
id: default_settings.id,
window: default_settings.window,
fonts: default_settings.fonts,
default_font: default_settings.default_font,
default_text_size: default_settings.default_text_size,
antialiasing: default_settings.antialiasing,
}
}
}
impl<Flags> Default for Settings<Flags>
where
Flags: Default,
{
fn default() -> Self {
Self {
id: None,
window: window::Settings::default(),
flags: Default::default(),
fonts: Vec::new(),
default_font: Font::default(),
default_text_size: Pixels(16.0),
antialiasing: false,
}
}
}
impl<Flags> From<Settings<Flags>> for iced_winit::Settings<Flags> {
fn from(settings: Settings<Flags>) -> iced_winit::Settings<Flags> {
iced_winit::Settings {
id: settings.id,
window: settings.window,
flags: settings.flags,
fonts: settings.fonts,
}
}
}

View file

@ -1,5 +1,5 @@
//! Listen and react to time.
pub use crate::core::time::{Duration, Instant, SystemTime};
pub use crate::core::time::*;
#[allow(unused_imports)]
#[cfg_attr(

View file

@ -13,7 +13,7 @@ use std::path::Path;
/// This will return an error in case the file is missing at run-time. You may prefer [`from_file_data`] instead.
#[cfg(feature = "image")]
pub fn from_file<P: AsRef<Path>>(icon_path: P) -> Result<Icon, Error> {
let icon = image::io::Reader::open(icon_path)?.decode()?.to_rgba8();
let icon = image::ImageReader::open(icon_path)?.decode()?.to_rgba8();
Ok(icon::from_rgba(icon.to_vec(), icon.width(), icon.height())?)
}
@ -27,7 +27,7 @@ pub fn from_file_data(
data: &[u8],
explicit_format: Option<image::ImageFormat>,
) -> Result<Icon, Error> {
let mut icon = image::io::Reader::new(std::io::Cursor::new(data));
let mut icon = image::ImageReader::new(std::io::Cursor::new(data));
let icon_with_format = match explicit_format {
Some(format) => {