iced-yoda/widget/src/helpers.rs

2125 lines
60 KiB
Rust
Raw Normal View History

//! Helper functions to create pure widgets.
use crate::button::{self, Button};
use crate::checkbox::{self, Checkbox};
use crate::combo_box::{self, ComboBox};
use crate::container::{self, Container};
use crate::core;
use crate::core::theme;
use crate::core::widget::operation::{self, Operation};
use crate::core::window;
use crate::core::{Element, Length, Size, Widget};
use crate::float::{self, Float};
2023-09-04 02:55:09 +02:00
use crate::keyed;
use crate::list::{self, List};
use crate::overlay;
use crate::pane_grid::{self, PaneGrid};
use crate::pick_list::{self, PickList};
use crate::progress_bar::{self, ProgressBar};
use crate::radio::{self, Radio};
use crate::scrollable::{self, Scrollable};
use crate::slider::{self, Slider};
use crate::text::{self, Text};
use crate::text_editor::{self, TextEditor};
use crate::text_input::{self, TextInput};
use crate::toggler::{self, Toggler};
use crate::tooltip::{self, Tooltip};
use crate::vertical_slider::{self, VerticalSlider};
use crate::{
Column, Grid, MouseArea, Pin, Responsive, Row, Sensor, Space, Stack, Themer,
};
use std::borrow::Borrow;
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 f39a5fd8953494fd8e41c05bc053519740d09612) 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.
2023-05-02 15:48:20 -07:00
use std::ops::RangeInclusive;
2025-07-15 05:28:33 +02:00
pub use crate::table::table;
/// Creates a [`Column`] with the given children.
///
/// Columns distribute their children vertically.
///
/// # Example
/// ```no_run
/// # mod iced { pub mod widget { pub use iced_widget::*; } }
/// # pub type State = ();
/// # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>;
/// use iced::widget::{button, column};
///
/// #[derive(Debug, Clone)]
/// enum Message {
/// // ...
/// }
///
/// fn view(state: &State) -> Element<'_, Message> {
/// column![
/// "I am on top!",
/// button("I am in the center!"),
/// "I am below.",
/// ].into()
/// }
/// ```
#[macro_export]
macro_rules! column {
() => (
$crate::Column::new()
);
($($x:expr),+ $(,)?) => (
$crate::Column::with_children([$($crate::core::Element::from($x)),+])
);
}
/// Creates a [`Row`] with the given children.
///
/// Rows distribute their children horizontally.
///
/// # Example
/// ```no_run
/// # mod iced { pub mod widget { pub use iced_widget::*; } }
/// # pub type State = ();
/// # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>;
/// use iced::widget::{button, row};
///
/// #[derive(Debug, Clone)]
/// enum Message {
/// // ...
/// }
///
/// fn view(state: &State) -> Element<'_, Message> {
/// row![
/// "I am to the left!",
/// button("I am in the middle!"),
/// "I am to the right!",
/// ].into()
/// }
/// ```
#[macro_export]
macro_rules! row {
() => (
$crate::Row::new()
);
($($x:expr),+ $(,)?) => (
$crate::Row::with_children([$($crate::core::Element::from($x)),+])
);
}
/// Creates a [`Stack`] with the given children.
///
/// [`Stack`]: crate::Stack
#[macro_export]
macro_rules! stack {
() => (
$crate::Stack::new()
);
($($x:expr),+ $(,)?) => (
$crate::Stack::with_children([$($crate::core::Element::from($x)),+])
);
}
2025-04-26 10:30:12 +02:00
/// Creates a [`Grid`] with the given children.
///
/// [`Grid`]: crate::Grid
#[macro_export]
macro_rules! grid {
() => (
$crate::Grid::new()
);
($($x:expr),+ $(,)?) => (
$crate::Grid::with_children([$($crate::core::Element::from($x)),+])
);
}
/// Creates a new [`Text`] widget with the provided content.
///
/// [`Text`]: core::widget::Text
///
/// This macro uses the same syntax as [`format!`], but creates a new [`Text`] widget instead.
///
/// See [the formatting documentation in `std::fmt`](std::fmt)
/// for details of the macro argument syntax.
///
/// # Examples
///
/// ```no_run
/// # mod iced {
/// # pub mod widget {
/// # macro_rules! text {
/// # ($($arg:tt)*) => {unimplemented!()}
/// # }
/// # pub(crate) use text;
/// # }
/// # }
/// # pub type State = ();
/// # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::core::Theme, ()>;
/// use iced::widget::text;
///
/// enum Message {
/// // ...
/// }
///
/// fn view(_state: &State) -> Element<Message> {
/// let simple = text!("Hello, world!");
2024-03-18 18:30:29 -03:00
///
/// let keyword = text!("Hello, {}", "world!");
2024-03-18 18:30:29 -03:00
///
/// let planet = "Earth";
/// let local_variable = text!("Hello, {planet}!");
/// // ...
/// # unimplemented!()
/// }
/// ```
#[macro_export]
macro_rules! text {
($($arg:tt)*) => {
$crate::Text::new(format!($($arg)*))
};
}
/// Creates some [`Rich`] text with the given spans.
///
/// [`Rich`]: text::Rich
///
/// # Example
/// ```no_run
/// # mod iced { pub mod widget { pub use iced_widget::*; } pub use iced_widget::core::*; }
/// # pub type State = ();
/// # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>;
/// use iced::font;
/// use iced::widget::{rich_text, span};
/// use iced::{color, never, Font};
///
/// #[derive(Debug, Clone)]
/// enum Message {
/// // ...
/// }
///
/// fn view(state: &State) -> Element<'_, Message> {
/// rich_text![
/// span("I am red!").color(color!(0xff0000)),
/// span(" "),
/// span("And I am bold!").font(Font { weight: font::Weight::Bold, ..Font::default() }),
/// ]
/// .on_link_click(never)
/// .size(20)
/// .into()
/// }
/// ```
#[macro_export]
macro_rules! rich_text {
() => (
2025-02-04 07:53:56 +01:00
$crate::text::Rich::new()
);
($($x:expr),+ $(,)?) => (
2024-07-20 19:54:25 +02:00
$crate::text::Rich::from_iter([$($crate::text::Span::from($x)),+])
);
}
/// Creates a new [`Container`] with the provided content.
///
/// Containers let you align a widget inside their boundaries.
///
/// # Example
/// ```no_run
/// # mod iced { pub mod widget { pub use iced_widget::*; } }
/// # pub type State = ();
/// # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>;
/// use iced::widget::container;
///
/// enum Message {
/// // ...
/// }
///
/// fn view(state: &State) -> Element<'_, Message> {
/// container("This text is centered inside a rounded box!")
/// .padding(10)
/// .center(800)
/// .style(container::rounded_box)
/// .into()
/// }
/// ```
pub fn container<'a, Message, Theme, Renderer>(
content: impl Into<Element<'a, Message, Theme, Renderer>>,
) -> Container<'a, Message, Theme, Renderer>
where
2024-03-24 05:03:09 +01:00
Theme: container::Catalog + 'a,
Renderer: core::Renderer,
{
Container::new(content)
}
/// Creates a new [`Container`] that fills all the available space
/// and centers its contents inside.
///
/// This is equivalent to:
/// ```rust,no_run
/// # use iced_widget::core::Length::Fill;
/// # use iced_widget::Container;
/// # fn container<A>(x: A) -> Container<'static, ()> { unreachable!() }
/// let center = container("Center!").center(Fill);
/// ```
///
/// [`Container`]: crate::Container
pub fn center<'a, Message, Theme, Renderer>(
content: impl Into<Element<'a, Message, Theme, Renderer>>,
) -> Container<'a, Message, Theme, Renderer>
where
Theme: container::Catalog + 'a,
Renderer: core::Renderer,
{
container(content).center(Length::Fill)
}
/// Creates a new [`Container`] that fills all the available space
/// horizontally and centers its contents inside.
///
/// This is equivalent to:
/// ```rust,no_run
/// # use iced_widget::core::Length::Fill;
/// # use iced_widget::Container;
/// # fn container<A>(x: A) -> Container<'static, ()> { unreachable!() }
/// let center_x = container("Horizontal Center!").center_x(Fill);
/// ```
///
/// [`Container`]: crate::Container
pub fn center_x<'a, Message, Theme, Renderer>(
content: impl Into<Element<'a, Message, Theme, Renderer>>,
) -> Container<'a, Message, Theme, Renderer>
where
Theme: container::Catalog + 'a,
Renderer: core::Renderer,
{
container(content).center_x(Length::Fill)
}
/// Creates a new [`Container`] that fills all the available space
/// vertically and centers its contents inside.
///
/// This is equivalent to:
/// ```rust,no_run
/// # use iced_widget::core::Length::Fill;
/// # use iced_widget::Container;
/// # fn container<A>(x: A) -> Container<'static, ()> { unreachable!() }
/// let center_y = container("Vertical Center!").center_y(Fill);
/// ```
///
/// [`Container`]: crate::Container
pub fn center_y<'a, Message, Theme, Renderer>(
content: impl Into<Element<'a, Message, Theme, Renderer>>,
) -> Container<'a, Message, Theme, Renderer>
where
Theme: container::Catalog + 'a,
Renderer: core::Renderer,
{
container(content).center_y(Length::Fill)
}
/// Creates a new [`Container`] that fills all the available space
/// horizontally and right-aligns its contents inside.
///
/// This is equivalent to:
/// ```rust,no_run
/// # use iced_widget::core::Length::Fill;
/// # use iced_widget::Container;
/// # fn container<A>(x: A) -> Container<'static, ()> { unreachable!() }
/// let right = container("Right!").align_right(Fill);
/// ```
///
/// [`Container`]: crate::Container
pub fn right<'a, Message, Theme, Renderer>(
content: impl Into<Element<'a, Message, Theme, Renderer>>,
) -> Container<'a, Message, Theme, Renderer>
where
Theme: container::Catalog + 'a,
Renderer: core::Renderer,
{
container(content).align_right(Length::Fill)
}
/// Creates a new [`Container`] that fills all the available space
/// and aligns its contents inside to the right center.
///
/// This is equivalent to:
/// ```rust,no_run
/// # use iced_widget::core::Length::Fill;
/// # use iced_widget::Container;
/// # fn container<A>(x: A) -> Container<'static, ()> { unreachable!() }
/// let right_center = container("Bottom Center!").align_right(Fill).center_y(Fill);
/// ```
///
/// [`Container`]: crate::Container
pub fn right_center<'a, Message, Theme, Renderer>(
content: impl Into<Element<'a, Message, Theme, Renderer>>,
) -> Container<'a, Message, Theme, Renderer>
where
Theme: container::Catalog + 'a,
Renderer: core::Renderer,
{
container(content)
.align_right(Length::Fill)
.center_y(Length::Fill)
}
/// Creates a new [`Container`] that fills all the available space
/// vertically and bottom-aligns its contents inside.
///
/// This is equivalent to:
/// ```rust,no_run
/// # use iced_widget::core::Length::Fill;
/// # use iced_widget::Container;
/// # fn container<A>(x: A) -> Container<'static, ()> { unreachable!() }
/// let bottom = container("Bottom!").align_bottom(Fill);
/// ```
///
/// [`Container`]: crate::Container
pub fn bottom<'a, Message, Theme, Renderer>(
content: impl Into<Element<'a, Message, Theme, Renderer>>,
) -> Container<'a, Message, Theme, Renderer>
where
Theme: container::Catalog + 'a,
Renderer: core::Renderer,
{
container(content).align_bottom(Length::Fill)
}
/// Creates a new [`Container`] that fills all the available space
/// and aligns its contents inside to the bottom center.
///
/// This is equivalent to:
/// ```rust,no_run
/// # use iced_widget::core::Length::Fill;
/// # use iced_widget::Container;
/// # fn container<A>(x: A) -> Container<'static, ()> { unreachable!() }
/// let bottom_center = container("Bottom Center!").center_x(Fill).align_bottom(Fill);
/// ```
///
/// [`Container`]: crate::Container
pub fn bottom_center<'a, Message, Theme, Renderer>(
content: impl Into<Element<'a, Message, Theme, Renderer>>,
) -> Container<'a, Message, Theme, Renderer>
where
Theme: container::Catalog + 'a,
Renderer: core::Renderer,
{
container(content)
.center_x(Length::Fill)
.align_bottom(Length::Fill)
}
/// Creates a new [`Container`] that fills all the available space
/// and aligns its contents inside to the bottom right corner.
///
/// This is equivalent to:
/// ```rust,no_run
/// # use iced_widget::core::Length::Fill;
/// # use iced_widget::Container;
/// # fn container<A>(x: A) -> Container<'static, ()> { unreachable!() }
/// let bottom_right = container("Bottom!").align_right(Fill).align_bottom(Fill);
/// ```
///
/// [`Container`]: crate::Container
pub fn bottom_right<'a, Message, Theme, Renderer>(
content: impl Into<Element<'a, Message, Theme, Renderer>>,
) -> Container<'a, Message, Theme, Renderer>
where
Theme: container::Catalog + 'a,
Renderer: core::Renderer,
{
container(content)
.align_right(Length::Fill)
.align_bottom(Length::Fill)
}
2024-11-22 04:06:52 +01:00
/// Creates a new [`Pin`] widget with the given content.
///
/// A [`Pin`] widget positions its contents at some fixed coordinates inside of its boundaries.
///
/// # Example
/// ```no_run
/// # mod iced { pub mod widget { pub use iced_widget::*; } pub use iced_widget::core::Length::Fill; }
/// # pub type State = ();
/// # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>;
/// use iced::widget::pin;
/// use iced::Fill;
///
/// enum Message {
/// // ...
/// }
///
/// fn view(state: &State) -> Element<'_, Message> {
/// pin("This text is displayed at coordinates (50, 50)!")
/// .x(50)
/// .y(50)
/// .into()
/// }
/// ```
pub fn pin<'a, Message, Theme, Renderer>(
content: impl Into<Element<'a, Message, Theme, Renderer>>,
) -> Pin<'a, Message, Theme, Renderer>
where
Renderer: core::Renderer,
{
Pin::new(content)
}
/// Creates a new [`Column`] with the given children.
///
/// Columns distribute their children vertically.
///
/// # Example
/// ```no_run
/// # mod iced { pub mod widget { pub use iced_widget::*; } }
/// # pub type State = ();
/// # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>;
/// use iced::widget::{column, text};
///
/// enum Message {
/// // ...
/// }
///
/// fn view(state: &State) -> Element<'_, Message> {
/// column((0..5).map(|i| text!("Item {i}").into())).into()
/// }
/// ```
pub fn column<'a, Message, Theme, Renderer>(
children: impl IntoIterator<Item = Element<'a, Message, Theme, Renderer>>,
) -> Column<'a, Message, Theme, Renderer>
where
Renderer: core::Renderer,
{
Column::with_children(children)
}
/// Creates a new [`keyed::Column`] from an iterator of elements.
///
/// Keyed columns distribute content vertically while keeping continuity.
///
/// # Example
/// ```no_run
/// # mod iced { pub mod widget { pub use iced_widget::*; } }
/// # pub type State = ();
/// # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>;
/// use iced::widget::{keyed_column, text};
///
/// enum Message {
/// // ...
/// }
///
/// fn view(state: &State) -> Element<'_, Message> {
/// keyed_column((0..=100).map(|i| {
/// (i, text!("Item {i}").into())
/// })).into()
/// }
/// ```
pub fn keyed_column<'a, Key, Message, Theme, Renderer>(
children: impl IntoIterator<Item = (Key, Element<'a, Message, Theme, Renderer>)>,
) -> keyed::Column<'a, Key, Message, Theme, Renderer>
2023-09-04 02:55:09 +02:00
where
Key: Copy + PartialEq,
2024-01-09 06:44:15 +01:00
Renderer: core::Renderer,
2023-09-04 02:55:09 +02:00
{
keyed::Column::with_children(children)
}
/// Creates a new [`Row`] from an iterator.
///
/// Rows distribute their children horizontally.
///
/// # Example
/// ```no_run
/// # mod iced { pub mod widget { pub use iced_widget::*; } }
/// # pub type State = ();
/// # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>;
/// use iced::widget::{row, text};
///
/// enum Message {
/// // ...
/// }
///
/// fn view(state: &State) -> Element<'_, Message> {
/// row((0..5).map(|i| text!("Item {i}").into())).into()
/// }
/// ```
pub fn row<'a, Message, Theme, Renderer>(
children: impl IntoIterator<Item = Element<'a, Message, Theme, Renderer>>,
) -> Row<'a, Message, Theme, Renderer>
where
Renderer: core::Renderer,
{
Row::with_children(children)
}
2025-04-10 02:49:32 +02:00
/// Creates a new [`Grid`] from an iterator.
pub fn grid<'a, Message, Theme, Renderer>(
children: impl IntoIterator<Item = Element<'a, Message, Theme, Renderer>>,
) -> Grid<'a, Message, Theme, Renderer>
where
Renderer: core::Renderer,
{
Grid::with_children(children)
}
/// Creates a new [`Stack`] with the given children.
///
/// [`Stack`]: crate::Stack
pub fn stack<'a, Message, Theme, Renderer>(
children: impl IntoIterator<Item = Element<'a, Message, Theme, Renderer>>,
) -> Stack<'a, Message, Theme, Renderer>
where
Renderer: core::Renderer,
{
Stack::with_children(children)
}
2024-04-25 06:05:00 +02:00
/// Wraps the given widget and captures any mouse button presses inside the bounds of
2024-04-27 06:06:13 +02:00
/// the widget—effectively making it _opaque_.
2024-04-25 06:05:00 +02:00
///
/// This helper is meant to be used to mark elements in a [`Stack`] to avoid mouse
/// events from passing through layers.
///
/// [`Stack`]: crate::Stack
pub fn opaque<'a, Message, Theme, Renderer>(
content: impl Into<Element<'a, Message, Theme, Renderer>>,
) -> Element<'a, Message, Theme, Renderer>
where
Message: 'a,
Theme: 'a,
Renderer: core::Renderer + 'a,
{
use crate::core::layout::{self, Layout};
use crate::core::mouse;
use crate::core::renderer;
use crate::core::widget::tree::{self, Tree};
use crate::core::{Event, Rectangle, Shell, Size};
2024-04-25 06:05:00 +02:00
struct Opaque<'a, Message, Theme, Renderer> {
content: Element<'a, Message, Theme, Renderer>,
}
2024-12-02 19:53:16 +01:00
impl<Message, Theme, Renderer> Widget<Message, Theme, Renderer>
for Opaque<'_, Message, Theme, Renderer>
2024-04-25 06:05:00 +02:00
where
Renderer: core::Renderer,
{
fn tag(&self) -> tree::Tag {
self.content.as_widget().tag()
}
fn state(&self) -> tree::State {
self.content.as_widget().state()
}
fn children(&self) -> Vec<Tree> {
self.content.as_widget().children()
}
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 f39a5fd8953494fd8e41c05bc053519740d09612) 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.
2023-05-02 15:48:20 -07:00
fn diff(&mut self, tree: &mut Tree) {
self.content.as_widget_mut().diff(tree);
2024-04-25 06:05:00 +02:00
}
fn size(&self) -> Size<Length> {
self.content.as_widget().size()
}
fn size_hint(&self) -> Size<Length> {
self.content.as_widget().size_hint()
}
fn layout(
&mut self,
2024-04-25 06:05:00 +02:00
tree: &mut Tree,
renderer: &Renderer,
limits: &layout::Limits,
) -> layout::Node {
self.content.as_widget_mut().layout(tree, renderer, limits)
2024-04-25 06:05:00 +02:00
}
fn draw(
&self,
tree: &Tree,
renderer: &mut Renderer,
theme: &Theme,
style: &renderer::Style,
layout: Layout<'_>,
cursor: mouse::Cursor,
viewport: &Rectangle,
) {
self.content
.as_widget()
.draw(tree, renderer, theme, style, layout, cursor, viewport);
}
fn operate(
&mut self,
tree: &mut Tree,
2024-04-25 06:05:00 +02:00
layout: Layout<'_>,
renderer: &Renderer,
operation: &mut dyn operation::Operation,
2024-04-25 06:05:00 +02:00
) {
self.content
.as_widget_mut()
.operate(tree, layout, renderer, operation);
2024-04-25 06:05:00 +02:00
}
2024-10-25 22:06:06 +02:00
fn update(
2024-04-25 06:05:00 +02:00
&mut self,
tree: &mut Tree,
event: &Event,
2024-04-25 06:05:00 +02:00
layout: Layout<'_>,
cursor: mouse::Cursor,
renderer: &Renderer,
clipboard: &mut dyn core::Clipboard,
shell: &mut Shell<'_, Message>,
viewport: &Rectangle,
) {
2024-04-25 06:05:00 +02:00
let is_mouse_press = matches!(
event,
core::Event::Mouse(mouse::Event::ButtonPressed(_))
);
2024-10-25 22:06:06 +02:00
self.content.as_widget_mut().update(
tree, event, layout, cursor, renderer, clipboard, shell,
viewport,
);
2024-04-25 06:05:00 +02:00
if is_mouse_press && cursor.is_over(layout.bounds()) {
shell.capture_event();
2024-04-25 06:05:00 +02:00
}
}
fn mouse_interaction(
&self,
state: &core::widget::Tree,
layout: core::Layout<'_>,
cursor: core::mouse::Cursor,
viewport: &core::Rectangle,
renderer: &Renderer,
) -> core::mouse::Interaction {
let interaction = self
.content
.as_widget()
.mouse_interaction(state, layout, cursor, viewport, renderer);
if interaction == mouse::Interaction::None
&& cursor.is_over(layout.bounds())
{
mouse::Interaction::Idle
} else {
interaction
}
}
fn overlay<'b>(
&'b mut self,
state: &'b mut core::widget::Tree,
layout: core::Layout<'b>,
2024-04-25 06:05:00 +02:00
renderer: &Renderer,
viewport: &Rectangle,
2024-04-25 06:05:00 +02:00
translation: core::Vector,
) -> Option<core::overlay::Element<'b, Message, Theme, Renderer>>
{
self.content.as_widget_mut().overlay(
state,
layout,
renderer,
viewport,
2024-04-25 06:05:00 +02:00
translation,
)
}
}
Element::new(Opaque {
content: content.into(),
})
}
2024-04-27 06:06:13 +02:00
/// Displays a widget on top of another one, only when the base widget is hovered.
///
/// This works analogously to a [`stack`], but it will only display the layer on top
/// when the cursor is over the base. It can be useful for removing visual clutter.
///
/// [`stack`]: stack()
2024-04-27 06:06:13 +02:00
pub fn hover<'a, Message, Theme, Renderer>(
base: impl Into<Element<'a, Message, Theme, Renderer>>,
top: impl Into<Element<'a, Message, Theme, Renderer>>,
) -> Element<'a, Message, Theme, Renderer>
where
Message: 'a,
Theme: 'a,
Renderer: core::Renderer + 'a,
{
use crate::core::layout::{self, Layout};
use crate::core::mouse;
use crate::core::renderer;
use crate::core::widget::tree::{self, Tree};
use crate::core::{Event, Rectangle, Shell, Size};
2024-04-27 06:06:13 +02:00
struct Hover<'a, Message, Theme, Renderer> {
base: Element<'a, Message, Theme, Renderer>,
top: Element<'a, Message, Theme, Renderer>,
is_top_focused: bool,
is_top_overlay_active: bool,
is_hovered: bool,
2024-04-27 06:06:13 +02:00
}
2024-12-02 19:53:16 +01:00
impl<Message, Theme, Renderer> Widget<Message, Theme, Renderer>
for Hover<'_, Message, Theme, Renderer>
2024-04-27 06:06:13 +02:00
where
Renderer: core::Renderer,
{
fn tag(&self) -> tree::Tag {
struct Tag;
tree::Tag::of::<Tag>()
}
fn children(&self) -> Vec<Tree> {
vec![Tree::new(&self.base), Tree::new(&self.top)]
}
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 f39a5fd8953494fd8e41c05bc053519740d09612) 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.
2023-05-02 15:48:20 -07:00
fn diff(&mut self, tree: &mut Tree) {
tree.diff_children(&mut [&mut self.base, &mut self.top]);
2024-04-27 06:06:13 +02:00
}
fn size(&self) -> Size<Length> {
self.base.as_widget().size()
}
fn size_hint(&self) -> Size<Length> {
self.base.as_widget().size_hint()
}
fn layout(
&mut self,
2024-04-27 06:06:13 +02:00
tree: &mut Tree,
renderer: &Renderer,
limits: &layout::Limits,
) -> layout::Node {
let base = self.base.as_widget_mut().layout(
2024-04-27 06:06:13 +02:00
&mut tree.children[0],
renderer,
limits,
);
let top = self.top.as_widget_mut().layout(
2024-04-27 06:06:13 +02:00
&mut tree.children[1],
renderer,
&layout::Limits::new(Size::ZERO, base.size()),
);
layout::Node::with_children(base.size(), vec![base, top])
}
fn draw(
&self,
tree: &Tree,
renderer: &mut Renderer,
theme: &Theme,
style: &renderer::Style,
layout: Layout<'_>,
cursor: mouse::Cursor,
viewport: &Rectangle,
) {
if let Some(bounds) = layout.bounds().intersection(viewport) {
let mut children = layout.children().zip(&tree.children);
let (base_layout, base_tree) = children.next().unwrap();
self.base.as_widget().draw(
base_tree,
renderer,
theme,
style,
base_layout,
cursor,
viewport,
);
if cursor.is_over(layout.bounds())
|| self.is_top_focused
|| self.is_top_overlay_active
{
let (top_layout, top_tree) = children.next().unwrap();
renderer.with_layer(bounds, |renderer| {
self.top.as_widget().draw(
top_tree, renderer, theme, style, top_layout,
cursor, viewport,
);
});
}
2024-04-27 06:06:13 +02:00
}
}
fn operate(
&mut self,
2024-04-27 06:06:13 +02:00
tree: &mut Tree,
layout: Layout<'_>,
renderer: &Renderer,
operation: &mut dyn operation::Operation,
2024-04-27 06:06:13 +02:00
) {
let children = [&mut self.base, &mut self.top]
2024-04-27 06:06:13 +02:00
.into_iter()
.zip(layout.children().zip(&mut tree.children));
for (child, (layout, tree)) in children {
child
.as_widget_mut()
.operate(tree, layout, renderer, operation);
2024-04-27 06:06:13 +02:00
}
}
2024-10-25 22:06:06 +02:00
fn update(
2024-04-27 06:06:13 +02:00
&mut self,
tree: &mut Tree,
event: &Event,
2024-04-27 06:06:13 +02:00
layout: Layout<'_>,
cursor: mouse::Cursor,
renderer: &Renderer,
clipboard: &mut dyn core::Clipboard,
shell: &mut Shell<'_, Message>,
viewport: &Rectangle,
) {
2024-04-27 06:06:13 +02:00
let mut children = layout.children().zip(&mut tree.children);
let (base_layout, base_tree) = children.next().unwrap();
let (top_layout, top_tree) = children.next().unwrap();
let is_hovered = cursor.is_over(layout.bounds());
if matches!(event, Event::Window(window::Event::RedrawRequested(_)))
{
let mut count_focused = operation::focusable::count();
self.top.as_widget_mut().operate(
top_tree,
top_layout,
renderer,
&mut operation::black_box(&mut count_focused),
);
self.is_top_focused = match count_focused.finish() {
operation::Outcome::Some(count) => count.focused.is_some(),
_ => false,
};
self.is_hovered = is_hovered;
} else if is_hovered != self.is_hovered {
shell.request_redraw();
}
2024-04-27 06:06:13 +02:00
let is_visible =
is_hovered || self.is_top_focused || self.is_top_overlay_active;
if matches!(
event,
Event::Mouse(
mouse::Event::CursorMoved { .. }
| mouse::Event::ButtonReleased(_)
)
) || is_visible
{
let redraw_request = shell.redraw_request();
2024-04-27 06:06:13 +02:00
2024-10-25 22:06:06 +02:00
self.top.as_widget_mut().update(
top_tree, event, top_layout, cursor, renderer, clipboard,
shell, viewport,
);
// Ignore redraw requests of invisible content
if !is_visible {
Shell::replace_redraw_request(shell, redraw_request);
}
2024-04-27 06:06:13 +02:00
if shell.is_event_captured() {
return;
}
};
2024-04-27 06:06:13 +02:00
2024-10-25 22:06:06 +02:00
self.base.as_widget_mut().update(
2024-04-27 06:06:13 +02:00
base_tree,
event,
2024-04-27 06:06:13 +02:00
base_layout,
cursor,
renderer,
clipboard,
shell,
viewport,
);
2024-04-27 06:06:13 +02:00
}
fn mouse_interaction(
&self,
tree: &Tree,
layout: Layout<'_>,
cursor: mouse::Cursor,
viewport: &Rectangle,
renderer: &Renderer,
) -> mouse::Interaction {
[&self.base, &self.top]
.into_iter()
.rev()
.zip(layout.children().rev().zip(tree.children.iter().rev()))
.map(|(child, (layout, tree))| {
child.as_widget().mouse_interaction(
tree, layout, cursor, viewport, renderer,
)
})
.find(|&interaction| interaction != mouse::Interaction::None)
.unwrap_or_default()
}
fn overlay<'b>(
&'b mut self,
tree: &'b mut core::widget::Tree,
layout: core::Layout<'b>,
2024-04-27 06:06:13 +02:00
renderer: &Renderer,
viewport: &Rectangle,
2024-04-27 06:06:13 +02:00
translation: core::Vector,
) -> Option<core::overlay::Element<'b, Message, Theme, Renderer>>
{
let mut overlays = [&mut self.base, &mut self.top]
2024-04-27 06:06:13 +02:00
.into_iter()
.zip(layout.children().zip(tree.children.iter_mut()))
.map(|(child, (layout, tree))| {
2024-04-27 06:06:13 +02:00
child.as_widget_mut().overlay(
tree,
layout,
renderer,
viewport,
2024-04-27 06:06:13 +02:00
translation,
)
});
if let Some(base_overlay) = overlays.next()? {
return Some(base_overlay);
}
let top_overlay = overlays.next()?;
self.is_top_overlay_active = top_overlay.is_some();
top_overlay
2024-04-27 06:06:13 +02:00
}
}
Element::new(Hover {
base: base.into(),
top: top.into(),
is_top_focused: false,
is_top_overlay_active: false,
is_hovered: false,
2024-04-27 06:06:13 +02:00
})
}
/// Creates a new [`Sensor`] widget.
///
/// A [`Sensor`] widget can generate messages when its contents are shown,
/// hidden, or resized.
2025-01-26 04:21:44 +01:00
///
/// It can even notify you with anticipation at a given distance!
pub fn sensor<'a, Message, Theme, Renderer>(
2025-01-26 04:21:44 +01:00
content: impl Into<Element<'a, Message, Theme, Renderer>>,
) -> Sensor<'a, (), Message, Theme, Renderer>
2025-01-26 04:21:44 +01:00
where
Renderer: core::Renderer,
{
Sensor::new(content)
2025-01-26 04:21:44 +01:00
}
/// Creates a new [`Scrollable`] with the provided content.
///
/// Scrollables let users navigate an endless amount of content with a scrollbar.
///
/// # Example
/// ```no_run
/// # mod iced { pub mod widget { pub use iced_widget::*; } }
/// # pub type State = ();
/// # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>;
/// use iced::widget::{column, scrollable, space};
///
/// enum Message {
/// // ...
/// }
///
/// fn view(state: &State) -> Element<'_, Message> {
/// scrollable(column![
/// "Scroll me!",
/// space().height(3000),
/// "You did it!",
/// ]).into()
/// }
/// ```
pub fn scrollable<'a, Message, Theme, Renderer>(
content: impl Into<Element<'a, Message, Theme, Renderer>>,
) -> Scrollable<'a, Message, Theme, Renderer>
where
2024-03-24 05:03:09 +01:00
Theme: scrollable::Catalog + 'a,
Renderer: core::text::Renderer,
{
Scrollable::new(content)
}
/// Creates a new [`List`] with the provided [`Content`] and
/// closure to view an item of the [`List`].
///
/// [`List`]: crate::List
/// [`Content`]: crate::list::Content
pub fn list<'a, T, Message, Theme, Renderer>(
content: &'a list::Content<T>,
view_item: impl Fn(usize, &'a T) -> Element<'a, Message, Theme, Renderer> + 'a,
) -> List<'a, T, Message, Theme, Renderer> {
List::new(content, view_item)
}
/// Creates a new [`Button`] with the provided content.
///
/// # Example
/// ```no_run
/// # mod iced { pub mod widget { pub use iced_widget::*; } }
/// # pub type State = ();
/// # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>;
/// use iced::widget::button;
///
/// #[derive(Clone)]
/// enum Message {
/// ButtonPressed,
/// }
///
/// fn view(state: &State) -> Element<'_, Message> {
/// button("Press me!").on_press(Message::ButtonPressed).into()
/// }
/// ```
pub fn button<'a, Message, Theme, Renderer>(
content: impl Into<Element<'a, Message, Theme, Renderer>>,
) -> Button<'a, Message, Theme, Renderer>
where
Theme: button::Catalog + 'a,
Renderer: core::Renderer,
{
Button::new(content)
}
2024-02-09 02:12:22 +01:00
/// Creates a new [`Tooltip`] for the provided content with the given
/// [`Element`] and [`tooltip::Position`].
///
/// Tooltips display a hint of information over some element when hovered.
///
/// # Example
/// ```no_run
/// # mod iced { pub mod widget { pub use iced_widget::*; } }
/// # pub type State = ();
/// # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>;
/// use iced::widget::{container, tooltip};
///
/// enum Message {
/// // ...
/// }
///
/// fn view(_state: &State) -> Element<'_, Message> {
/// tooltip(
/// "Hover me to display the tooltip!",
/// container("This is the tooltip contents!")
/// .padding(10)
/// .style(container::rounded_box),
/// tooltip::Position::Bottom,
/// ).into()
/// }
/// ```
pub fn tooltip<'a, Message, Theme, Renderer>(
content: impl Into<Element<'a, Message, Theme, Renderer>>,
tooltip: impl Into<Element<'a, Message, Theme, Renderer>>,
position: tooltip::Position,
) -> crate::Tooltip<'a, Message, Theme, Renderer>
where
2024-03-24 05:03:09 +01:00
Theme: container::Catalog + 'a,
Renderer: core::text::Renderer,
{
Tooltip::new(content, tooltip, position)
}
/// Creates a new [`Text`] widget with the provided content.
///
/// # Example
/// ```no_run
/// # mod iced { pub mod widget { pub use iced_widget::*; } pub use iced_widget::Renderer; pub use iced_widget::core::*; }
/// # pub type State = ();
/// # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::core::Theme, ()>;
/// use iced::widget::text;
/// use iced::color;
///
/// enum Message {
/// // ...
/// }
///
/// fn view(state: &State) -> Element<'_, Message> {
/// text("Hello, this is iced!")
/// .size(20)
/// .color(color!(0x0000ff))
/// .into()
/// }
/// ```
pub fn text<'a, Theme, Renderer>(
text: impl text::IntoFragment<'a>,
) -> Text<'a, Theme, Renderer>
where
2024-03-24 05:03:09 +01:00
Theme: text::Catalog + 'a,
Renderer: core::text::Renderer,
{
Text::new(text)
}
/// Creates a new [`Text`] widget that displays the provided value.
pub fn value<'a, Theme, Renderer>(
value: impl ToString,
) -> Text<'a, Theme, Renderer>
where
Theme: text::Catalog + 'a,
Renderer: core::text::Renderer,
{
Text::new(value.to_string())
}
/// Creates a new [`Rich`] text widget with the provided spans.
///
/// [`Rich`]: text::Rich
///
/// # Example
/// ```no_run
/// # mod iced { pub mod widget { pub use iced_widget::*; } pub use iced_widget::core::*; }
/// # pub type State = ();
/// # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>;
/// use iced::font;
/// use iced::widget::{rich_text, span};
/// use iced::{color, never, Font};
///
/// #[derive(Debug, Clone)]
/// enum Message {
/// LinkClicked(&'static str),
/// // ...
/// }
///
/// fn view(state: &State) -> Element<'_, Message> {
/// rich_text([
/// span("I am red!").color(color!(0xff0000)),
/// span(" "),
/// span("And I am bold!").font(Font { weight: font::Weight::Bold, ..Font::default() }),
/// ])
/// .on_link_click(never)
/// .size(20)
/// .into()
/// }
/// ```
2025-02-04 07:53:56 +01:00
pub fn rich_text<'a, Link, Message, Theme, Renderer>(
spans: impl AsRef<[text::Span<'a, Link, Renderer::Font>]> + 'a,
2025-02-04 07:53:56 +01:00
) -> text::Rich<'a, Link, Message, Theme, Renderer>
where
Link: Clone + 'static,
Theme: text::Catalog + 'a,
Renderer: core::text::Renderer,
Renderer::Font: 'a,
{
text::Rich::with_spans(spans)
}
/// Creates a new [`Span`] of text with the provided content.
///
/// A [`Span`] is a fragment of some [`Rich`] text.
///
/// [`Span`]: text::Span
/// [`Rich`]: text::Rich
///
/// # Example
/// ```no_run
/// # mod iced { pub mod widget { pub use iced_widget::*; } pub use iced_widget::core::*; }
/// # pub type State = ();
/// # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>;
/// use iced::font;
/// use iced::widget::{rich_text, span};
/// use iced::{color, never, Font};
///
/// #[derive(Debug, Clone)]
/// enum Message {
/// // ...
/// }
///
/// fn view(state: &State) -> Element<'_, Message> {
/// rich_text![
/// span("I am red!").color(color!(0xff0000)),
/// " ",
/// span("And I am bold!").font(Font { weight: font::Weight::Bold, ..Font::default() }),
/// ]
/// .on_link_click(never)
/// .size(20)
/// .into()
/// }
/// ```
pub fn span<'a, Link, Font>(
text: impl text::IntoFragment<'a>,
) -> text::Span<'a, Link, Font> {
text::Span::new(text)
}
#[cfg(feature = "markdown")]
#[doc(inline)]
2024-07-18 14:54:26 +02:00
pub use crate::markdown::view as markdown;
/// Creates a new [`Checkbox`].
///
/// # Example
/// ```no_run
/// # mod iced { pub mod widget { pub use iced_widget::*; } pub use iced_widget::Renderer; pub use iced_widget::core::*; }
/// # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>;
/// #
/// use iced::widget::checkbox;
///
/// struct State {
/// is_checked: bool,
/// }
///
/// enum Message {
/// CheckboxToggled(bool),
/// }
///
/// fn view(state: &State) -> Element<'_, Message> {
/// checkbox(state.is_checked)
/// .label("Toggle me!")
/// .on_toggle(Message::CheckboxToggled)
/// .into()
/// }
///
/// fn update(state: &mut State, message: Message) {
/// match message {
/// Message::CheckboxToggled(is_checked) => {
/// state.is_checked = is_checked;
/// }
/// }
/// }
/// ```
/// ![Checkbox drawn by `iced_wgpu`](https://github.com/iced-rs/iced/blob/7760618fb112074bc40b148944521f312152012a/docs/images/checkbox.png?raw=true)
pub fn checkbox<'a, Message, Theme, Renderer>(
is_checked: bool,
) -> Checkbox<'a, Message, Theme, Renderer>
where
Theme: checkbox::Catalog + 'a,
Renderer: core::text::Renderer,
{
Checkbox::new(is_checked)
}
/// Creates a new [`Radio`].
///
/// Radio buttons let users choose a single option from a bunch of options.
///
/// # Example
/// ```no_run
/// # mod iced { pub mod widget { pub use iced_widget::*; } pub use iced_widget::Renderer; pub use iced_widget::core::*; }
/// # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>;
/// #
/// use iced::widget::{column, radio};
///
/// struct State {
/// selection: Option<Choice>,
/// }
///
/// #[derive(Debug, Clone, Copy)]
/// enum Message {
/// RadioSelected(Choice),
/// }
///
/// #[derive(Debug, Clone, Copy, PartialEq, Eq)]
/// enum Choice {
/// A,
/// B,
/// C,
/// All,
/// }
///
/// fn view(state: &State) -> Element<'_, Message> {
/// let a = radio(
/// "A",
/// Choice::A,
/// state.selection,
/// Message::RadioSelected,
/// );
///
/// let b = radio(
/// "B",
/// Choice::B,
/// state.selection,
/// Message::RadioSelected,
/// );
///
/// let c = radio(
/// "C",
/// Choice::C,
/// state.selection,
/// Message::RadioSelected,
/// );
///
/// let all = radio(
/// "All of the above",
/// Choice::All,
/// state.selection,
/// Message::RadioSelected
/// );
///
/// column![a, b, c, all].into()
/// }
/// ```
2024-03-12 14:45:28 +01:00
pub fn radio<'a, Message, Theme, Renderer, V>(
label: impl Into<String>,
value: V,
selected: Option<V>,
on_click: impl FnOnce(V) -> Message,
2024-03-12 14:45:28 +01:00
) -> Radio<'a, Message, Theme, Renderer>
where
Message: Clone,
2024-03-24 05:03:09 +01:00
Theme: radio::Catalog + 'a,
Renderer: core::text::Renderer,
V: Copy + Eq,
{
Radio::new(label, value, selected, on_click)
}
/// Creates a new [`Toggler`].
///
/// Togglers let users make binary choices by toggling a switch.
///
/// # Example
/// ```no_run
/// # mod iced { pub mod widget { pub use iced_widget::*; } pub use iced_widget::Renderer; pub use iced_widget::core::*; }
/// # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>;
/// #
/// use iced::widget::toggler;
///
/// struct State {
/// is_checked: bool,
/// }
///
/// enum Message {
/// TogglerToggled(bool),
/// }
///
/// fn view(state: &State) -> Element<'_, Message> {
/// toggler(state.is_checked)
/// .label("Toggle me!")
/// .on_toggle(Message::TogglerToggled)
/// .into()
/// }
///
/// fn update(state: &mut State, message: Message) {
/// match message {
/// Message::TogglerToggled(is_checked) => {
/// state.is_checked = is_checked;
/// }
/// }
/// }
/// ```
pub fn toggler<'a, Message, Theme, Renderer>(
is_checked: bool,
) -> Toggler<'a, Message, Theme, Renderer>
where
2024-03-24 05:03:09 +01:00
Theme: toggler::Catalog + 'a,
Renderer: core::text::Renderer,
{
2024-09-11 00:20:23 +02:00
Toggler::new(is_checked)
}
/// Creates a new [`TextInput`].
///
/// Text inputs display fields that can be filled with text.
///
/// # Example
/// ```no_run
/// # mod iced { pub mod widget { pub use iced_widget::*; } pub use iced_widget::Renderer; pub use iced_widget::core::*; }
/// # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>;
/// #
/// use iced::widget::text_input;
///
/// struct State {
/// content: String,
/// }
///
/// #[derive(Debug, Clone)]
/// enum Message {
/// ContentChanged(String)
/// }
///
/// fn view(state: &State) -> Element<'_, Message> {
/// text_input("Type something here...", &state.content)
/// .on_input(Message::ContentChanged)
/// .into()
/// }
///
/// fn update(state: &mut State, message: Message) {
/// match message {
/// Message::ContentChanged(content) => {
/// state.content = content;
/// }
/// }
/// }
/// ```
pub fn text_input<'a, Message, Theme, Renderer>(
placeholder: &str,
value: &str,
) -> TextInput<'a, Message, Theme, Renderer>
where
Message: Clone,
2024-03-24 05:03:09 +01:00
Theme: text_input::Catalog + 'a,
Renderer: core::text::Renderer,
{
TextInput::new(placeholder, value)
}
/// Creates a new [`TextEditor`].
///
/// Text editors display a multi-line text input for text editing.
///
/// # Example
/// ```no_run
/// # mod iced { pub mod widget { pub use iced_widget::*; } pub use iced_widget::Renderer; pub use iced_widget::core::*; }
/// # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>;
/// #
/// use iced::widget::text_editor;
///
/// struct State {
/// content: text_editor::Content,
/// }
///
/// #[derive(Debug, Clone)]
/// enum Message {
/// Edit(text_editor::Action)
/// }
///
/// fn view(state: &State) -> Element<'_, Message> {
/// text_editor(&state.content)
/// .placeholder("Type something here...")
/// .on_action(Message::Edit)
/// .into()
/// }
///
/// fn update(state: &mut State, message: Message) {
/// match message {
/// Message::Edit(action) => {
/// state.content.perform(action);
/// }
/// }
/// }
/// ```
2024-03-12 15:47:37 +01:00
pub fn text_editor<'a, Message, Theme, Renderer>(
content: &'a text_editor::Content<Renderer>,
) -> TextEditor<'a, core::text::highlighter::PlainText, Message, Theme, Renderer>
where
Message: Clone,
2024-03-24 05:03:09 +01:00
Theme: text_editor::Catalog + 'a,
Renderer: core::text::Renderer,
{
TextEditor::new(content)
}
/// Creates a new [`Slider`].
///
/// Sliders let users set a value by moving an indicator.
///
/// # Example
/// ```no_run
/// # mod iced { pub mod widget { pub use iced_widget::*; } pub use iced_widget::Renderer; pub use iced_widget::core::*; }
/// # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>;
/// #
/// use iced::widget::slider;
///
/// struct State {
/// value: f32,
/// }
///
/// #[derive(Debug, Clone)]
/// enum Message {
/// ValueChanged(f32),
/// }
///
/// fn view(state: &State) -> Element<'_, Message> {
/// slider(0.0..=100.0, state.value, Message::ValueChanged).into()
/// }
///
/// fn update(state: &mut State, message: Message) {
/// match message {
/// Message::ValueChanged(value) => {
/// state.value = value;
/// }
/// }
/// }
/// ```
pub fn slider<'a, T, Message, Theme>(
range: std::ops::RangeInclusive<T>,
value: T,
on_change: impl Fn(T) -> Message + 'a,
) -> Slider<'a, T, Message, Theme>
where
T: Copy + From<u8> + std::cmp::PartialOrd,
Message: Clone,
2024-03-24 05:03:09 +01:00
Theme: slider::Catalog + 'a,
{
Slider::new(range, value, on_change)
}
/// Creates a new [`VerticalSlider`].
///
/// Sliders let users set a value by moving an indicator.
///
/// # Example
/// ```no_run
/// # mod iced { pub mod widget { pub use iced_widget::*; } pub use iced_widget::Renderer; pub use iced_widget::core::*; }
/// # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>;
/// #
/// use iced::widget::vertical_slider;
///
/// struct State {
/// value: f32,
/// }
///
/// #[derive(Debug, Clone)]
/// enum Message {
/// ValueChanged(f32),
/// }
///
/// fn view(state: &State) -> Element<'_, Message> {
/// vertical_slider(0.0..=100.0, state.value, Message::ValueChanged).into()
/// }
///
/// fn update(state: &mut State, message: Message) {
/// match message {
/// Message::ValueChanged(value) => {
/// state.value = value;
/// }
/// }
/// }
/// ```
pub fn vertical_slider<'a, T, Message, Theme>(
range: std::ops::RangeInclusive<T>,
value: T,
on_change: impl Fn(T) -> Message + 'a,
) -> VerticalSlider<'a, T, Message, Theme>
where
T: Copy + From<u8> + std::cmp::PartialOrd,
Message: Clone,
2024-03-24 05:03:09 +01:00
Theme: vertical_slider::Catalog + 'a,
{
VerticalSlider::new(range, value, on_change)
}
/// Creates a new [`PickList`].
///
/// Pick lists display a dropdown list of selectable options.
///
/// # Example
/// ```no_run
/// # mod iced { pub mod widget { pub use iced_widget::*; } pub use iced_widget::Renderer; pub use iced_widget::core::*; }
/// # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>;
/// #
/// use iced::widget::pick_list;
///
/// struct State {
/// favorite: Option<Fruit>,
/// }
///
/// #[derive(Debug, Clone, Copy, PartialEq, Eq)]
/// enum Fruit {
/// Apple,
/// Orange,
/// Strawberry,
/// Tomato,
/// }
///
/// #[derive(Debug, Clone)]
/// enum Message {
/// FruitSelected(Fruit),
/// }
///
/// fn view(state: &State) -> Element<'_, Message> {
/// let fruits = [
/// Fruit::Apple,
/// Fruit::Orange,
/// Fruit::Strawberry,
/// Fruit::Tomato,
/// ];
///
/// pick_list(
/// fruits,
/// state.favorite,
/// Message::FruitSelected,
/// )
/// .placeholder("Select your favorite fruit...")
/// .into()
/// }
///
/// fn update(state: &mut State, message: Message) {
/// match message {
/// Message::FruitSelected(fruit) => {
/// state.favorite = Some(fruit);
/// }
/// }
/// }
///
/// impl std::fmt::Display for Fruit {
/// fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
/// f.write_str(match self {
/// Self::Apple => "Apple",
/// Self::Orange => "Orange",
/// Self::Strawberry => "Strawberry",
/// Self::Tomato => "Tomato",
/// })
/// }
/// }
/// ```
pub fn pick_list<'a, T, L, V, Message, Theme, Renderer>(
options: L,
selected: Option<V>,
on_selected: impl Fn(T) -> Message + 'a,
) -> PickList<'a, T, L, V, Message, Theme, Renderer>
where
T: ToString + PartialEq + Clone + 'a,
L: Borrow<[T]> + 'a,
V: Borrow<T> + 'a,
Message: Clone,
2024-03-24 05:03:09 +01:00
Theme: pick_list::Catalog + overlay::menu::Catalog,
Renderer: core::text::Renderer,
{
PickList::new(options, selected, on_selected)
}
/// Creates a new [`ComboBox`].
///
/// Combo boxes display a dropdown list of searchable and selectable options.
///
/// # Example
/// ```no_run
/// # mod iced { pub mod widget { pub use iced_widget::*; } pub use iced_widget::Renderer; pub use iced_widget::core::*; }
/// # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>;
/// #
/// use iced::widget::combo_box;
///
/// struct State {
/// fruits: combo_box::State<Fruit>,
/// favorite: Option<Fruit>,
/// }
///
/// #[derive(Debug, Clone)]
/// enum Fruit {
/// Apple,
/// Orange,
/// Strawberry,
/// Tomato,
/// }
///
/// #[derive(Debug, Clone)]
/// enum Message {
/// FruitSelected(Fruit),
/// }
///
/// fn view(state: &State) -> Element<'_, Message> {
/// combo_box(
/// &state.fruits,
/// "Select your favorite fruit...",
/// state.favorite.as_ref(),
/// Message::FruitSelected
/// )
/// .into()
/// }
///
/// fn update(state: &mut State, message: Message) {
/// match message {
/// Message::FruitSelected(fruit) => {
/// state.favorite = Some(fruit);
/// }
/// }
/// }
///
/// impl std::fmt::Display for Fruit {
/// fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
/// f.write_str(match self {
/// Self::Apple => "Apple",
/// Self::Orange => "Orange",
/// Self::Strawberry => "Strawberry",
/// Self::Tomato => "Tomato",
/// })
/// }
/// }
/// ```
pub fn combo_box<'a, T, Message, Theme, Renderer>(
state: &'a combo_box::State<T>,
placeholder: &str,
selection: Option<&T>,
on_selected: impl Fn(T) -> Message + 'static,
) -> ComboBox<'a, T, Message, Theme, Renderer>
where
T: std::fmt::Display + Clone,
2024-03-24 05:03:09 +01:00
Theme: combo_box::Catalog + 'a,
Renderer: core::text::Renderer,
{
ComboBox::new(state, placeholder, selection, on_selected)
}
/// Creates some empty [`Space`] with no size.
///
/// This is considered the "identity" widget. It will take
/// no space and do nothing.
pub fn space() -> Space {
Space::new()
}
/// Creates a new [`ProgressBar`].
///
/// Progress bars visualize the progression of an extended computer operation, such as a download, file transfer, or installation.
///
/// It expects:
/// * an inclusive range of possible values, and
/// * the current value of the [`ProgressBar`].
///
/// # Example
/// ```no_run
/// # mod iced { pub mod widget { pub use iced_widget::*; } pub use iced_widget::Renderer; pub use iced_widget::core::*; }
/// # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>;
/// #
/// use iced::widget::progress_bar;
///
/// struct State {
/// progress: f32,
/// }
///
/// enum Message {
/// // ...
/// }
///
/// fn view(state: &State) -> Element<'_, Message> {
/// progress_bar(0.0..=100.0, state.progress).into()
/// }
/// ```
2024-03-12 15:45:21 +01:00
pub fn progress_bar<'a, Theme>(
range: RangeInclusive<f32>,
value: f32,
2024-03-12 15:45:21 +01:00
) -> ProgressBar<'a, Theme>
where
2024-03-24 05:03:09 +01:00
Theme: progress_bar::Catalog + 'a,
{
ProgressBar::new(range, value)
}
/// Creates a new [`Image`].
///
/// Images display raster graphics in different formats (PNG, JPG, etc.).
///
/// [`Image`]: crate::Image
///
/// # Example
/// ```no_run
/// # mod iced { pub mod widget { pub use iced_widget::*; } }
/// # pub type State = ();
/// # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>;
/// use iced::widget::image;
///
/// enum Message {
/// // ...
/// }
///
/// fn view(state: &State) -> Element<'_, Message> {
/// image("ferris.png").into()
/// }
/// ```
/// <img src="https://github.com/iced-rs/iced/blob/9712b319bb7a32848001b96bd84977430f14b623/examples/resources/ferris.png?raw=true" width="300">
#[cfg(feature = "image")]
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 f39a5fd8953494fd8e41c05bc053519740d09612) 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.
2023-05-02 15:48:20 -07:00
#[cfg_attr(docsrs, doc(cfg(feature = "image")))]
pub fn image<'a, Handle>(
handle: impl Into<Handle>,
) -> crate::Image<'a, Handle> {
crate::Image::new(handle.into())
}
/// Creates a new [`Svg`] widget from the given [`Handle`].
///
/// Svg widgets display vector graphics in your application.
///
/// [`Svg`]: crate::Svg
/// [`Handle`]: crate::svg::Handle
///
/// # Example
/// ```no_run
/// # mod iced { pub mod widget { pub use iced_widget::*; } }
/// # pub type State = ();
/// # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>;
/// use iced::widget::svg;
///
/// enum Message {
/// // ...
/// }
///
/// fn view(state: &State) -> Element<'_, Message> {
/// svg("tiger.svg").into()
/// }
/// ```
#[cfg(feature = "svg")]
2024-03-12 13:41:14 +01:00
pub fn svg<'a, Theme>(
handle: impl Into<core::svg::Handle>,
) -> crate::Svg<'a, Theme>
where
Theme: crate::svg::Catalog,
{
crate::Svg::new(handle)
}
/// Creates an [`Element`] that displays the iced logo with the given `text_size`.
///
/// Useful for showing some love to your favorite GUI library in your "About" screen,
/// for instance.
pub fn iced<'a, Message, Theme, Renderer>(
text_size: impl Into<core::Pixels>,
) -> Element<'a, Message, Theme, Renderer>
where
Message: 'a,
Renderer: core::Renderer + core::text::Renderer<Font = core::Font> + 'a,
2025-04-25 15:45:36 +02:00
Theme: text::Catalog + container::Catalog + 'a,
<Theme as container::Catalog>::Class<'a>:
From<container::StyleFn<'a, Theme>>,
<Theme as text::Catalog>::Class<'a>: From<text::StyleFn<'a, Theme>>,
{
use crate::core::border;
use crate::core::color;
use crate::core::gradient;
use crate::core::{Alignment, Color, Font, Radians};
let text_size = text_size.into();
row![
2025-04-25 15:45:36 +02:00
container(
text(Renderer::ICED_LOGO)
.line_height(1.0)
.size(text_size)
.font(Renderer::ICON_FONT)
.color(Color::WHITE)
)
.padding(text_size * 0.15)
.style(move |_| container::Style {
background: Some(
gradient::Linear::new(Radians::PI / 4.0)
.add_stop(0.0, color!(0x0033ff))
2025-04-27 13:02:01 +02:00
.add_stop(1.0, color!(0x1177ff))
2025-04-25 15:45:36 +02:00
.into()
),
border: border::rounded(border::radius(text_size * 0.4)),
2025-04-25 15:45:36 +02:00
..container::Style::default()
}),
text("iced").size(text_size).font(Font::MONOSPACE)
]
.spacing(text_size.0 / 3.0)
.align_y(Alignment::Center)
.into()
}
/// Creates a new [`Canvas`].
///
/// Canvases can be leveraged to draw interactive 2D graphics.
///
/// [`Canvas`]: crate::Canvas
///
/// # Example: Drawing a Simple Circle
/// ```no_run
/// # mod iced { pub mod widget { pub use iced_widget::*; } pub use iced_widget::Renderer; pub use iced_widget::core::*; }
/// # pub type State = ();
/// # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>;
/// #
/// use iced::mouse;
/// use iced::widget::canvas;
/// use iced::{Color, Rectangle, Renderer, Theme};
///
/// // First, we define the data we need for drawing
/// #[derive(Debug)]
/// struct Circle {
/// radius: f32,
/// }
///
/// // Then, we implement the `Program` trait
/// impl<Message> canvas::Program<Message> for Circle {
/// // No internal state
/// type State = ();
///
/// fn draw(
/// &self,
/// _state: &(),
/// renderer: &Renderer,
/// _theme: &Theme,
/// bounds: Rectangle,
/// _cursor: mouse::Cursor
/// ) -> Vec<canvas::Geometry> {
/// // We prepare a new `Frame`
/// let mut frame = canvas::Frame::new(renderer, bounds.size());
///
/// // We create a `Path` representing a simple circle
/// let circle = canvas::Path::circle(frame.center(), self.radius);
///
/// // And fill it with some color
/// frame.fill(&circle, Color::BLACK);
///
/// // Then, we produce the geometry
/// vec![frame.into_geometry()]
/// }
/// }
///
/// // Finally, we simply use our `Circle` to create the `Canvas`!
/// fn view<'a, Message: 'a>(_state: &'a State) -> Element<'a, Message> {
/// canvas(Circle { radius: 50.0 }).into()
/// }
/// ```
#[cfg(feature = "canvas")]
pub fn canvas<P, Message, Theme, Renderer>(
program: P,
) -> crate::Canvas<P, Message, Theme, Renderer>
where
Renderer: crate::graphics::geometry::Renderer,
P: crate::canvas::Program<Message, Theme, Renderer>,
{
crate::Canvas::new(program)
}
2024-02-15 02:38:07 +01:00
/// Creates a new [`QRCode`] widget from the given [`Data`].
///
/// QR codes display information in a type of two-dimensional matrix barcode.
///
/// [`QRCode`]: crate::QRCode
2024-02-15 02:38:07 +01:00
/// [`Data`]: crate::qr_code::Data
///
/// # Example
/// ```no_run
/// # mod iced { pub mod widget { pub use iced_widget::*; } pub use iced_widget::Renderer; pub use iced_widget::core::*; }
/// # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>;
/// #
/// use iced::widget::qr_code;
///
/// struct State {
/// data: qr_code::Data,
/// }
///
/// #[derive(Debug, Clone)]
/// enum Message {
/// // ...
/// }
///
/// fn view(state: &State) -> Element<'_, Message> {
/// qr_code(&state.data).into()
/// }
/// ```
2024-02-15 02:38:07 +01:00
#[cfg(feature = "qr_code")]
2024-03-12 14:51:30 +01:00
pub fn qr_code<'a, Theme>(
data: &'a crate::qr_code::Data,
) -> crate::QRCode<'a, Theme>
2024-02-15 02:38:07 +01:00
where
2024-03-24 05:03:09 +01:00
Theme: crate::qr_code::Catalog + 'a,
2024-02-15 02:38:07 +01:00
{
crate::QRCode::new(data)
}
/// Creates a new [`Shader`].
///
/// [`Shader`]: crate::Shader
#[cfg(feature = "wgpu")]
pub fn shader<Message, P>(program: P) -> crate::Shader<Message, P>
where
P: crate::shader::Program<Message>,
{
crate::Shader::new(program)
}
/// Creates a new [`MouseArea`].
pub fn mouse_area<'a, Message, Theme, Renderer>(
widget: impl Into<Element<'a, Message, Theme, Renderer>>,
) -> MouseArea<'a, Message, Theme, Renderer>
where
Renderer: core::Renderer,
{
MouseArea::new(widget)
}
2024-01-21 19:02:01 +01:00
/// A widget that applies any `Theme` to its contents.
pub fn themer<'a, Message, Theme, Renderer>(
theme: Option<Theme>,
content: impl Into<Element<'a, Message, Theme, Renderer>>,
) -> Themer<'a, Message, Theme, Renderer>
2024-01-21 19:02:01 +01:00
where
Theme: theme::Base,
2024-01-21 19:02:01 +01:00
Renderer: core::Renderer,
{
Themer::new(theme, content)
2024-01-21 19:02:01 +01:00
}
/// Creates a [`PaneGrid`] with the given [`pane_grid::State`] and view function.
///
/// Pane grids let your users split regions of your application and organize layout dynamically.
///
/// # Example
/// ```no_run
/// # mod iced { pub mod widget { pub use iced_widget::*; } pub use iced_widget::Renderer; pub use iced_widget::core::*; }
/// # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>;
/// #
/// use iced::widget::{pane_grid, text};
///
/// struct State {
/// panes: pane_grid::State<Pane>,
/// }
///
/// enum Pane {
/// SomePane,
/// AnotherKindOfPane,
/// }
///
/// enum Message {
/// PaneDragged(pane_grid::DragEvent),
/// PaneResized(pane_grid::ResizeEvent),
/// }
///
/// fn view(state: &State) -> Element<'_, Message> {
/// pane_grid(&state.panes, |pane, state, is_maximized| {
/// pane_grid::Content::new(match state {
/// Pane::SomePane => text("This is some pane"),
/// Pane::AnotherKindOfPane => text("This is another kind of pane"),
/// })
/// })
/// .on_drag(Message::PaneDragged)
/// .on_resize(10, Message::PaneResized)
/// .into()
/// }
/// ```
pub fn pane_grid<'a, T, Message, Theme, Renderer>(
state: &'a pane_grid::State<T>,
view: impl Fn(
pane_grid::Pane,
&'a T,
bool,
) -> pane_grid::Content<'a, Message, Theme, Renderer>,
) -> PaneGrid<'a, Message, Theme, Renderer>
where
2024-05-09 12:32:25 +02:00
Theme: pane_grid::Catalog,
Renderer: core::Renderer,
{
PaneGrid::new(state, view)
}
/// Creates a new [`Float`] widget with the given content.
pub fn float<'a, Message, Theme, Renderer>(
content: impl Into<Element<'a, Message, Theme, Renderer>>,
) -> Float<'a, Message, Theme, Renderer>
where
Theme: float::Catalog,
Renderer: core::Renderer,
{
Float::new(content)
}
/// Creates a new [`Responsive`] widget with a closure that produces its
/// contents.
///
/// The `view` closure will receive the maximum available space for
/// the [`Responsive`] during layout. You can use this [`Size`] to
/// conditionally build the contents.
pub fn responsive<'a, Message, Theme, Renderer>(
f: impl Fn(Size) -> Element<'a, Message, Theme, Renderer> + 'a,
) -> Responsive<'a, Message, Theme, Renderer>
where
Renderer: core::Renderer,
{
Responsive::new(f)
}