iced-yoda/widget/src/text_input.rs

1910 lines
64 KiB
Rust
Raw Normal View History

//! 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;
//! }
//! }
//! }
//! ```
mod editor;
2020-03-24 20:36:33 +01:00
mod value;
2020-03-24 20:23:31 +01:00
pub mod cursor;
pub use cursor::Cursor;
2020-03-24 20:36:33 +01:00
pub use value::Value;
2020-03-24 20:23:31 +01:00
use editor::Editor;
use crate::core::alignment;
2024-02-13 03:14:08 +01:00
use crate::core::clipboard::{self, Clipboard};
use crate::core::input_method;
use crate::core::keyboard;
use crate::core::keyboard::key;
use crate::core::layout;
use crate::core::mouse::{self, click};
use crate::core::renderer;
use crate::core::text::paragraph::{self, Paragraph as _};
2024-07-17 18:47:58 +02:00
use crate::core::text::{self, Text};
use crate::core::time::{Duration, Instant};
use crate::core::touch;
use crate::core::widget;
use crate::core::widget::operation::{self, Operation};
use crate::core::widget::tree::{self, Tree};
use crate::core::window;
use crate::core::{
Alignment, Background, Border, Color, Element, Event, InputMethod, Layout,
Length, Padding, Pixels, Point, Rectangle, Shell, Size, Theme, Vector,
Widget,
};
/// A field that can be filled with text.
///
/// # Example
2023-03-05 04:19:31 +01:00
/// ```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,
/// }
///
2019-11-24 10:48:29 +01:00
/// #[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 struct TextInput<
'a,
Message,
Theme = crate::Theme,
Renderer = crate::Renderer,
> where
2024-03-24 05:03:09 +01:00
Theme: Catalog,
Renderer: text::Renderer,
{
id: Option<widget::Id>,
placeholder: String,
value: Value,
is_secure: bool,
font: Option<Renderer::Font>,
width: Length,
2020-11-23 17:19:21 +00:00
padding: Padding,
size: Option<Pixels>,
line_height: text::LineHeight,
2026-03-31 14:24:39 -06:00
alignment: Option<alignment::Horizontal>,
on_input: Option<Box<dyn Fn(String) -> Message + 'a>>,
on_paste: Option<Box<dyn Fn(String) -> Message + 'a>>,
on_submit: Option<Message>,
icon: Option<Icon<Renderer::Font>>,
2024-03-24 05:03:09 +01:00
class: Theme::Class<'a>,
last_status: Option<Status>,
}
/// The default [`Padding`] of a [`TextInput`].
pub const DEFAULT_PADDING: Padding = Padding::new(5.0);
impl<'a, Message, Theme, Renderer> TextInput<'a, Message, Theme, Renderer>
where
Message: Clone,
2024-03-24 05:03:09 +01:00
Theme: Catalog,
Renderer: text::Renderer,
{
/// Creates a new [`TextInput`] with the given placeholder and
/// its current value.
2024-03-24 05:03:09 +01:00
pub fn new(placeholder: &str, value: &str) -> Self {
TextInput {
id: None,
placeholder: String::from(placeholder),
value: Value::new(value),
is_secure: false,
font: None,
width: Length::Fill,
padding: DEFAULT_PADDING,
size: None,
line_height: text::LineHeight::default(),
2026-03-31 14:24:39 -06:00
alignment: None,
on_input: None,
on_paste: None,
on_submit: None,
icon: None,
2024-03-24 05:03:09 +01:00
class: Theme::default(),
last_status: None,
}
}
2025-08-23 02:41:52 +02:00
/// Sets the [`widget::Id`] of the [`TextInput`].
pub fn id(mut self, id: impl Into<widget::Id>) -> Self {
self.id = Some(id.into());
self
}
/// Converts the [`TextInput`] into a secure password input.
pub fn secure(mut self, is_secure: bool) -> Self {
self.is_secure = is_secure;
self
}
/// Sets the message that should be produced when some text is typed into
/// the [`TextInput`].
///
/// If this method is not called, the [`TextInput`] will be disabled.
pub fn on_input(
mut self,
on_input: impl Fn(String) -> Message + 'a,
) -> Self {
self.on_input = Some(Box::new(on_input));
self
}
/// Sets the message that should be produced when some text is typed into
/// the [`TextInput`], if `Some`.
///
/// If `None`, the [`TextInput`] will be disabled.
pub fn on_input_maybe(
mut self,
on_input: Option<impl Fn(String) -> Message + 'a>,
) -> Self {
self.on_input = on_input.map(|f| Box::new(f) as _);
self
}
/// Sets the message that should be produced when the [`TextInput`] is
/// focused and the enter key is pressed.
pub fn on_submit(mut self, message: Message) -> Self {
self.on_submit = Some(message);
self
}
/// Sets the message that should be produced when the [`TextInput`] is
/// focused and the enter key is pressed, if `Some`.
pub fn on_submit_maybe(mut self, on_submit: Option<Message>) -> Self {
self.on_submit = on_submit;
self
}
/// Sets the message that should be produced when some text is pasted into
/// the [`TextInput`].
pub fn on_paste(
mut self,
on_paste: impl Fn(String) -> Message + 'a,
) -> Self {
self.on_paste = Some(Box::new(on_paste));
self
}
/// Sets the message that should be produced when some text is pasted into
/// the [`TextInput`], if `Some`.
pub fn on_paste_maybe(
mut self,
on_paste: Option<impl Fn(String) -> Message + 'a>,
) -> Self {
self.on_paste = on_paste.map(|f| Box::new(f) as _);
self
}
/// Sets the [`Font`] of the [`TextInput`].
///
/// [`Font`]: text::Renderer::Font
pub fn font(mut self, font: Renderer::Font) -> Self {
self.font = Some(font);
self
}
2023-02-13 11:38:05 +01:00
/// Sets the [`Icon`] of the [`TextInput`].
pub fn icon(mut self, icon: Icon<Renderer::Font>) -> Self {
self.icon = Some(icon);
2023-02-13 11:38:05 +01:00
self
}
/// Sets the width of the [`TextInput`].
pub fn width(mut self, width: impl Into<Length>) -> Self {
self.width = width.into();
self
}
2020-11-23 17:19:21 +00:00
/// Sets the [`Padding`] of the [`TextInput`].
pub fn padding<P: Into<Padding>>(mut self, padding: P) -> Self {
self.padding = padding.into();
self
}
/// Sets the text size of the [`TextInput`].
2023-02-04 16:41:18 +01:00
pub fn size(mut self, size: impl Into<Pixels>) -> Self {
self.size = Some(size.into());
self
}
/// Sets the [`text::LineHeight`] of the [`TextInput`].
pub fn line_height(
mut self,
line_height: impl Into<text::LineHeight>,
) -> Self {
self.line_height = line_height.into();
self
}
/// Sets the horizontal alignment of the [`TextInput`].
pub fn align_x(
mut self,
alignment: impl Into<alignment::Horizontal>,
) -> Self {
2026-03-31 14:24:39 -06:00
self.alignment = Some(alignment.into());
self
}
2020-01-01 18:26:49 +01:00
/// Sets the style of the [`TextInput`].
2024-03-24 05:03:09 +01:00
#[must_use]
pub fn style(mut self, style: impl Fn(&Theme, Status) -> Style + 'a) -> Self
where
Theme::Class<'a>: From<StyleFn<'a, Theme>>,
{
self.class = (Box::new(style) as StyleFn<'a, Theme>).into();
self
}
/// Sets the style class of the [`TextInput`].
#[must_use]
pub fn class(mut self, class: impl Into<Theme::Class<'a>>) -> Self {
self.class = class.into();
2020-01-01 18:26:49 +01:00
self
}
/// Lays out the [`TextInput`], overriding its [`Value`] if provided.
///
/// [`Renderer`]: text::Renderer
pub fn layout(
&mut self,
tree: &mut Tree,
renderer: &Renderer,
limits: &layout::Limits,
value: Option<&Value>,
) -> layout::Node {
let state = tree.state.downcast_mut::<State<Renderer::Paragraph>>();
let value = value.unwrap_or(&self.value);
let font = self.font.unwrap_or_else(|| renderer.default_font());
let text_size = self.size.unwrap_or_else(|| renderer.default_size());
let padding = self.padding.fit(Size::ZERO, limits.max());
let height = self.line_height.to_absolute(text_size);
let limits = limits.width(self.width).shrink(padding);
let text_bounds = limits.resolve(self.width, height, Size::ZERO);
let placeholder_text = Text {
font,
line_height: self.line_height,
content: self.placeholder.as_str(),
bounds: Size::new(f32::INFINITY, text_bounds.height),
size: text_size,
align_x: text::Alignment::Default,
align_y: alignment::Vertical::Center,
shaping: text::Shaping::Advanced,
wrapping: text::Wrapping::default(),
2026-02-19 09:27:37 -07:00
ellipsize: text::Ellipsize::default(),
};
let _ = state.placeholder.update(placeholder_text);
let secure_value = self.is_secure.then(|| value.secure());
let value = secure_value.as_ref().unwrap_or(value);
let _ = state.value.update(Text {
content: &value.to_string(),
..placeholder_text
});
if let Some(icon) = &self.icon {
let mut content = [0; 4];
let icon_text = Text {
line_height: self.line_height,
content: icon.code_point.encode_utf8(&mut content) as &_,
font: icon.font,
size: icon.size.unwrap_or_else(|| renderer.default_size()),
bounds: Size::new(f32::INFINITY, text_bounds.height),
align_x: text::Alignment::Center,
align_y: alignment::Vertical::Center,
shaping: text::Shaping::Advanced,
wrapping: text::Wrapping::default(),
2026-02-19 09:27:37 -07:00
ellipsize: text::Ellipsize::default(),
};
let _ = state.icon.update(icon_text);
let icon_width = state.icon.min_width();
let (text_position, icon_position) = match icon.side {
Side::Left => (
Point::new(
padding.left + icon_width + icon.spacing,
padding.top,
),
Point::new(padding.left, padding.top),
),
Side::Right => (
Point::new(padding.left, padding.top),
Point::new(
padding.left + text_bounds.width - icon_width,
padding.top,
),
),
};
let text_node = layout::Node::new(
text_bounds - Size::new(icon_width + icon.spacing, 0.0),
)
.move_to(text_position);
let icon_node =
layout::Node::new(Size::new(icon_width, text_bounds.height))
.move_to(icon_position);
layout::Node::with_children(
text_bounds.expand(padding),
vec![text_node, icon_node],
)
} else {
let text = layout::Node::new(text_bounds)
.move_to(Point::new(padding.left, padding.top));
layout::Node::with_children(text_bounds.expand(padding), vec![text])
}
}
fn input_method<'b>(
2025-01-10 07:12:31 +09:00
&self,
state: &'b State<Renderer::Paragraph>,
2025-01-10 07:12:31 +09:00
layout: Layout<'_>,
value: &Value,
) -> InputMethod<&'b str> {
let Some(Focus {
is_window_focused: true,
..
}) = &state.is_focused
else {
return InputMethod::Disabled;
};
2025-01-10 07:12:31 +09:00
let secure_value = self.is_secure.then(|| value.secure());
let value = secure_value.as_ref().unwrap_or(value);
2025-02-03 01:30:41 +01:00
let text_bounds = layout.children().next().unwrap().bounds();
2025-01-10 07:12:31 +09:00
let caret_index = match state.cursor.state(value) {
cursor::State::Index(position) => position,
cursor::State::Selection { start, end } => start.min(end),
};
2025-02-02 17:50:12 +01:00
let text = state.value.raw();
2026-03-31 14:24:39 -06:00
let effective_alignment = effective_alignment(self.alignment, text);
let (cursor_x, _) = measure_cursor_and_scroll_offset(
text,
text_bounds,
caret_index,
value,
state.cursor.affinity(),
state.scroll_offset,
);
2025-01-10 07:12:31 +09:00
let alignment_offset = alignment_offset(
text_bounds.width,
text.min_width(),
2026-03-31 14:24:39 -06:00
effective_alignment,
);
2025-01-10 07:12:31 +09:00
2026-03-31 14:24:39 -06:00
let x = (text_bounds.x + cursor_x).floor() - state.scroll_offset
+ alignment_offset;
2025-02-02 17:50:12 +01:00
InputMethod::Enabled {
cursor: Rectangle::new(
Point::new(x, text_bounds.y),
Size::new(1.0, text_bounds.height),
),
purpose: if self.is_secure {
input_method::Purpose::Secure
} else {
input_method::Purpose::Normal
},
preedit: state.preedit.as_ref().map(input_method::Preedit::as_ref),
2025-01-10 07:12:31 +09:00
}
}
/// Draws the [`TextInput`] with the given [`Renderer`], overriding its
2022-11-10 00:10:53 +01:00
/// [`Value`] if provided.
///
/// [`Renderer`]: text::Renderer
pub fn draw(
&self,
tree: &Tree,
renderer: &mut Renderer,
theme: &Theme,
layout: Layout<'_>,
_cursor: mouse::Cursor,
value: Option<&Value>,
viewport: &Rectangle,
) {
let state = tree.state.downcast_ref::<State<Renderer::Paragraph>>();
let value = value.unwrap_or(&self.value);
let is_disabled = self.on_input.is_none();
let secure_value = self.is_secure.then(|| value.secure());
let value = secure_value.as_ref().unwrap_or(value);
let bounds = layout.bounds();
let mut children_layout = layout.children();
let text_bounds = children_layout.next().unwrap().bounds();
let style = theme
.style(&self.class, self.last_status.unwrap_or(Status::Disabled));
renderer.fill_quad(
renderer::Quad {
bounds,
2024-03-24 05:03:09 +01:00
border: style.border,
..renderer::Quad::default()
},
2024-03-24 05:03:09 +01:00
style.background,
);
if self.icon.is_some() {
let icon_layout = children_layout.next().unwrap();
let icon = state.icon.raw();
renderer.fill_paragraph(
icon,
icon_layout.bounds().anchor(
icon.min_bounds(),
Alignment::Center,
Alignment::Center,
),
2024-03-24 05:03:09 +01:00
style.icon,
*viewport,
);
}
let text = value.to_string();
2026-03-31 14:24:39 -06:00
let (cursors, offset, is_selecting) = if let Some(focus) = state
.is_focused
.as_ref()
.filter(|focus| focus.is_window_focused)
{
match state.cursor.state(value) {
cursor::State::Index(position) => {
2026-03-31 14:24:39 -06:00
let (text_value_width, _) =
measure_cursor_and_scroll_offset(
2024-07-17 18:47:58 +02:00
state.value.raw(),
text_bounds,
position,
2026-03-31 14:24:39 -06:00
value,
state.cursor.affinity(),
state.scroll_offset,
);
let is_cursor_visible = !is_disabled
&& ((focus.now - focus.updated_at).as_millis()
/ CURSOR_BLINK_INTERVAL_MILLIS)
2025-09-19 18:22:45 +02:00
.is_multiple_of(2);
2026-03-31 14:24:39 -06:00
let cursors = if is_cursor_visible {
vec![(
renderer::Quad {
bounds: Rectangle {
x: (text_bounds.x + text_value_width)
.floor(),
y: text_bounds.y,
width: 1.0,
height: text_bounds.height,
},
..renderer::Quad::default()
},
2024-03-24 05:03:09 +01:00
style.value,
2026-03-31 14:24:39 -06:00
)]
} else {
2026-03-31 14:24:39 -06:00
vec![]
};
2026-03-31 14:24:39 -06:00
(cursors, state.scroll_offset, false)
}
cursor::State::Selection { start, end } => {
let left = start.min(end);
let right = end.max(start);
2026-03-31 14:24:39 -06:00
let lo_byte = value.byte_index_at_grapheme(left);
let hi_byte = value.byte_index_at_grapheme(right);
2026-03-31 14:24:39 -06:00
let rects = state.value.raw().highlight(
0,
(lo_byte, text::Affinity::After),
(hi_byte, text::Affinity::Before),
);
2026-03-31 14:24:39 -06:00
let cursors: Vec<(renderer::Quad, Color)> = rects
.into_iter()
.map(|r| {
(
renderer::Quad {
bounds: Rectangle {
x: text_bounds.x + r.x,
y: text_bounds.y,
width: r.width,
height: text_bounds.height,
},
..renderer::Quad::default()
},
2026-03-31 14:24:39 -06:00
style.selection,
)
})
.collect();
(cursors, state.scroll_offset, true)
}
}
} else {
2026-03-31 14:24:39 -06:00
let unfocused_offset = {
match effective_alignment(self.alignment, state.value.raw()) {
alignment::Horizontal::Right => {
(state.value.raw().min_width() - text_bounds.width)
.max(0.0)
}
_ => 0.0,
}
};
(vec![], unfocused_offset, false)
};
let draw = |renderer: &mut Renderer, viewport| {
let paragraph = if text.is_empty()
&& state
.preedit
.as_ref()
.map(|preedit| preedit.content.is_empty())
.unwrap_or(true)
{
state.placeholder.raw()
} else {
state.value.raw()
};
let alignment_offset = alignment_offset(
text_bounds.width,
paragraph.min_width(),
2026-03-31 14:24:39 -06:00
effective_alignment(self.alignment, paragraph),
);
2026-03-31 14:24:39 -06:00
if !cursors.is_empty() {
renderer.with_translation(
Vector::new(alignment_offset - offset, 0.0),
|renderer| {
2026-03-31 14:24:39 -06:00
for (quad, color) in &cursors {
renderer.fill_quad(*quad, *color);
}
},
);
} else {
renderer.with_translation(Vector::ZERO, |_| {});
}
renderer.fill_paragraph(
paragraph,
text_bounds.anchor(
paragraph.min_bounds(),
Alignment::Start,
Alignment::Center,
) + Vector::new(alignment_offset - offset, 0.0),
if text.is_empty() {
2024-03-24 05:03:09 +01:00
style.placeholder
} else {
2024-03-24 05:03:09 +01:00
style.value
},
viewport,
);
};
if is_selecting {
2026-03-31 14:24:39 -06:00
renderer.with_layer(bounds, |renderer| draw(renderer, *viewport));
} else {
2026-03-31 14:24:39 -06:00
draw(renderer, bounds);
}
}
}
2024-12-02 19:53:16 +01:00
impl<Message, Theme, Renderer> Widget<Message, Theme, Renderer>
for TextInput<'_, Message, Theme, Renderer>
where
Message: Clone,
2024-03-24 05:03:09 +01:00
Theme: Catalog,
Renderer: text::Renderer,
{
fn tag(&self) -> tree::Tag {
tree::Tag::of::<State<Renderer::Paragraph>>()
}
fn state(&self) -> tree::State {
tree::State::new(State::<Renderer::Paragraph>::new())
}
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) {
let state = tree.state.downcast_mut::<State<Renderer::Paragraph>>();
// Stop pasting if input becomes disabled
if self.on_input.is_none() {
state.is_pasting = None;
}
}
fn size(&self) -> Size<Length> {
Size {
width: self.width,
height: Length::Shrink,
}
}
fn layout(
&mut self,
tree: &mut Tree,
renderer: &Renderer,
limits: &layout::Limits,
) -> layout::Node {
self.layout(tree, renderer, limits, None)
}
fn operate(
&mut self,
tree: &mut Tree,
layout: Layout<'_>,
2022-12-22 14:29:24 +01:00
_renderer: &Renderer,
operation: &mut dyn Operation,
) {
let state = tree.state.downcast_mut::<State<Renderer::Paragraph>>();
operation.text_input(self.id.as_ref(), layout.bounds(), state);
operation.focusable(self.id.as_ref(), layout.bounds(), state);
}
2024-10-25 22:06:06 +02:00
fn update(
&mut self,
tree: &mut Tree,
event: &Event,
layout: Layout<'_>,
2023-06-08 20:11:59 +02:00
cursor: mouse::Cursor,
renderer: &Renderer,
clipboard: &mut dyn Clipboard,
shell: &mut Shell<'_, Message>,
2023-07-15 10:04:25 -07:00
_viewport: &Rectangle,
) {
let update_cache = |state, value| {
replace_paragraph(
renderer,
state,
layout,
value,
self.font,
self.size,
self.line_height,
);
};
match &event {
Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left))
| Event::Touch(touch::Event::FingerPressed { .. }) => {
let state = state::<Renderer>(tree);
let cursor_before = state.cursor;
let click_position = cursor.position_over(layout.bounds());
state.is_focused = if click_position.is_some() {
let now = Instant::now();
Some(Focus {
updated_at: now,
now,
is_window_focused: true,
})
} else {
None
};
if let Some(cursor_position) = click_position {
let text_layout = layout.children().next().unwrap();
let target = {
let text_bounds = text_layout.bounds();
let alignment_offset = alignment_offset(
text_bounds.width,
state.value.raw().min_width(),
2026-03-31 14:24:39 -06:00
effective_alignment(
self.alignment,
state.value.raw(),
),
);
cursor_position.x - text_bounds.x - alignment_offset
};
2024-04-30 11:49:50 -04:00
let click = mouse::Click::new(
cursor_position,
mouse::Button::Left,
state.last_click,
);
match click.kind() {
click::Kind::Single => {
2026-03-31 14:24:39 -06:00
let value = if self.is_secure {
self.value.secure()
} else {
2026-03-31 14:24:39 -06:00
self.value.clone()
};
let (position, affinity) = find_cursor_position(
text_layout.bounds(),
&value,
state,
target,
)
.unwrap_or((0, text::Affinity::Before));
state.cursor.set_affinity(affinity);
if state.keyboard_modifiers.shift() {
state.cursor.select_range(
state.cursor.start(&self.value),
position,
);
} else {
state.cursor.move_to(position);
}
state.is_dragging = Some(Drag::Select);
}
click::Kind::Double => {
if self.is_secure {
state.cursor.select_all(&self.value);
state.is_dragging = None;
} else {
2026-03-31 14:24:39 -06:00
let (position, affinity) =
find_cursor_position(
text_layout.bounds(),
&self.value,
state,
target,
)
.unwrap_or((0, text::Affinity::Before));
state.cursor.set_affinity(affinity);
state.cursor.select_range(
self.value.previous_start_of_word(position),
self.value.next_end_of_word(position),
);
state.is_dragging = Some(Drag::SelectWords {
anchor: position,
});
}
}
click::Kind::Triple => {
state.cursor.select_all(&self.value);
state.is_dragging = None;
}
}
state.last_click = Some(click);
if cursor_before != state.cursor {
shell.request_redraw();
}
shell.capture_event();
}
}
Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Left))
| Event::Touch(touch::Event::FingerLifted { .. })
| Event::Touch(touch::Event::FingerLost { .. }) => {
state::<Renderer>(tree).is_dragging = None;
}
Event::Mouse(mouse::Event::CursorMoved { position })
| Event::Touch(touch::Event::FingerMoved { position, .. }) => {
let state = state::<Renderer>(tree);
if let Some(is_dragging) = &state.is_dragging {
let text_layout = layout.children().next().unwrap();
let target = {
let text_bounds = text_layout.bounds();
let alignment_offset = alignment_offset(
text_bounds.width,
state.value.raw().min_width(),
2026-03-31 14:24:39 -06:00
effective_alignment(
self.alignment,
state.value.raw(),
),
);
position.x - text_bounds.x - alignment_offset
};
let value = if self.is_secure {
self.value.secure()
} else {
self.value.clone()
};
2026-03-31 14:24:39 -06:00
let (position, affinity) = find_cursor_position(
text_layout.bounds(),
&value,
state,
target,
)
2026-03-31 14:24:39 -06:00
.unwrap_or((0, text::Affinity::Before));
state.cursor.set_affinity(affinity);
let selection_before = state.cursor.selection(&value);
match is_dragging {
Drag::Select => {
state.cursor.select_range(
state.cursor.start(&value),
position,
);
}
Drag::SelectWords { anchor } => {
if position < *anchor {
state.cursor.select_range(
self.value.previous_start_of_word(position),
self.value.next_end_of_word(*anchor),
);
} else {
state.cursor.select_range(
self.value.previous_start_of_word(*anchor),
self.value.next_end_of_word(position),
);
}
}
}
if let Some(focus) = &mut state.is_focused {
focus.updated_at = Instant::now();
}
if selection_before != state.cursor.selection(&value) {
shell.request_redraw();
}
shell.capture_event();
}
}
Event::Keyboard(keyboard::Event::KeyPressed {
key,
text,
modified_key,
physical_key,
..
}) => {
let state = state::<Renderer>(tree);
if let Some(focus) = &mut state.is_focused {
let modifiers = state.keyboard_modifiers;
match key.to_latin(*physical_key) {
Some('c')
if state.keyboard_modifiers.command()
&& !self.is_secure =>
{
if let Some((start, end)) =
state.cursor.selection(&self.value)
{
clipboard.write(
clipboard::Kind::Standard,
self.value.select(start, end).to_string(),
);
}
shell.capture_event();
return;
}
Some('x')
if state.keyboard_modifiers.command()
&& !self.is_secure =>
{
let Some(on_input) = &self.on_input else {
return;
};
if let Some((start, end)) =
state.cursor.selection(&self.value)
{
clipboard.write(
clipboard::Kind::Standard,
self.value.select(start, end).to_string(),
);
}
let mut editor =
Editor::new(&mut self.value, &mut state.cursor);
editor.delete();
let message = (on_input)(editor.contents());
shell.publish(message);
shell.capture_event();
focus.updated_at = Instant::now();
update_cache(state, &self.value);
return;
}
Some('v')
if state.keyboard_modifiers.command()
&& !state.keyboard_modifiers.alt() =>
{
let Some(on_input) = &self.on_input else {
return;
};
let content = match state.is_pasting.take() {
Some(content) => content,
None => {
let content: String = clipboard
.read(clipboard::Kind::Standard)
.unwrap_or_default()
.chars()
.filter(|c| !c.is_control())
.collect();
Value::new(&content)
}
};
let mut editor =
Editor::new(&mut self.value, &mut state.cursor);
editor.paste(content.clone());
let message = if let Some(paste) = &self.on_paste {
(paste)(editor.contents())
} else {
(on_input)(editor.contents())
};
shell.publish(message);
shell.capture_event();
state.is_pasting = Some(content);
focus.updated_at = Instant::now();
update_cache(state, &self.value);
return;
}
Some('a') if state.keyboard_modifiers.command() => {
let cursor_before = state.cursor;
state.cursor.select_all(&self.value);
if cursor_before != state.cursor {
focus.updated_at = Instant::now();
shell.request_redraw();
}
shell.capture_event();
return;
}
_ => {}
}
if let Some(text) = text {
let Some(on_input) = &self.on_input else {
return;
};
state.is_pasting = None;
if let Some(c) =
text.chars().next().filter(|c| !c.is_control())
{
let mut editor =
Editor::new(&mut self.value, &mut state.cursor);
editor.insert(c);
let message = (on_input)(editor.contents());
shell.publish(message);
shell.capture_event();
focus.updated_at = Instant::now();
update_cache(state, &self.value);
return;
}
}
#[cfg(target_os = "macos")]
let macos_shortcut =
crate::text_editor::convert_macos_shortcut(
key, modifiers,
);
#[cfg(target_os = "macos")]
let modified_key =
macos_shortcut.as_ref().unwrap_or(modified_key);
match modified_key.as_ref() {
keyboard::Key::Named(key::Named::Enter) => {
if let Some(on_submit) = self.on_submit.clone() {
shell.publish(on_submit);
shell.capture_event();
}
}
keyboard::Key::Named(key::Named::Backspace) => {
let Some(on_input) = &self.on_input else {
return;
};
if state.cursor.selection(&self.value).is_none() {
if (self.is_secure && modifiers.jump())
|| modifiers.macos_command()
{
state.cursor.select_range(
state.cursor.start(&self.value),
0,
);
} else if modifiers.jump() {
state
.cursor
.select_left_by_words(&self.value);
}
}
let mut editor =
Editor::new(&mut self.value, &mut state.cursor);
editor.backspace();
let message = (on_input)(editor.contents());
shell.publish(message);
shell.capture_event();
focus.updated_at = Instant::now();
update_cache(state, &self.value);
}
keyboard::Key::Named(key::Named::Delete) => {
let Some(on_input) = &self.on_input else {
return;
};
if state.cursor.selection(&self.value).is_none() {
if (self.is_secure && modifiers.jump())
|| modifiers.macos_command()
{
state.cursor.select_range(
state.cursor.start(&self.value),
self.value.len(),
);
} else if modifiers.jump() {
state
.cursor
.select_right_by_words(&self.value);
}
}
let mut editor =
Editor::new(&mut self.value, &mut state.cursor);
editor.delete();
let message = (on_input)(editor.contents());
shell.publish(message);
shell.capture_event();
focus.updated_at = Instant::now();
update_cache(state, &self.value);
}
keyboard::Key::Named(key::Named::Home) => {
let cursor_before = state.cursor;
if modifiers.shift() {
state.cursor.select_range(
state.cursor.start(&self.value),
0,
);
} else {
state.cursor.move_to(0);
}
if cursor_before != state.cursor {
focus.updated_at = Instant::now();
shell.request_redraw();
}
shell.capture_event();
}
keyboard::Key::Named(key::Named::End) => {
let cursor_before = state.cursor;
if modifiers.shift() {
state.cursor.select_range(
state.cursor.start(&self.value),
self.value.len(),
);
} else {
state.cursor.move_to(self.value.len());
}
if cursor_before != state.cursor {
focus.updated_at = Instant::now();
shell.request_redraw();
}
shell.capture_event();
}
keyboard::Key::Named(key::Named::ArrowLeft) => {
let cursor_before = state.cursor;
2026-03-31 14:24:39 -06:00
let rtl =
state.value.raw().is_rtl(0).unwrap_or(false);
if (self.is_secure && modifiers.jump())
|| modifiers.macos_command()
{
if modifiers.shift() {
state.cursor.select_range(
state.cursor.start(&self.value),
0,
);
} else {
state.cursor.move_to(0);
}
2026-03-31 14:24:39 -06:00
} else {
let by_words = modifiers.jump();
if modifiers.shift() {
2026-03-31 14:24:39 -06:00
state.cursor.select_visual(
false,
by_words,
rtl,
&self.value,
);
} else {
2026-03-31 14:24:39 -06:00
state.cursor.move_visual(
false,
by_words,
rtl,
&self.value,
);
}
}
if cursor_before != state.cursor {
focus.updated_at = Instant::now();
shell.request_redraw();
}
shell.capture_event();
}
keyboard::Key::Named(key::Named::ArrowRight) => {
let cursor_before = state.cursor;
2026-03-31 14:24:39 -06:00
let rtl =
state.value.raw().is_rtl(0).unwrap_or(false);
if (self.is_secure && modifiers.jump())
|| modifiers.macos_command()
{
if modifiers.shift() {
state.cursor.select_range(
state.cursor.start(&self.value),
self.value.len(),
);
} else {
state.cursor.move_to(self.value.len());
}
2026-03-31 14:24:39 -06:00
} else {
let by_words = modifiers.jump();
if modifiers.shift() {
2026-03-31 14:24:39 -06:00
state.cursor.select_visual(
true,
by_words,
rtl,
&self.value,
);
} else {
2026-03-31 14:24:39 -06:00
state.cursor.move_visual(
true,
by_words,
rtl,
&self.value,
);
}
}
if cursor_before != state.cursor {
focus.updated_at = Instant::now();
shell.request_redraw();
}
shell.capture_event();
}
keyboard::Key::Named(key::Named::Escape) => {
state.is_focused = None;
state.is_dragging = None;
state.is_pasting = None;
state.keyboard_modifiers =
keyboard::Modifiers::default();
shell.capture_event();
}
_ => {}
}
}
}
Event::Keyboard(keyboard::Event::KeyReleased { key, .. }) => {
let state = state::<Renderer>(tree);
if state.is_focused.is_some()
&& let keyboard::Key::Character("v") = key.as_ref()
{
state.is_pasting = None;
shell.capture_event();
}
state.is_pasting = None;
}
Event::Keyboard(keyboard::Event::ModifiersChanged(modifiers)) => {
let state = state::<Renderer>(tree);
state.keyboard_modifiers = *modifiers;
}
Event::InputMethod(event) => match event {
input_method::Event::Opened | input_method::Event::Closed => {
let state = state::<Renderer>(tree);
2025-01-10 07:12:31 +09:00
state.preedit =
2025-02-12 07:26:26 +01:00
matches!(event, input_method::Event::Opened)
.then(input_method::Preedit::new);
shell.request_redraw();
}
input_method::Event::Preedit(content, selection) => {
let state = state::<Renderer>(tree);
2025-01-10 07:12:31 +09:00
if state.is_focused.is_some() {
state.preedit = Some(input_method::Preedit {
content: content.to_owned(),
selection: selection.clone(),
text_size: self.size,
});
shell.request_redraw();
}
}
input_method::Event::Commit(text) => {
let state = state::<Renderer>(tree);
2025-01-10 07:12:31 +09:00
if let Some(focus) = &mut state.is_focused {
let Some(on_input) = &self.on_input else {
return;
};
2025-01-10 07:12:31 +09:00
let mut editor =
Editor::new(&mut self.value, &mut state.cursor);
editor.paste(Value::new(text));
focus.updated_at = Instant::now();
state.is_pasting = None;
2025-01-10 07:12:31 +09:00
let message = (on_input)(editor.contents());
shell.publish(message);
shell.capture_event();
update_cache(state, &self.value);
}
2025-01-10 07:12:31 +09:00
}
},
Event::Window(window::Event::Unfocused) => {
let state = state::<Renderer>(tree);
if let Some(focus) = &mut state.is_focused {
focus.is_window_focused = false;
}
}
Event::Window(window::Event::Focused) => {
let state = state::<Renderer>(tree);
if let Some(focus) = &mut state.is_focused {
focus.is_window_focused = true;
focus.updated_at = Instant::now();
shell.request_redraw();
}
}
Event::Window(window::Event::RedrawRequested(now)) => {
let state = state::<Renderer>(tree);
if let Some(focus) = &mut state.is_focused
&& focus.is_window_focused
{
if matches!(
state.cursor.state(&self.value),
cursor::State::Index(_)
) {
focus.now = *now;
let millis_until_redraw = CURSOR_BLINK_INTERVAL_MILLIS
- (*now - focus.updated_at).as_millis()
% CURSOR_BLINK_INTERVAL_MILLIS;
shell.request_redraw_at(
*now + Duration::from_millis(
millis_until_redraw as u64,
),
);
}
shell.request_input_method(&self.input_method(
state,
layout,
&self.value,
));
}
}
_ => {}
}
let state = state::<Renderer>(tree);
2026-03-31 14:24:39 -06:00
// Cache scroll offset for consistent hit-testing in the next event.
// This prevents feedback loops where cursor changes alter the offset,
// which shifts the text, which causes the next hit-test to overshoot.
{
let text_layout = layout.children().next().unwrap();
state.scroll_offset = offset(
text_layout.bounds(),
&self.value,
state,
self.alignment,
);
}
let is_disabled = self.on_input.is_none();
let status = if is_disabled {
Status::Disabled
} else if state.is_focused() {
Status::Focused {
is_hovered: cursor.is_over(layout.bounds()),
}
} else if cursor.is_over(layout.bounds()) {
Status::Hovered
} else {
Status::Active
};
if let Event::Window(window::Event::RedrawRequested(_now)) = event {
self.last_status = Some(status);
} else if self
.last_status
.is_some_and(|last_status| status != last_status)
{
shell.request_redraw();
}
}
fn draw(
&self,
tree: &Tree,
renderer: &mut Renderer,
theme: &Theme,
_style: &renderer::Style,
layout: Layout<'_>,
2023-06-08 20:11:59 +02:00
cursor: mouse::Cursor,
viewport: &Rectangle,
) {
self.draw(tree, renderer, theme, layout, cursor, None, viewport);
}
fn mouse_interaction(
&self,
_tree: &Tree,
layout: Layout<'_>,
2023-06-08 20:11:59 +02:00
cursor: mouse::Cursor,
_viewport: &Rectangle,
_renderer: &Renderer,
) -> mouse::Interaction {
if cursor.is_over(layout.bounds()) {
if self.on_input.is_none() {
mouse::Interaction::Idle
} else {
mouse::Interaction::Text
}
} else {
mouse::Interaction::default()
}
}
}
impl<'a, Message, Theme, Renderer> From<TextInput<'a, Message, Theme, Renderer>>
for Element<'a, Message, Theme, Renderer>
where
2024-03-24 05:03:09 +01:00
Message: Clone + 'a,
Theme: Catalog + 'a,
Renderer: text::Renderer + 'a,
{
fn from(
text_input: TextInput<'a, Message, Theme, Renderer>,
) -> Element<'a, Message, Theme, Renderer> {
Element::new(text_input)
}
}
/// The content of the [`Icon`].
#[derive(Debug, Clone)]
pub struct Icon<Font> {
/// The font that will be used to display the `code_point`.
pub font: Font,
/// The unicode code point that will be used as the icon.
pub code_point: char,
/// The font size of the content.
pub size: Option<Pixels>,
/// The spacing between the [`Icon`] and the text in a [`TextInput`].
pub spacing: f32,
/// The side of a [`TextInput`] where to display the [`Icon`].
pub side: Side,
}
/// The side of a [`TextInput`].
#[derive(Debug, Clone)]
pub enum Side {
/// The left side of a [`TextInput`].
Left,
/// The right side of a [`TextInput`].
Right,
}
/// The state of a [`TextInput`].
#[derive(Debug, Default, Clone)]
pub struct State<P: text::Paragraph> {
2024-07-17 18:47:58 +02:00
value: paragraph::Plain<P>,
placeholder: paragraph::Plain<P>,
icon: paragraph::Plain<P>,
is_focused: Option<Focus>,
is_dragging: Option<Drag>,
is_pasting: Option<Value>,
preedit: Option<input_method::Preedit>,
last_click: Option<mouse::Click>,
cursor: Cursor,
keyboard_modifiers: keyboard::Modifiers,
2026-03-31 14:24:39 -06:00
scroll_offset: f32,
}
fn state<Renderer: text::Renderer>(
tree: &mut Tree,
) -> &mut State<Renderer::Paragraph> {
tree.state.downcast_mut::<State<Renderer::Paragraph>>()
}
#[derive(Debug, Clone)]
struct Focus {
updated_at: Instant,
now: Instant,
is_window_focused: bool,
}
#[derive(Debug, Clone)]
enum Drag {
Select,
SelectWords { anchor: usize },
}
impl<P: text::Paragraph> State<P> {
/// Creates a new [`State`], representing an unfocused [`TextInput`].
pub fn new() -> Self {
Self::default()
}
/// Returns whether the [`TextInput`] is currently focused or not.
pub fn is_focused(&self) -> bool {
self.is_focused.is_some()
}
/// Returns the [`Cursor`] of the [`TextInput`].
pub fn cursor(&self) -> Cursor {
self.cursor
}
2020-06-05 08:58:34 -07:00
/// Focuses the [`TextInput`].
pub fn focus(&mut self) {
let now = Instant::now();
self.is_focused = Some(Focus {
updated_at: now,
now,
is_window_focused: true,
});
self.move_cursor_to_end();
}
/// Unfocuses the [`TextInput`].
pub fn unfocus(&mut self) {
self.is_focused = None;
}
2020-06-05 08:58:34 -07:00
/// Moves the [`Cursor`] of the [`TextInput`] to the front of the input text.
pub fn move_cursor_to_front(&mut self) {
self.cursor.move_to(0);
}
/// Moves the [`Cursor`] of the [`TextInput`] to the end of the input text.
2020-06-08 10:00:25 -07:00
pub fn move_cursor_to_end(&mut self) {
self.cursor.move_to(usize::MAX);
2020-06-05 08:58:34 -07:00
}
2020-06-05 09:19:46 -07:00
/// Moves the [`Cursor`] of the [`TextInput`] to an arbitrary location.
pub fn move_cursor_to(&mut self, position: usize) {
self.cursor.move_to(position);
}
/// Selects all the content of the [`TextInput`].
pub fn select_all(&mut self) {
self.cursor.select_range(0, usize::MAX);
}
/// Selects the given range of the content of the [`TextInput`].
pub fn select_range(&mut self, start: usize, end: usize) {
self.cursor.select_range(start, end);
}
}
impl<P: text::Paragraph> operation::Focusable for State<P> {
2022-07-28 02:46:51 +02:00
fn is_focused(&self) -> bool {
State::is_focused(self)
}
fn focus(&mut self) {
State::focus(self);
2022-07-28 02:46:51 +02:00
}
fn unfocus(&mut self) {
State::unfocus(self);
2022-07-28 02:46:51 +02:00
}
}
impl<P: text::Paragraph> operation::TextInput for State<P> {
fn text(&self) -> &str {
if self.value.content().is_empty() {
self.placeholder.content()
} else {
self.value.content()
}
}
2022-11-11 08:43:36 -08:00
fn move_cursor_to_front(&mut self) {
State::move_cursor_to_front(self);
2022-11-11 08:43:36 -08:00
}
fn move_cursor_to_end(&mut self) {
State::move_cursor_to_end(self);
2022-11-11 08:43:36 -08:00
}
fn move_cursor_to(&mut self, position: usize) {
State::move_cursor_to(self, position);
2022-11-11 08:43:36 -08:00
}
fn select_all(&mut self) {
State::select_all(self);
2022-11-11 08:43:36 -08:00
}
fn select_range(&mut self, start: usize, end: usize) {
State::select_range(self, start, end);
}
2022-11-11 08:43:36 -08:00
}
fn offset<P: text::Paragraph>(
text_bounds: Rectangle,
value: &Value,
state: &State<P>,
2026-03-31 14:24:39 -06:00
alignment: Option<alignment::Horizontal>,
) -> f32 {
if state.is_focused() {
let cursor = state.cursor();
let focus_position = match cursor.state(value) {
cursor::State::Index(i) => i,
cursor::State::Selection { end, .. } => end,
};
let (_, offset) = measure_cursor_and_scroll_offset(
2024-07-17 18:47:58 +02:00
state.value.raw(),
text_bounds,
focus_position,
2026-03-31 14:24:39 -06:00
value,
state.cursor().affinity(),
state.scroll_offset,
);
offset
} else {
2026-03-31 14:24:39 -06:00
match effective_alignment(alignment, state.value.raw()) {
alignment::Horizontal::Right => {
(state.value.raw().min_width() - text_bounds.width).max(0.0)
}
_ => 0.0,
}
}
}
fn measure_cursor_and_scroll_offset(
paragraph: &impl text::Paragraph,
text_bounds: Rectangle,
cursor_index: usize,
2026-03-31 14:24:39 -06:00
value: &Value,
affinity: text::Affinity,
current_offset: f32,
) -> (f32, f32) {
2026-03-31 14:24:39 -06:00
let byte_index = value.byte_index_at_grapheme(cursor_index);
let position = paragraph
.cursor_position(0, byte_index, affinity)
.unwrap_or(Point::ORIGIN);
2026-03-31 14:24:39 -06:00
// The visible window in paragraph coordinates is:
// [current_offset, current_offset + text_bounds.width]
// Keep the cursor visible with a 5px margin on each side.
let offset = if position.x > current_offset + text_bounds.width - 5.0 {
// Cursor past right edge of visible window → scroll left
(position.x + 5.0) - text_bounds.width
} else if position.x < current_offset + 5.0 {
// Cursor past left edge of visible window → scroll right
position.x - 5.0
} else {
// Cursor is within visible window → keep current scroll
current_offset
};
let max_offset = (paragraph.min_width() - text_bounds.width).max(0.0);
let offset = offset.clamp(0.0, max_offset);
2026-03-31 14:24:39 -06:00
(position.x, offset)
}
/// Computes the position of the text cursor at the given X coordinate of
/// a [`TextInput`].
fn find_cursor_position<P: text::Paragraph>(
text_bounds: Rectangle,
value: &Value,
state: &State<P>,
x: f32,
2026-03-31 14:24:39 -06:00
) -> Option<(usize, text::Affinity)> {
let value_str = value.to_string();
let hit = state.value.raw().hit_test(Point::new(
x + state.scroll_offset,
text_bounds.height / 2.0,
))?;
let char_offset = hit.cursor();
let affinity = hit.affinity();
let grapheme_count = unicode_segmentation::UnicodeSegmentation::graphemes(
&value_str[..char_offset.min(value_str.len())],
true,
)
2026-03-31 14:24:39 -06:00
.count();
Some((grapheme_count, affinity))
}
fn replace_paragraph<Renderer>(
renderer: &Renderer,
state: &mut State<Renderer::Paragraph>,
layout: Layout<'_>,
value: &Value,
font: Option<Renderer::Font>,
text_size: Option<Pixels>,
line_height: text::LineHeight,
) where
Renderer: text::Renderer,
{
let font = font.unwrap_or_else(|| renderer.default_font());
let text_size = text_size.unwrap_or_else(|| renderer.default_size());
let mut children_layout = layout.children();
let text_bounds = children_layout.next().unwrap().bounds();
2024-07-17 18:47:58 +02:00
state.value = paragraph::Plain::new(Text {
font,
line_height,
content: value.to_string(),
bounds: Size::new(f32::INFINITY, text_bounds.height),
size: text_size,
align_x: text::Alignment::Default,
align_y: alignment::Vertical::Center,
shaping: text::Shaping::Advanced,
wrapping: text::Wrapping::default(),
2026-02-19 09:27:37 -07:00
ellipsize: text::Ellipsize::default(),
});
}
const CURSOR_BLINK_INTERVAL_MILLIS: u128 = 500;
/// The possible status of a [`TextInput`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Status {
/// The [`TextInput`] can be interacted with.
Active,
/// The [`TextInput`] is being hovered.
Hovered,
/// The [`TextInput`] is focused.
Focused {
/// Whether the [`TextInput`] is hovered, while focused.
is_hovered: bool,
},
/// The [`TextInput`] cannot be interacted with.
Disabled,
}
/// The appearance of a text input.
#[derive(Debug, Clone, Copy, PartialEq)]
2024-03-24 05:03:09 +01:00
pub struct Style {
/// The [`Background`] of the text input.
pub background: Background,
/// The [`Border`] of the text input.
pub border: Border,
/// The [`Color`] of the icon of the text input.
pub icon: Color,
/// The [`Color`] of the placeholder of the text input.
pub placeholder: Color,
/// The [`Color`] of the value of the text input.
pub value: Color,
/// The [`Color`] of the selection of the text input.
pub selection: Color,
}
2024-03-24 05:03:09 +01:00
/// The theme catalog of a [`TextInput`].
pub trait Catalog: Sized {
/// The item class of the [`Catalog`].
type Class<'a>;
2024-03-24 05:03:09 +01:00
/// The default class produced by the [`Catalog`].
fn default<'a>() -> Self::Class<'a>;
/// The [`Style`] of a class with the given status.
fn style(&self, class: &Self::Class<'_>, status: Status) -> Style;
}
2024-03-24 05:03:09 +01:00
/// A styling function for a [`TextInput`].
///
/// This is just a boxed closure: `Fn(&Theme, Status) -> Style`.
pub type StyleFn<'a, Theme> = Box<dyn Fn(&Theme, Status) -> Style + 'a>;
impl Catalog for Theme {
type Class<'a> = StyleFn<'a, Self>;
fn default<'a>() -> Self::Class<'a> {
Box::new(default)
}
2024-03-24 05:03:09 +01:00
fn style(&self, class: &Self::Class<'_>, status: Status) -> Style {
class(self, status)
}
}
/// The default style of a [`TextInput`].
2024-03-24 05:03:09 +01:00
pub fn default(theme: &Theme, status: Status) -> Style {
let palette = theme.extended_palette();
2024-03-24 05:03:09 +01:00
let active = Style {
background: Background::Color(palette.background.base.color),
border: Border {
radius: 2.0.into(),
width: 1.0,
color: palette.background.strong.color,
},
icon: palette.background.weak.text,
placeholder: palette.secondary.base.color,
value: palette.background.base.text,
selection: palette.primary.weak.color,
};
match status {
Status::Active => active,
2024-03-24 05:03:09 +01:00
Status::Hovered => Style {
border: Border {
color: palette.background.base.text,
..active.border
},
..active
},
Status::Focused { .. } => Style {
border: Border {
color: palette.primary.strong.color,
..active.border
},
..active
},
2024-03-24 05:03:09 +01:00
Status::Disabled => Style {
background: Background::Color(palette.background.weak.color),
value: active.placeholder,
placeholder: palette.background.strongest.color,
..active
},
}
}
fn alignment_offset(
text_bounds_width: f32,
text_min_width: f32,
alignment: alignment::Horizontal,
) -> f32 {
if text_min_width > text_bounds_width {
0.0
} else {
match alignment {
alignment::Horizontal::Left => 0.0,
alignment::Horizontal::Center => {
(text_bounds_width - text_min_width) / 2.0
}
alignment::Horizontal::Right => text_bounds_width - text_min_width,
}
}
}
2026-03-31 14:24:39 -06:00
/// Returns the effective horizontal alignment for the given paragraph,
/// defaulting to [`alignment::Horizontal::Right`] for RTL text and
/// [`alignment::Horizontal::Left`] for LTR text when no explicit alignment is
/// set.
fn effective_alignment(
alignment: Option<alignment::Horizontal>,
paragraph: &impl text::Paragraph,
) -> alignment::Horizontal {
alignment.unwrap_or_else(|| {
if paragraph.is_rtl(0).unwrap_or(false) {
alignment::Horizontal::Right
} else {
alignment::Horizontal::Left
}
})
}