feat: pop-os megasquash

x11: Workaround nvidia driver lacking DRI

feat(mouse area): add double click

mouse area: add double click

compositor: Add code to extract adapter from x11

refactor: Extract ids_from_dev from wayland specific code

wayland: Don't crash if libwayland isn't available

feat(sctk): support for overflow widget

sctk: Fixes for cursor icon

* With multiple windows, `SetCursor` is only sent for the focused
  window. Fixing a flicker between icons when two windows are using
  different cursors.
* If there is a drag surface, let that surface set the cursor. And not
  any other.
* Set cursor on `enter`, and when switching between CSDs and app area.

Fixes https://github.com/pop-os/libcosmic/issues/533.

improv(sctk): per-surface cursor position tracking

feat(sctk): support ShowWindowMenu

Make text wrap configurable

fix(core): state order and handling of new trees

fix: settings.decorations enables SSD

refactor(sctk): convert window actions

fix: enable the tokio feature for accesskit_unix

fix: only try to connect to clipboard if on linux

iced_wgpu: don't query Wayland on macos

Update `window_clipboard`

sctk: Unmap subsurfaces instead of immediately destroying them

Destroying a surface is immediate, rather than synchronized with
commits.

This fixes a flickering behavior with drag and drop in
cosmic-workspaces.

sctk: Add alpha setting to `Subsurface` widget

sctk: Update `sctk`, `wayland-protocols`

Update for cosmic-text undefined buffer size

Adapt to cosmic-text undefined width change

fix: unset VK_LOADER_DRIVERS_DISABLE after enumeration

Allows applications to be launched on the NVIDIA GPU with Vulkan support

Adapt to new cosmic-text

wgpu: Fix wayland device id conversion

wgpu: Fix querying adapter, even if we already have one

wgpu: fix nvidia gpu powering up in hybrid setups

cargo fmt

fix: refactor dnd impl to support responsive widget

fix: update read and write methods so they don't recurse

fix(core): replace debug_assert in diff

fix: avoid with_borrow_mut

fix: better handling of state tree

This persists widget state associated with widgets assigned custom IDs even when the tree structure changes, but resets state if the custom ID is not found.

fix: emit Event::Resized to fix nav bar in cosmic-settings

fix(image): guess the image format before decoding

iced_wgpu: Query wayland for the device to use, if possible

sctk: Support `start_drag` with drags started from touch events

sctk: Add touch support

fix: update widnow-clipboard tag

fix: clean up dnd surfaces when a window is removed

Adjust to line ending needing to be specified as part of cosmic_text::BufferLine

sctk: Add support for drag-and-drop surface offsets

This adds an offset `Vector` as an argument to `on_drag`, and allows
passing an offset to `start_drag`.

Some applications using drag and drop want the top left corner of the
drag surface (as happens without an offset). But others want the drag
surface to be offset based on where the cursor is on the widget when
starting the drag. This can just be `-1 * offset`, but may be scaled if
the drag surface is a different size from the original widget.

fix(sctk): nested popup parent

feat(mouseare): mouse enter and exit

fix(tiny_skia): damage

fix(scrollable): filter scroll events in the wrong direction

sctk: Use empty input region for subsurfaces

This seems to work, and is a better way to deal with subsurface input if
there aren't any problems. This way, input events simply go to the
parent surface, so we don't have to deal with various edge cases related
to that. (Though for compositor-side issues, we still need to fix those
for other clients.)

This helps with an issue with drag-and-drop and subsurfaces on Smithay,
and a different issue on Kwin (in KDE 5.27, at least).

Send `DataSource` events to all surfaces

Previously these events are directed to the first surface, then removed
from `sctk_events`. Which is definitely not right.

slider & toggler roundness

Update window_clipboard to pop-dnd-4

fix(tiny-skia): non-simple border scaling

the issue can be seen with sharp corners when using the screenshot portal with scaling

Add read_primary/write_primary

chore: update tag

fix: translate offer positions in scrollable

fix(winit multi-window): handle exit_on_close request

fix(scrollable): pass child layout when calculating drag destinations

fix(container): id and set_id should use content

Clean up after lock surfaces are destroyed

Call unlock on session lock

chore: update tag

fixes for dnd

sctk: Fix handling of DnD with subsurfaces (#122)

Map subsurface to parent and add offset.

refactor: remove Sync bound for Message

fix: pass correct state and layout for container widgets

fix: docs

feat: update advertised drag destinations after rebuilding an interface

fix: color format & multi-window

fix: doc

feat: winit dnd

fix: ambiguous import

chore: reexport mime from window_clipboard

chore: use tag

clippy

feat: add actions and commands for new clipboard methods

cleanup docs

feat: custom mime types for Clipboard

sctk: Fix handling of layer surface `pointer_interactivity` (#115)

A null `region` represents an infinite region (the default). To set an
empty region, we need to create a `wl_region`.

fix(tiny_skia): disable shadows due to rendering glitch

fix(winit): add static lifetimes to multi-window application update

fix(winit): add static lifetimes to application update

Use `TypeId` to identify `subscription::Map`

(cherry picked from commit f39a5fd895)

fix(sctk): destroy drag icon and send event after cancel action

fix: clipboard cleanup

fix(sctk): clipboard dummy impl typo

refactor(sctk): optional clipboard

fix(sctk): broadcast events after update

when broadcasting events for no specific surface, it should be done after update so that the runtime subscription is current

fix(multi_window): enable drag resize

sctk: Map subsurface pointer events to parent surface, with offset

sctk_subsurface: Use two surfaces, handle button presses

Useful for testing pointer input to subsurfaces.

sctk: Add `subsurface_ids` mapping subsurface to parent and offset

sctk_subsurface_gst: NV12 surface suppport; disabled

Whether or not this works seems to depend on driver, or gstreamer
version...

Handle frame callbacks for subsurfaces, and `commit` parent surface

If the main surface is occluded completely by opaque subsurfaces, it may
not receive `frame` events. So we need to request frame events for all
subsurfaces as well.

Additionally, with "synchronized" subsurfaces, we need to `commit` the
parent surface for subsurface changes to take effect.

Fixes issues with subsurfaces updating slowly, or only when mouse moved
under some circumstances.

examples/sctk_subsurface_gst: Cache `BufferSource` in `BufferRef` qdata

Similar to `waylandsink`. Allows us to avoid creating a buffer source
(and ultimately `wl_buffer`) for every buffer swap.

sctk/subsurface: Cache `wl_buffer`s

Creating a new `wl_buffer` each frame seems to perform poorly. We can
instead keep a cache of `wl_buffer`s we have created from a
`BufferSource`.

sctk/subsurface: Avoid unnecessary subsurface commits if unchanged

feat(slider): add breakpoints

fix: autosize surface layout

Autosized surfaces perform the layout step to get the size and then again when building the interface, but sometimes the calculated size is not enough space when used as a bound, so we need to add a tiny amount to the calculated size. This also makes the event loop timeout duration configurable. Viewport physical size is calculated directly from the logical size now as well in iced-sctk to avoid inconsistencies that resulted from recalculating the logical size after using it to calculate the physical size.

fix(sctk): send close event instead of close requested when a window is closed

sctk: add command to set maximize state

Add `show_window_menu` action

Winit currently supports this only on Windows and Wayland.

This requests that a context menu is shown at the cursor position,
like the menu normally triggered by right clicking the title bar. This
is important for implementing client side decorations with Iced widgets.

Remove unnecessary redraw request

This was particularly visible on Redox where there is no vsync, but also
causes unnecessary redraws on Linux

chore: update accesskit

Disable broken rustdoc links

sctk: Add `Subsurface` widget (#79)

This adds a widget that attaches an shm or dma buffer to a subsurface,
scaled with `wp_viewporter`.

By exposing this as a widget, rather than as a type of window, it can be
positioned and scaled like any other iced widget. It provides an API
that's similar to an iced image.

The initial version of this just took a `wl_buffer`. But this makes
buffer re-use problematic. In particular, the docs for `wl_surface::attach`
note that `wl_buffer::release` events become unreliable if a buffer is
attached to multiple surfaces. And indicates that a client should create
multiple `wl_buffer` instances, or use `wp_linux_buffer_release`.

So we store information about the buffer, and create `wl_buffer`s as
needed. `SubsurfaceBuffer::new` also returns a future that's signaled
when all references are destroyed, both `wl_buffer`s and any instance of
the `SubsurfaceBuffer` that might still be used in the `view`.

So this seems like the best solution for now, within the
model-view-update architecture.

This has two examples: `sctk_subsurface`, showing a single-color shm
buffer, and `sctk_subsurface_gst`, which plays an h264 video to a
subsurface with vaapi decoding.

chore: use pop-os fork of winit

chore: unpin cosmic-text

Update wgpu to a commit that fixes use on Nvidia drivers

This can be tested with something like
`VK_ICD_FILENAMES=/usr/share/vulkan/icd.d/nvidia_icd.json cargo run -p tour
--features iced/wgpu`.

On Nvidia I'm seeing a flood of `Suboptimal present of frame` warnings.
So some improvement may still be needed here. But if it doesn't regress
behavior on other hardware, that seems like an improvement over
freezing.

fix(winit): pass text with modifiers in event

chore: update cosmic-text and glyphon

fix: distinguish between the key character and the utf8 of a key event

feat(wgpu): use alpha modes for compositing if available

chore: use updated softbuffer

fix: typo

fix: downgrade resvg

fix: core/serde

chore: remove default features

typo: add rev to glyphon

Update to cosmic-text refactor

Fix docs error

Add function to fill a Raw

Fixes for last commit

fix: broadcast surface events

dnd_listener: Fix behavior when there are multiple listeners (#87)

A `dnd_listener` widget shouldn't handle a DnD event when the dnd drag
isn't within the widget's bounds. So add a few more checks for this.

Enter/leave events generated by `DndOfferEvent::Motion` also don't
behave as one might expect, since the enter may occur before the leave
depending on the order it calls `on_event` on the widget. Not sure how
to address that, but cosmic-workspaces can just ignore the leave events
for now.

Otherwise, this seems to be working fine, after these changes.

chore: fix sctk multi-window dependency

cleanup: formatting and clippy

fix(example): sctk_drag id

fix: translate the wayland event position for content inside a scrollable

fix: set web-sys to =0.3.64

fix: clip mask checks

chore: use advanced text shaping for pick list

fix: dnd widget layout

fix: ambiguous palette import

chore: remove artifacts job

fix: CI tests

fix: add back the window id to the frames subscription

fix: tooltip children and diff

refactor: udpate gradient angles for slider

reexport limits

fix: editor and sctk_todos examples

cleanup: clippy

cleanup git workflows

chore: cleanup iced_widget

refactor

Update mod.rs

chore: update softbuffer

Hack to remove image blur

iced_core: feature for serde serialization of KeyCode

fix(wgpu): handle border_radius property with image raster

feat: add border radius to image rendering

feat: Add side mouse button events

cleanup: clippy fixes and formatting

Part of this is a refactor of the ID

cleanup: clippy and fmt

fix: test workflow

fix: add note in CHANGELOG

fix: clippy

refactor: restore default style of slider

feat: allow setting the width and height of a rule

fix: slider gradient angle

feat: gradient backgground for the slider rail

feat(mouse-area): added on_drag method

fix(widget): container inherited wrong icon color from renderer

fix(button): inherit icon color if set to none

feat(renderer): define default icon color

By default, this is the same as the text color for best visibility.

feat(winit): client-side resize drag support

feat(winit): client-side resize drag support

Make vertical scroll properties optional

fix: quad rendering including border only inside of the bounds

Move `Screenshot` inside `window` module

Added offscreen rendering support for wgpu & tiny-skia exposed with the window::screenshot command.

Provide access to font from each crate

Use nested for lazy widgets

Use layout with children for nesting

Introduce internal `overlay::Nested` for `UserInterface`

fix: reset button state if the cursor leaves

runtime: Handle widget operations in `program::State` helper (#46)

chore: default line height, text size, and shaping for cosmic

feat: sctk shell

fix: quad rendering including border only inside of the bounds

fix: better slider drawing (it allows just the border part of the handle quad outside of the layout bouds, which isn't great, but is ok for our purposes due to being transparent)

cleanup: fix & format

fix: use iced_core::Font

cleanup

fix: allow leaving out winit & iced-sctk

fix: settings

fix: slider draw improvements

fix: websocket example

fix: modal example

fix: scrollable example

fix: toast example

fix: avoid panicking in iced_sctk with lazy widgets in auto-size surfaces

fix: todos panic

fix: only diff auto-sized surfaces in iced_sctk build_user_interface & improve sctk examples

wip (iced-sctk): window resize with icons

feat (iced-sctk): support for setting cursor

refactor: default decorations to client

fix: set window geometry after receiving configure

fix: size limits with no max bound must be cut off

fix: send size update when autosized surface resizes

fix: use ceil size for positioner

cleanup: remove dbg statement

fix: remove a destroyed surface from compositor surfaces

fix errors after rebase and wip scaling support

fix: handling of scale factor in set_logical_size

fix (sctk_drag example): add .into for border radius

fix: fractional scaling

sctk: Fire RedrawRequests

wip: animations via frame event

fix / refactor iced-sctk redraw & frame event handling

cleanup: note about frame request in iced-sctk

fix: send resize when necessary for layer surface and popups too

fix: always request redraw for a new surface

fix: scaling and autosize surface improvements

refactor: sctk_lazy keyboard interactivity

feat(sctk): configurable natural_scroll property

feat: send state and capabilities events when there are changes

fix: redraw when an update is needed and clean up the logic

Update sctk to latest commit

Fix compilation of sctk drag example

fix(sctk): update interface before checking if it has a redraw request

refactor: after autosize surface resize wait to redraw until the resize has been applied

refactor: better handling of autosize surfaces

chore: update sctk

chore: update sctk

fixes sctk_drag example

fix: default to ControlFlow::Wait for applications with no surface

this seems to help CPU usage for app library and launcher

default to 250ms timeout in the event loop

Update sctk

sctk: Implement xdg-activation support

fix: don't require Flags to be clone for settings on wayland

chore: error if neither winit or wayland feature is set

chore: Allow compiling without windowing system (#65)

fix(iced-sctk): handle exit_on_close_request

fix: make sure that each widget operation operates on every interface

This should be ok even for widget actions like focus next because there can only ever be a single focused widget

cargo fmt

cleanup: dbg statement

fix(iced-sctk): replace panic with handling for remaining enum variants

refactor: use iced clipboard for interacting with the selection

refactor: allow passing an activation token when creating a window

sctk: Add support for `ext-session-lock` protocol

fix(sctk): build and use tree for layout of autosize surfaces

Update winit to latest commit used by upstream iced

fix(sctk): send key characters

fix(sctk): check if key is a named key first

refactor(sctk): keep compositor surface in state

feat: accessibility with some widget impls

feat: stable ids

a11y: Don't unconditionally pull winit (#43)

Update conversion.rs

integration fixes

integration

integration

integration

integration

s

integration

some integration work

more integration

Update Cargo.toml

Update mod.rs

Update multi_window.rs

s

more integration

more integration (ryanabx wip #100000)

more integration!!

integration 2

integration

more integration (rbx)

s

integration

integration work

integration

Update Cargo.toml

integration

simple integration things

int

integration to 175

integration(170)

Co-Authored-By: Ashley Wulber <48420062+wash2@users.noreply.github.com>
Co-Authored-By: Victoria Brekenfeld <4404502+Drakulix@users.noreply.github.com>
Co-Authored-By: Eduardo Flores <edfloreshz@gmail.com>
Co-Authored-By: Michael Murphy <michael@mmurphy.dev>
Co-Authored-By: wiiznokes <78230769+wiiznokes@users.noreply.github.com>
Co-Authored-By: Jeremy Soller <jeremy@system76.com>
Co-Authored-By: Ryan Brue <56272643+ryanabx@users.noreply.github.com>

fix(column): handle keys len change

fix: iced-sctk a11y

wip: winit single window updates

tokio feature hangs even without a11y feature

fix: multiwindow a11y fixes

fix: component

update winit

wip: sctk integration to winit shell

refactor: remove accesskit_unix

fix: svg

fix: remove wayland default feature

feat: derive Hash for image Handle

fix: cleanup 0.13 rebase errors

fix: remove path dependencies

conversion for Radius

conversion for Padding

setter for Svg border radius

re-export Limits

fix: connect clipboard if disconnected on layer surface or popup creation

fix: connect clipboard if disconnected on session lock surface creation

fix: update size of layer surface after configure

fix: insert user interfaces for popup and lock surfaces on creation

fix: svg scaling

feat: popups on winit windows

fix: default text shaping to advanced

fix: fallback to renderer icon style if svg is symbolic

fixes

fix: sctk frame handling

feat: autosize handling

fix: better autosize handling

fix: avoid duplicate window events from sctk

fix: better handling of popups

fix: refactor redraw handling for sctk

fix: include id in frames

fix: image

fix: scrollable delta direction

sctk: unregister clipboard when surface is done

set min / max size when size is requested

fix: popups

filter pointer events

feat: add Hide variant to mouse Interaction

dnd fixes

fix: use physical width for DnD surface

fix: tiny-skia svg quality

refactor: peek_dnd try to parse data

cleanup text conversion

cleanup

svg scaling fixes

background color fix

Introduce consecutive_click_distance like other toolkits do such as gtk,qt,imgui.
This commit is contained in:
Ashley Wulber 2023-05-02 15:48:20 -07:00
parent 595af03a9f
commit 08fe1f3aa5
No known key found for this signature in database
GPG key ID: 5216D4F46A90A820
233 changed files with 24391 additions and 1911 deletions

View file

@ -10,12 +10,16 @@ homepage.workspace = true
categories.workspace = true
keywords.workspace = true
[features]
selector = ["dep:iced_selector"]
[lints]
workspace = true
[features]
debug = []
selector = ["dep:iced_selector"]
multi-window = []
a11y = ["iced_accessibility", "iced_core/a11y"]
wayland = ["iced_core/wayland", "sctk"]
[dependencies]
bytes.workspace = true
iced_core.workspace = true
@ -29,3 +33,10 @@ sipper.optional = true
iced_selector.workspace = true
iced_selector.optional = true
iced_futures.features = ["thread-pool"]
sctk.workspace = true
sctk.optional = true
iced_accessibility.workspace = true
iced_accessibility.optional = true
window_clipboard.workspace = true
dnd.workspace = true

View file

@ -1,4 +1,6 @@
//! Access the clipboard.
use window_clipboard::mime::{AllowedMimeTypes, AsMimeTypes};
use crate::core::clipboard::Kind;
use crate::futures::futures::channel::oneshot;
use crate::task::{self, Task};
@ -6,9 +8,8 @@ use crate::task::{self, Task};
/// A clipboard action to be performed by some [`Task`].
///
/// [`Task`]: crate::Task
#[derive(Debug)]
pub enum Action {
/// Read the clipboard and produce `T` with the result.
/// Read the clipboard and produce `String` with the result.
Read {
/// The clipboard target.
target: Kind,
@ -23,6 +24,40 @@ pub enum Action {
/// The contents to be written.
contents: String,
},
/// Write the given contents to the clipboard.
WriteData(Box<dyn AsMimeTypes + Send + Sync + 'static>, Kind),
#[allow(clippy::type_complexity)]
/// Read the clipboard and produce `T` with the result.
ReadData(
Vec<String>,
oneshot::Sender<Option<(Vec<u8>, String)>>,
// Box<dyn Fn(Option<(Vec<u8>, String)>) -> T + Send + 'static>,
Kind,
),
}
impl std::fmt::Debug for Action {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Read { channel: _, target } => {
write!(f, "Action::Read{target:?}")
}
Self::Write {
contents: _,
target,
} => {
write!(f, "Action::Write({target:?})")
}
Self::WriteData(_, target) => {
write!(f, "Action::WriteData({target:?})")
}
Self::ReadData(_, _, target) => {
write!(f, "Action::ReadData({target:?})")
}
}
}
}
/// Read the current contents of the clipboard.
@ -60,3 +95,47 @@ pub fn write_primary<Message>(contents: String) -> Task<Message> {
contents,
}))
}
/// Read the current contents of the clipboard.
pub fn read_data<T: AllowedMimeTypes>() -> Task<Option<T>> {
task::oneshot(|tx| {
crate::Action::Clipboard(Action::ReadData(
T::allowed().into(),
tx,
Kind::Standard,
))
})
.map(|d| d.and_then(|d| T::try_from(d).ok()))
}
/// Write the given contents to the clipboard.
pub fn write_data<Message>(
contents: impl AsMimeTypes + std::marker::Sync + std::marker::Send + 'static,
) -> Task<Message> {
task::effect(crate::Action::Clipboard(Action::WriteData(
Box::new(contents),
Kind::Standard,
)))
}
/// Read from the primary clipboard
pub fn read_primary_data<T: AllowedMimeTypes>() -> Task<Option<T>> {
task::oneshot(|tx| {
crate::Action::Clipboard(Action::ReadData(
T::allowed().into(),
tx,
// Box::new(move |d| f(d.and_then(|d| T::try_from(d).ok()))),
Kind::Primary,
))
})
.map(|d| d.and_then(|d| T::try_from(d).ok()))
}
/// Write the given contents to the clipboard.
pub fn write_primary_data<Message>(
contents: impl AsMimeTypes + std::marker::Sync + std::marker::Send + 'static,
) -> Task<Message> {
task::effect(crate::Action::Clipboard(Action::WriteData(
Box::new(contents),
Kind::Primary,
)))
}

129
runtime/src/dnd.rs Normal file
View file

@ -0,0 +1,129 @@
//! Access the clipboard.
use std::any::Any;
use bytes::buf::Take;
use dnd::{DndDestinationRectangle, DndSurface};
use iced_core::{clipboard::DndSource, Vector};
use iced_futures::MaybeSend;
use window_clipboard::mime::{AllowedMimeTypes, AsMimeTypes};
use crate::{oneshot, task, Action, Task};
/// An action to be performed on the system.
pub enum DndAction {
/// Register a Dnd destination.
RegisterDndDestination {
/// The surface to register.
surface: DndSurface,
/// The rectangles to register.
rectangles: Vec<DndDestinationRectangle>,
},
/// Start a Dnd operation.
StartDnd {
/// Whether the Dnd operation is internal.
internal: bool,
/// The source surface of the Dnd operation.
source_surface: Option<DndSource>,
/// The icon surface of the Dnd operation.
icon_surface: Option<Box<dyn Any + Send>>,
/// The content of the Dnd operation.
content: Box<dyn AsMimeTypes + Send + 'static>,
/// The actions of the Dnd operation.
actions: dnd::DndAction,
},
/// End a Dnd operation.
EndDnd,
/// Peek the current Dnd operation.
PeekDnd(
String,
oneshot::Sender<Option<(Vec<u8>, String)>>,
// Box<dyn Fn(Option<(Vec<u8>, String)>) -> T + Send + 'static>,
),
/// Set the action of the Dnd operation.
SetAction(dnd::DndAction),
}
impl std::fmt::Debug for DndAction {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::RegisterDndDestination {
surface,
rectangles,
} => f
.debug_struct("RegisterDndDestination")
.field("surface", surface)
.field("rectangles", rectangles)
.finish(),
Self::StartDnd {
internal,
source_surface,
icon_surface,
content: _,
actions,
} => f
.debug_struct("StartDnd")
.field("internal", internal)
.field("source_surface", source_surface)
.field("icon_surface", icon_surface)
.field("actions", actions)
.finish(),
Self::EndDnd => f.write_str("EndDnd"),
Self::PeekDnd(mime, _) => {
f.debug_struct("PeekDnd").field("mime", mime).finish()
}
Self::SetAction(a) => f.debug_tuple("SetAction").field(a).finish(),
}
}
}
/// Read the current contents of the Dnd operation.
pub fn peek_dnd<T: AllowedMimeTypes>() -> Task<Option<T>> {
task::oneshot(|tx| {
Action::Dnd(DndAction::PeekDnd(
T::allowed()
.get(0)
.map_or_else(|| String::new(), |s| s.to_string()),
tx,
))
})
.map(|data| data.and_then(|data| T::try_from(data).ok()))
}
/// Register a Dnd destination.
pub fn register_dnd_destination<Message>(
surface: DndSurface,
rectangles: Vec<DndDestinationRectangle>,
) -> Task<Message> {
task::effect(Action::Dnd(DndAction::RegisterDndDestination {
surface,
rectangles,
}))
}
/// Start a Dnd operation.
pub fn start_dnd<Message>(
internal: bool,
source_surface: Option<DndSource>,
icon_surface: Option<Box<dyn Any + Send>>,
content: Box<dyn AsMimeTypes + Send + 'static>,
actions: dnd::DndAction,
) -> Task<Message> {
task::effect(Action::Dnd(DndAction::StartDnd {
internal,
source_surface,
icon_surface,
content,
actions,
}))
}
/// End a Dnd operation.
pub fn end_dnd<Message>() -> Task<Message> {
task::effect(Action::Dnd(DndAction::EndDnd))
}
/// Set the action of the Dnd operation.
pub fn set_action<Message>(a: dnd::DndAction) -> Task<Message> {
task::effect(Action::Dnd(DndAction::SetAction(a)))
}

View file

@ -10,9 +10,11 @@
)]
#![cfg_attr(docsrs, feature(doc_cfg))]
pub mod clipboard;
pub mod dnd;
pub mod font;
pub mod image;
pub mod keyboard;
pub mod platform_specific;
pub mod system;
pub mod task;
pub mod user_interface;
@ -27,6 +29,7 @@ pub use user_interface::UserInterface;
pub use window::Window;
use crate::futures::futures::channel::oneshot;
use dnd::DndAction;
use std::borrow::Cow;
use std::fmt;
@ -67,6 +70,11 @@ pub enum Action<T> {
/// This will normally close any application windows and
/// terminate the runtime loop.
Exit,
/// Run a Dnd action.
Dnd(crate::dnd::DndAction),
/// Run a platform specific action
PlatformSpecific(crate::platform_specific::Action),
}
impl<T> Action<T> {
@ -88,6 +96,8 @@ impl<T> Action<T> {
Action::Image(action) => Err(Action::Image(action)),
Action::Reload => Err(Action::Reload),
Action::Exit => Err(Action::Exit),
Action::Dnd(a) => Err(Action::Dnd(a)),
Action::PlatformSpecific(a) => Err(Action::PlatformSpecific(a)),
}
}
}
@ -113,6 +123,10 @@ where
Action::Image(_) => write!(f, "Action::Image"),
Action::Reload => write!(f, "Action::Reload"),
Action::Exit => write!(f, "Action::Exit"),
Action::PlatformSpecific(action) => {
write!(f, "Action::PlatformSpecific({:?})", action)
}
Action::Dnd(action) => write!(f, "Action::Dnd({:?})", action),
}
}
}
@ -124,3 +138,39 @@ where
pub fn exit<T>() -> Task<T> {
task::effect(Action::Exit)
}
/// The appearance of a program.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Appearance {
/// The background [`Color`] of the application.
pub background_color: iced_core::Color,
/// The default text [`Color`] of the application.
pub text_color: iced_core::Color,
/// The default icon [`Color`] of the application.
pub icon_color: iced_core::Color,
}
/// The default style of a [`Program`].
pub trait DefaultStyle {
/// Returns the default style of a [`Program`].
fn default_style(&self) -> Appearance;
}
impl DefaultStyle for iced_core::Theme {
fn default_style(&self) -> Appearance {
default(self)
}
}
/// The default [`Appearance`] of a [`Program`] with the built-in [`Theme`].
pub fn default(theme: &iced_core::Theme) -> Appearance {
let palette = theme.extended_palette();
Appearance {
background_color: palette.background.base.color,
text_color: palette.background.base.text,
icon_color: palette.background.base.text,
}
}

View file

@ -0,0 +1,279 @@
//! The internal state of a multi-window [`Program`].
use crate::core::event::{self, Event};
use crate::core::mouse;
use crate::core::renderer;
use crate::core::widget::operation::{self, Operation};
use crate::core::{Clipboard, Size};
use crate::user_interface::{self, UserInterface};
use crate::{Debug, Program, Task};
/// The execution state of a multi-window [`Program`]. It leverages caching, event
/// processing, and rendering primitive storage.
#[allow(missing_debug_implementations)]
pub struct State<P>
where
P: Program + 'static,
{
program: P,
caches: Option<Vec<user_interface::Cache>>,
queued_events: Vec<Event>,
queued_messages: Vec<P::Message>,
mouse_interaction: mouse::Interaction,
}
impl<P> State<P>
where
P: Program + 'static,
{
/// Creates a new [`State`] with the provided [`Program`], initializing its
/// primitive with the given logical bounds and renderer.
pub fn new(
program: P,
bounds: Size,
renderer: &mut P::Renderer,
debug: &mut Debug,
) -> Self {
let user_interface = build_user_interface(
&program,
user_interface::Cache::default(),
renderer,
bounds,
debug,
);
let caches = Some(vec![user_interface.into_cache()]);
State {
program,
caches,
queued_events: Vec::new(),
queued_messages: Vec::new(),
mouse_interaction: mouse::Interaction::None,
}
}
/// Returns a reference to the [`Program`] of the [`State`].
pub fn program(&self) -> &P {
&self.program
}
/// Queues an event in the [`State`] for processing during an [`update`].
///
/// [`update`]: Self::update
pub fn queue_event(&mut self, event: Event) {
self.queued_events.push(event);
}
/// Queues a message in the [`State`] for processing during an [`update`].
///
/// [`update`]: Self::update
pub fn queue_message(&mut self, message: P::Message) {
self.queued_messages.push(message);
}
/// Returns whether the event queue of the [`State`] is empty or not.
pub fn is_queue_empty(&self) -> bool {
self.queued_events.is_empty() && self.queued_messages.is_empty()
}
/// Returns the current [`mouse::Interaction`] of the [`State`].
pub fn mouse_interaction(&self) -> mouse::Interaction {
self.mouse_interaction
}
/// Processes all the queued events and messages, rebuilding and redrawing
/// the widgets of the linked [`Program`] if necessary.
///
/// Returns a list containing the instances of [`Event`] that were not
/// captured by any widget, and the [`Task`] obtained from [`Program`]
/// after updating it, only if an update was necessary.
pub fn update(
&mut self,
bounds: Size,
cursor: mouse::Cursor,
renderer: &mut P::Renderer,
theme: &P::Theme,
style: &renderer::Style,
clipboard: &mut dyn Clipboard,
debug: &mut Debug,
) -> (Vec<Event>, Option<Task<P::Message>>) {
let mut user_interfaces = build_user_interfaces(
&self.program,
self.caches.take().unwrap(),
renderer,
bounds,
debug,
);
debug.event_processing_started();
let mut messages = Vec::new();
let uncaptured_events = user_interfaces.iter_mut().fold(
vec![],
|mut uncaptured_events, ui| {
let (_, event_statuses) = ui.update(
&self.queued_events,
cursor,
renderer,
clipboard,
&mut messages,
);
uncaptured_events.extend(
self.queued_events
.iter()
.zip(event_statuses)
.filter_map(|(event, status)| {
matches!(status, event::Status::Ignored)
.then_some(event)
})
.cloned(),
);
uncaptured_events
},
);
self.queued_events.clear();
messages.append(&mut self.queued_messages);
debug.event_processing_finished();
let commands = if messages.is_empty() {
debug.draw_started();
for ui in &mut user_interfaces {
self.mouse_interaction =
ui.draw(renderer, theme, style, cursor);
}
debug.draw_finished();
self.caches = Some(
user_interfaces
.drain(..)
.map(UserInterface::into_cache)
.collect(),
);
None
} else {
let temp_caches = user_interfaces
.drain(..)
.map(UserInterface::into_cache)
.collect();
drop(user_interfaces);
let commands = Task::batch(messages.into_iter().map(|msg| {
debug.log_message(&msg);
debug.update_started();
let task = self.program.update(msg);
debug.update_finished();
task
}));
let mut user_interfaces = build_user_interfaces(
&self.program,
temp_caches,
renderer,
bounds,
debug,
);
debug.draw_started();
for ui in &mut user_interfaces {
self.mouse_interaction =
ui.draw(renderer, theme, style, cursor);
}
debug.draw_finished();
self.caches = Some(
user_interfaces
.drain(..)
.map(UserInterface::into_cache)
.collect(),
);
Some(commands)
};
(uncaptured_events, commands)
}
/// Applies widget [`Operation`]s to the [`State`].
pub fn operate(
&mut self,
renderer: &mut P::Renderer,
operations: impl Iterator<Item = Box<dyn Operation>>,
bounds: Size,
debug: &mut Debug,
) {
let mut user_interfaces = build_user_interfaces(
&self.program,
self.caches.take().unwrap(),
renderer,
bounds,
debug,
);
for operation in operations {
let mut current_operation = Some(operation);
while let Some(mut operation) = current_operation.take() {
for ui in &mut user_interfaces {
ui.operate(renderer, operation.as_mut());
}
match operation.finish() {
operation::Outcome::None => {}
operation::Outcome::Some(()) => {}
operation::Outcome::Chain(next) => {
current_operation = Some(next);
}
_ => {}
};
}
}
self.caches = Some(
user_interfaces
.drain(..)
.map(UserInterface::into_cache)
.collect(),
);
}
}
fn build_user_interfaces<'a, P: Program>(
program: &'a P,
mut caches: Vec<user_interface::Cache>,
renderer: &mut P::Renderer,
size: Size,
debug: &mut Debug,
) -> Vec<UserInterface<'a, P::Message, P::Theme, P::Renderer>> {
caches
.drain(..)
.map(|cache| {
build_user_interface(program, cache, renderer, size, debug)
})
.collect()
}
fn build_user_interface<'a, P: Program>(
program: &'a P,
cache: user_interface::Cache,
renderer: &mut P::Renderer,
size: Size,
debug: &mut Debug,
) -> UserInterface<'a, P::Message, P::Theme, P::Renderer> {
debug.view_started();
let view = program.view();
debug.view_finished();
debug.layout_started();
let user_interface = UserInterface::build(view, size, cache, renderer);
debug.layout_finished();
user_interface
}

View file

@ -0,0 +1,26 @@
//! Platform specific actions defined for wayland
use std::{fmt, marker::PhantomData};
use iced_futures::MaybeSend;
#[cfg(feature = "wayland")]
/// Platform specific actions defined for wayland
pub mod wayland;
/// Platform specific actions defined for wayland
pub enum Action {
/// Wayland Specific Actions
#[cfg(feature = "wayland")]
Wayland(wayland::Action),
}
impl fmt::Debug for Action {
fn fmt(&self, _f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
#[cfg(feature = "wayland")]
Action::Wayland(action) => action.fmt(_f),
_ => Ok(()),
}
}
}

View file

@ -0,0 +1,42 @@
use iced_core::window::Id;
use std::fmt;
use crate::oneshot;
/// xdg-activation Actions
pub enum Action {
/// request an activation token
RequestToken {
/// application id
app_id: Option<String>,
/// window, if provided
window: Option<Id>,
/// message generation
channel: oneshot::Sender<Option<String>>,
},
/// request a window to be activated
Activate {
/// window to activate
window: Id,
/// activation token
token: String,
},
}
impl fmt::Debug for Action {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Action::RequestToken { app_id, window, .. } => write!(
f,
"Action::ActivationAction::RequestToken {{ app_id: {:?}, window: {:?} }}",
app_id, window,
),
Action::Activate { window, token } => write!(
f,
"Action::ActivationAction::Activate {{ window: {:?}, token: {:?} }}",
window, token,
)
}
}
}

View file

@ -0,0 +1,185 @@
use std::fmt;
use iced_core::layout::Limits;
use sctk::{
reexports::client::protocol::wl_output::WlOutput,
shell::wlr_layer::{Anchor, KeyboardInteractivity, Layer},
};
use iced_core::window::Id;
/// output for layer surface
#[derive(Debug, Clone)]
pub enum IcedOutput {
/// show on all outputs
All,
/// show on active output
Active,
/// show on a specific output
Output(WlOutput),
}
impl Default for IcedOutput {
fn default() -> Self {
Self::Active
}
}
/// margins of the layer surface
#[derive(Debug, Clone, Copy, Default)]
pub struct IcedMargin {
/// top
pub top: i32,
/// right
pub right: i32,
/// bottom
pub bottom: i32,
/// left
pub left: i32,
}
/// layer surface
#[derive(Debug, Clone)]
pub struct SctkLayerSurfaceSettings {
/// XXX id must be unique for every surface, window, and popup
pub id: Id,
/// layer
pub layer: Layer,
/// keyboard interactivity
pub keyboard_interactivity: KeyboardInteractivity,
/// pointer interactivity
pub pointer_interactivity: bool,
/// anchor, if a surface is anchored to two opposite edges, it will be stretched to fit between those edges, regardless of the specified size in that dimension.
pub anchor: Anchor,
/// output
pub output: IcedOutput,
/// namespace
pub namespace: String,
/// margin
pub margin: IcedMargin,
/// XXX size, providing None will autosize the layer surface to its contents
/// If Some size is provided, None in a given dimension lets the compositor decide for that dimension, usually this would be done with a layer surface that is anchored to left & right or top & bottom
pub size: Option<(Option<u32>, Option<u32>)>,
/// exclusive zone
pub exclusive_zone: i32,
/// Limits of the popup size
pub size_limits: Limits,
}
impl Default for SctkLayerSurfaceSettings {
fn default() -> Self {
Self {
id: Id::unique(),
layer: Layer::Top,
keyboard_interactivity: Default::default(),
pointer_interactivity: true,
anchor: Anchor::empty(),
output: Default::default(),
namespace: Default::default(),
margin: Default::default(),
size: Default::default(),
exclusive_zone: Default::default(),
size_limits: Limits::NONE
.min_height(1.0)
.min_width(1.0)
.max_width(1920.0)
.max_height(1080.023),
}
}
}
#[derive(Clone)]
/// LayerSurface Action
pub enum Action {
/// create a layer surface and receive a message with its Id
LayerSurface {
/// surface builder
builder: SctkLayerSurfaceSettings,
},
/// Set size of the layer surface.
Size {
/// id of the layer surface
id: Id,
/// The new logical width of the window
width: Option<u32>,
/// The new logical height of the window
height: Option<u32>,
},
/// Destroy the layer surface
Destroy(Id),
/// The edges which the layer surface is anchored to
Anchor {
/// id of the layer surface
id: Id,
/// anchor of the layer surface
anchor: Anchor,
},
/// exclusive zone of the layer surface
ExclusiveZone {
/// id of the layer surface
id: Id,
/// exclusive zone of the layer surface
exclusive_zone: i32,
},
/// margin of the layer surface, ignored for un-anchored edges
Margin {
/// id of the layer surface
id: Id,
/// margins of the layer surface
margin: IcedMargin,
},
/// keyboard interactivity of the layer surface
KeyboardInteractivity {
/// id of the layer surface
id: Id,
/// keyboard interactivity of the layer surface
keyboard_interactivity: KeyboardInteractivity,
},
/// layer of the layer surface
Layer {
/// id of the layer surface
id: Id,
/// layer of the layer surface
layer: Layer,
},
}
impl fmt::Debug for Action {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Action::LayerSurface { builder, .. } => write!(
f,
"Action::LayerSurfaceAction::LayerSurface {{ builder: {:?} }}",
builder
),
Action::Size { id, width, height } => write!(
f,
"Action::LayerSurfaceAction::Size {{ id: {:#?}, width: {:?}, height: {:?} }}", id, width, height
),
Action::Destroy(id) => write!(
f,
"Action::LayerSurfaceAction::Destroy {{ id: {:#?} }}", id
),
Action::Anchor { id, anchor } => write!(
f,
"Action::LayerSurfaceAction::Anchor {{ id: {:#?}, anchor: {:?} }}", id, anchor
),
Action::ExclusiveZone { id, exclusive_zone } => write!(
f,
"Action::LayerSurfaceAction::ExclusiveZone {{ id: {:#?}, exclusive_zone: {exclusive_zone} }}", id
),
Action::Margin { id, margin } => write!(
f,
"Action::LayerSurfaceAction::Margin {{ id: {:#?}, margin: {:?} }}", id, margin
),
Action::KeyboardInteractivity { id, keyboard_interactivity } => write!(
f,
"Action::LayerSurfaceAction::Margin {{ id: {:#?}, keyboard_interactivity: {:?} }}", id, keyboard_interactivity
),
Action::Layer { id, layer } => write!(
f,
"Action::LayerSurfaceAction::Margin {{ id: {:#?}, layer: {:?} }}", id, layer
),
}
}
}

View file

@ -0,0 +1,42 @@
//! Wayland specific actions
use std::fmt::Debug;
/// activation Actions
pub mod activation;
/// layer surface actions
pub mod layer_surface;
/// popup actions
pub mod popup;
/// session locks
pub mod session_lock;
/// Platform specific actions defined for wayland
pub enum Action {
/// LayerSurface Actions
LayerSurface(layer_surface::Action),
/// popup
Popup(popup::Action),
/// activation
Activation(activation::Action),
/// session lock
SessionLock(session_lock::Action),
}
impl Debug for Action {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::LayerSurface(arg0) => {
f.debug_tuple("LayerSurface").field(arg0).finish()
}
Self::Popup(arg0) => f.debug_tuple("Popup").field(arg0).finish(),
Self::Activation(arg0) => {
f.debug_tuple("Activation").field(arg0).finish()
}
Self::SessionLock(arg0) => {
f.debug_tuple("SessionLock").field(arg0).finish()
}
}
}
}

View file

@ -0,0 +1,141 @@
use std::fmt;
use std::hash::{Hash, Hasher};
use iced_core::layout::Limits;
use iced_core::window::Id;
use iced_core::Rectangle;
use sctk::reexports::protocols::xdg::shell::client::xdg_positioner::{
Anchor, Gravity,
};
/// Popup creation details
#[derive(Debug, Clone)]
pub struct SctkPopupSettings {
/// XXX must be unique, id of the parent
pub parent: Id,
/// XXX must be unique, id of the popup
pub id: Id,
/// positioner of the popup
pub positioner: SctkPositioner,
/// optional parent size, must be correct if specified or the behavior is undefined
pub parent_size: Option<(u32, u32)>,
/// whether a grab should be requested for the popup after creation
pub grab: bool,
}
impl Hash for SctkPopupSettings {
fn hash<H: Hasher>(&self, state: &mut H) {
self.id.hash(state);
}
}
/// Positioner of a popup
#[derive(Debug, Clone)]
pub struct SctkPositioner {
/// size of the popup (if it is None, the popup will be autosized)
pub size: Option<(u32, u32)>,
/// Limits of the popup size
pub size_limits: Limits,
/// the rectangle which the popup will be anchored to
pub anchor_rect: Rectangle<i32>,
/// the anchor location on the popup
pub anchor: Anchor,
/// the gravity of the popup
pub gravity: Gravity,
/// the constraint adjustment,
/// Specify how the window should be positioned if the originally intended position caused the surface to be constrained, meaning at least partially outside positioning boundaries set by the compositor. The adjustment is set by constructing a bitmask describing the adjustment to be made when the surface is constrained on that axis.
/// If no bit for one axis is set, the compositor will assume that the child surface should not change its position on that axis when constrained.
///
/// If more than one bit for one axis is set, the order of how adjustments are applied is specified in the corresponding adjustment descriptions.
///
/// The default adjustment is none.
pub constraint_adjustment: u32,
/// offset of the popup
pub offset: (i32, i32),
/// whether the popup is reactive
pub reactive: bool,
}
impl Hash for SctkPositioner {
fn hash<H: Hasher>(&self, state: &mut H) {
self.size.hash(state);
self.anchor_rect.x.hash(state);
self.anchor_rect.y.hash(state);
self.anchor_rect.width.hash(state);
self.anchor_rect.height.hash(state);
self.anchor.hash(state);
self.gravity.hash(state);
self.constraint_adjustment.hash(state);
self.offset.hash(state);
self.reactive.hash(state);
}
}
impl Default for SctkPositioner {
fn default() -> Self {
Self {
size: None,
size_limits: Limits::NONE
.min_height(1.0)
.min_width(1.0)
.max_width(300.0)
.max_height(1080.0),
anchor_rect: Rectangle {
x: 0,
y: 0,
width: 1,
height: 1,
},
anchor: Anchor::None,
gravity: Gravity::None,
constraint_adjustment: 15,
offset: Default::default(),
reactive: true,
}
}
}
#[derive(Clone)]
/// Window Action
pub enum Action {
/// create a window and receive a message with its Id
Popup {
/// popup
popup: SctkPopupSettings,
},
/// destroy the popup
Destroy {
/// id of the popup
id: Id,
},
/// set the size of the popup
Size {
/// id of the popup
id: Id,
/// width
width: u32,
/// height
height: u32,
},
}
impl fmt::Debug for Action {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Action::Popup { popup, .. } => write!(
f,
"Action::PopupAction::Popup {{ popup: {:?} }}",
popup
),
Action::Destroy { id } => write!(
f,
"Action::PopupAction::Destroy {{ id: {:?} }}",
id
),
Action::Size { id, width, height } => write!(
f,
"Action::PopupAction::Size {{ id: {:?}, width: {:?}, height: {:?} }}",
id, width, height
),
}
}
}

View file

@ -0,0 +1,45 @@
use std::fmt;
use iced_core::window::Id;
use sctk::reexports::client::protocol::wl_output::WlOutput;
/// Session lock action
#[derive(Clone)]
pub enum Action {
/// Request a session lock
Lock,
/// Destroy lock
Unlock,
/// Create lock surface for output
LockSurface {
/// unique id for surface
id: Id,
/// output
output: WlOutput,
},
/// Destroy lock surface
DestroyLockSurface {
/// unique id for surface
id: Id,
},
}
impl fmt::Debug for Action {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Action::Lock => write!(f, "Action::SessionLock::Lock"),
Action::Unlock => write!(f, "Action::SessionLock::Unlock"),
Action::LockSurface { id, output } => write!(
f,
"Action::SessionLock::LockSurface {{ id: {:?}, output: {:?} }}",
id, output
),
Action::DestroyLockSurface { id } => write!(
f,
"Action::SessionLock::DestroyLockSurface {{ id: {:?} }}",
id
),
}
}
}

View file

@ -0,0 +1,240 @@
use iced_core::widget::operation::Outcome;
use crate::core::event::{self, Event};
use crate::core::mouse;
use crate::core::renderer;
use crate::core::widget::operation::{self, Operation};
use crate::core::{Clipboard, Size};
use crate::user_interface::{self, UserInterface};
use crate::{Debug, Program, Task};
/// The execution state of a [`Program`]. It leverages caching, event
/// processing, and rendering primitive storage.
#[allow(missing_debug_implementations)]
pub struct State<P>
where
P: Program + 'static,
{
program: P,
cache: Option<user_interface::Cache>,
queued_events: Vec<Event>,
queued_messages: Vec<P::Message>,
mouse_interaction: mouse::Interaction,
}
impl<P> State<P>
where
P: Program + 'static,
{
/// Creates a new [`State`] with the provided [`Program`], initializing its
/// primitive with the given logical bounds and renderer.
pub fn new(
id: iced_core::id::Id,
mut program: P,
bounds: Size,
renderer: &mut P::Renderer,
debug: &mut Debug,
) -> Self {
let user_interface = build_user_interface(
id,
&mut program,
user_interface::Cache::default(),
renderer,
bounds,
debug,
);
let cache = Some(user_interface.into_cache());
State {
program,
cache,
queued_events: Vec::new(),
queued_messages: Vec::new(),
mouse_interaction: mouse::Interaction::None,
}
}
/// Returns a reference to the [`Program`] of the [`State`].
pub fn program(&self) -> &P {
&self.program
}
/// Queues an event in the [`State`] for processing during an [`update`].
///
/// [`update`]: Self::update
pub fn queue_event(&mut self, event: Event) {
self.queued_events.push(event);
}
/// Queues a message in the [`State`] for processing during an [`update`].
///
/// [`update`]: Self::update
pub fn queue_message(&mut self, message: P::Message) {
self.queued_messages.push(message);
}
/// Returns whether the event queue of the [`State`] is empty or not.
pub fn is_queue_empty(&self) -> bool {
self.queued_events.is_empty() && self.queued_messages.is_empty()
}
/// Returns the current [`mouse::Interaction`] of the [`State`].
pub fn mouse_interaction(&self) -> mouse::Interaction {
self.mouse_interaction
}
/// Processes all the queued events and messages, rebuilding and redrawing
/// the widgets of the linked [`Program`] if necessary.
///
/// Returns a list containing the instances of [`Event`] that were not
/// captured by any widget, and the [`Task`] obtained from [`Program`]
/// after updating it, only if an update was necessary.
pub fn update(
&mut self,
id: iced_core::id::Id,
bounds: Size,
cursor: mouse::Cursor,
renderer: &mut P::Renderer,
theme: &P::Theme,
style: &renderer::Style,
clipboard: &mut dyn Clipboard,
debug: &mut Debug,
) -> (Vec<Event>, Option<Task<P::Message>>) {
let mut user_interface = build_user_interface(
id.clone(),
&mut self.program,
self.cache.take().unwrap(),
renderer,
bounds,
debug,
);
debug.event_processing_started();
let mut messages = Vec::new();
let (_, event_statuses) = user_interface.update(
&self.queued_events,
cursor,
renderer,
clipboard,
&mut messages,
);
let uncaptured_events = self
.queued_events
.iter()
.zip(event_statuses)
.filter_map(|(event, status)| {
matches!(status, event::Status::Ignored).then_some(event)
})
.cloned()
.collect();
self.queued_events.clear();
messages.append(&mut self.queued_messages);
debug.event_processing_finished();
let task = if messages.is_empty() {
debug.draw_started();
self.mouse_interaction =
user_interface.draw(renderer, theme, style, cursor);
debug.draw_finished();
self.cache = Some(user_interface.into_cache());
None
} else {
// When there are messages, we are forced to rebuild twice
// for now :^)
let temp_cache = user_interface.into_cache();
let tasks = Task::batch(messages.into_iter().map(|message| {
debug.log_message(&message);
debug.update_started();
let task = self.program.update(message);
debug.update_finished();
task
}));
let mut user_interface = build_user_interface(
id,
&mut self.program,
temp_cache,
renderer,
bounds,
debug,
);
debug.draw_started();
self.mouse_interaction =
user_interface.draw(renderer, theme, style, cursor);
debug.draw_finished();
self.cache = Some(user_interface.into_cache());
Some(tasks)
};
(uncaptured_events, task)
}
/// Applies [`Operation`]s to the [`State`]
pub fn operate(
&mut self,
id: iced_core::id::Id,
renderer: &mut P::Renderer,
operations: impl Iterator<Item = Box<dyn Operation>>,
bounds: Size,
debug: &mut Debug,
) {
let mut user_interface = build_user_interface(
id,
&mut self.program,
self.cache.take().unwrap(),
renderer,
bounds,
debug,
);
for operation in operations {
let mut current_operation = Some(operation);
while let Some(mut operation) = current_operation.take() {
user_interface.operate(renderer, operation.as_mut());
match operation.finish() {
operation::Outcome::None => {}
operation::Outcome::Some(()) => {}
operation::Outcome::Chain(next) => {
current_operation = Some(next);
}
_ => {}
};
}
}
self.cache = Some(user_interface.into_cache());
}
}
fn build_user_interface<'a, P: Program>(
_id: iced_core::id::Id,
program: &'a mut P,
cache: user_interface::Cache,
renderer: &mut P::Renderer,
size: Size,
debug: &mut Debug,
) -> UserInterface<'a, P::Message, P::Theme, P::Renderer> {
debug.view_started();
let view = program.view();
debug.view_finished();
debug.layout_started();
let user_interface = UserInterface::build(view, size, cache, renderer);
debug.layout_finished();
user_interface
}

View file

@ -1,4 +1,9 @@
//! Implement your own event loop to drive a user interface.
use iced_core::clipboard::DndDestinationRectangles;
use iced_core::widget::Operation;
use iced_core::widget::tree::NAMED;
use crate::core::event::{self, Event};
use crate::core::layout;
use crate::core::mouse;
@ -99,7 +104,12 @@ where
let mut root = root.into();
let Cache { mut state } = cache;
state.diff(root.as_widget());
NAMED.with(|named| {
let mut guard = named.borrow_mut();
*guard = state.take_all_named();
});
state.diff(root.as_widget_mut());
let base = root.as_widget_mut().layout(
&mut state,
@ -107,6 +117,10 @@ where
&layout::Limits::new(Size::ZERO, bounds),
);
NAMED.with(|named| {
named.borrow_mut().clear();
});
UserInterface {
root,
base,
@ -588,6 +602,40 @@ where
pub fn into_cache(self) -> Cache {
Cache { state: self.state }
}
/// get a11y nodes
#[cfg(feature = "a11y")]
pub fn a11y_nodes(
&self,
cursor: mouse::Cursor,
) -> iced_accessibility::A11yTree {
self.root.as_widget().a11y_nodes(
Layout::new(&self.base),
&self.state,
cursor,
)
}
/// Find widget with given id
pub fn find(&self, id: &widget::Id) -> Option<&widget::Tree> {
self.state.find(id)
}
/// Get the destination rectangles for the user interface.
pub fn dnd_rectangles(
&self,
prev_capacity: usize,
renderer: &Renderer,
) -> DndDestinationRectangles {
let mut ret = DndDestinationRectangles::with_capacity(prev_capacity);
self.root.as_widget().drag_destinations(
&self.state,
Layout::new(&self.base),
renderer,
&mut ret,
);
ret
}
}
/// Reusable data of a specific [`UserInterface`].
@ -615,7 +663,7 @@ impl Default for Cache {
}
/// The resulting state after updating a [`UserInterface`].
#[derive(Debug, Clone)]
#[derive(Clone)]
pub enum State {
/// The [`UserInterface`] is outdated and needs to be rebuilt.
Outdated,

View file

@ -205,9 +205,31 @@ impl<T> Window for T where T: HasWindowHandle + HasDisplayHandle {}
///
/// In any case, this [`Subscription`] is useful to smoothly draw application-driven
/// animations without missing any frames.
pub fn frames() -> Subscription<Instant> {
pub fn frames() -> Subscription<(Id, Instant)> {
event::listen_raw(|event, _status, window| match event {
crate::core::Event::Window(Event::RedrawRequested(at)) => {
Some((window, at))
}
_ => None,
})
}
#[cfg(feature = "wayland")]
/// Subscribes to the frames of the window of the running application.
///
/// The resulting [`Subscription`] will produce items at a rate equal to the
/// refresh rate of the window. Note that this rate may be variable, as it is
/// normally managed by the graphics driver and/or the OS.
///
/// In any case, this [`Subscription`] is useful to smoothly draw application-driven
/// animations without missing any frames.
pub fn wayland_frames() -> Subscription<Instant> {
event::listen_raw(|event, _status, _window| match event {
crate::core::Event::Window(Event::RedrawRequested(at)) => Some(at),
iced_core::Event::Window(Event::RedrawRequested(at))
| iced_core::Event::PlatformSpecific(
iced_core::event::PlatformSpecific::Wayland(
iced_core::event::wayland::Event::Frame(at, _, _),
),
) => Some(at),
_ => None,
})
}