//! Text widgets display information through writing.
//!
//! Keyboard shortcuts (applies to both [`Text`] and [`Rich`]):
//!
//! |MacOS|Linux/Windows|Effect|
//! |-|-|-|
//! |`Cmd + A`|`Ctrl + A`|Selects all text in the currently focused paragraph|
//! |`Cmd + C`|`Ctrl + C`|Copies the selected text to clipboard|
//! |`Shift + Left Arrow`|`Shift + Left Arrow`|Moves the selection to the left by one character|
//! |`Shift + Right Arrow`|`Shift + Right Arrow`|Moves the selection to the right by one character|
//! |`Shift + Opt + Left Arrow`|`Shift + Ctrl + Left Arrow`|Extends the selection to the previous start of a word|
//! |`Shift + Opt + Right Arrow`|`Shift + Ctrl + Right Arrow`|Extends the selection to the next end of a word|
//! |`Shift + Home`
`Shift + Cmd + Left Arrow`
`Shift + Opt + Up Arrow`|`Shift + Home`
`Shift + Ctrl + Up Arrow`|Selects to the beginning of the line|
//! |`Shift + End`
`Shift + Cmd + Right Arrow`
`Shift + Opt + Down Arrow`|`Shift + End`
`Shift + Ctrl + Down Arrow`|Selects to the end of the line|
//! |`Shift + Up Arrow`|`Shift + Up Arrow`|Moves the selection up by one line if possible, or to the start of the current line otherwise|
//! |`Shift + Down Arrow`|`Shift + Down Arrow`|Moves the selection down by one line if possible, or to the end of the current line otherwise|
//! |`Shift + Opt + Home`
`Shift + Cmd + Up Arrow`|`Shift + Ctrl + Home`|Selects to the beginning of the paragraph|
//! |`Shift + Opt + End`
`Shift + Cmd + Down Arrow`|`Shift + Ctrl + End`|Selects to the end of the paragraph|
mod rich;
use iced_widget::graphics::text::Paragraph;
pub use rich::Rich;
use text::{Alignment, LineHeight, Shaping, Wrapping};
pub use text::{Fragment, Highlighter, IntoFragment, Span};
use crate::core::alignment;
use crate::core::clipboard;
use crate::core::keyboard::{self, key};
use crate::core::layout;
use crate::core::mouse;
use crate::core::mouse::click;
use crate::core::renderer;
use crate::core::text;
use crate::core::text::paragraph::Paragraph as _;
use crate::core::touch;
use crate::core::widget::Operation;
use crate::core::widget::text::Format;
use crate::core::widget::tree::{self, Tree};
use crate::core::{
self, Color, Element, Event, Font, Layout, Length, Pixels, Point, Size,
Theme, Widget,
};
use crate::selection::{Selection, SelectionEnd};
/// A bunch of text.
///
/// # Example
/// ```no_run,ignore
/// use iced_selection::text;
///
/// enum Message {
/// // ...
/// }
///
/// fn view(state: &State) -> Element<'_, Message> {
/// text("Hello, this is iced!")
/// .size(20)
/// .into()
/// }
/// ```
pub struct Text<
'a,
Theme = iced_widget::Theme,
Renderer = iced_widget::Renderer,
> where
Theme: Catalog,
Renderer: text::Renderer,
{
fragment: Fragment<'a>,
format: Format,
class: Theme::Class<'a>,
}
impl<'a, Theme, Renderer> Text<'a, Theme, Renderer>
where
Theme: Catalog,
Renderer: text::Renderer,
{
/// Create a new fragment of [`Text`] with the given contents.
pub fn new(fragment: impl IntoFragment<'a>) -> Self {
Self {
fragment: fragment.into_fragment(),
format: Format::default(),
class: Theme::default(),
}
}
/// Sets the size of the [`Text`].
pub fn size(mut self, size: impl Into) -> Self {
self.format.size = Some(size.into());
self
}
/// Sets the [`LineHeight`] of the [`Text`].
pub fn line_height(mut self, line_height: impl Into) -> Self {
self.format.line_height = line_height.into();
self
}
/// Sets the [`Font`] of the [`Text`].
pub fn font(mut self, font: impl Into) -> Self {
self.format.font = Some(font.into());
self
}
/// Sets the width of the [`Text`] boundaries.
pub fn width(mut self, width: impl Into) -> Self {
self.format.width = width.into();
self
}
/// Sets the height of the [`Text`] boundaries.
pub fn height(mut self, height: impl Into) -> Self {
self.format.height = height.into();
self
}
/// Centers the [`Text`], both horizontally and vertically.
pub fn center(mut self) -> Self {
self.format.align_x = Alignment::Center;
self.format.align_y = alignment::Vertical::Center;
self
}
/// Sets the [`alignment::Horizontal`] of the [`Text`].
pub fn align_x(mut self, alignment: impl Into) -> Self {
self.format.align_x = alignment.into();
self
}
/// Sets the [`alignment::Vertical`] of the [`Text`].
pub fn align_y(
mut self,
alignment: impl Into,
) -> Self {
self.format.align_y = alignment.into();
self
}
/// Sets the [`Shaping`] strategy of the [`Text`].
pub fn shaping(mut self, shaping: Shaping) -> Self {
self.format.shaping = shaping;
self
}
/// Sets the [`Wrapping`] strategy of the [`Text`].
pub fn wrapping(mut self, wrapping: Wrapping) -> Self {
self.format.wrapping = wrapping;
self
}
/// Sets the style of the [`Text`].
#[must_use]
pub fn style(mut self, style: impl Fn(&Theme) -> Style + 'a) -> Self
where
Theme::Class<'a>: From>,
{
self.class = (Box::new(style) as StyleFn<'a, Theme>).into();
self
}
/// Sets the style class of the [`Text`].
#[must_use]
pub fn class(mut self, class: impl Into>) -> Self {
self.class = class.into();
self
}
}
/// The internal state of a [`Text`] widget.
#[derive(Debug, Default, Clone)]
pub struct State {
paragraph: Paragraph,
content: String,
is_hovered: bool,
selection: Selection,
dragging: Option,
last_click: Option,
keyboard_modifiers: keyboard::Modifiers,
}
/// The type of dragging selection.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[allow(missing_docs)]
pub enum Dragging {
Grapheme,
Word,
Line,
}
impl State {
fn grapheme_line_and_index(&self, point: Point) -> Option<(usize, usize)> {
let cursor = self.paragraph.buffer().hit(point.x, point.y)?;
let value = self.paragraph.buffer().lines[cursor.line].text();
Some((
cursor.line,
unicode_segmentation::UnicodeSegmentation::graphemes(
&value[..cursor.index.min(value.len())],
true,
)
.count(),
))
}
fn selection_end_points(&self) -> (usize, Point, Point) {
let Selection { start, end, .. } = self.selection;
let (start_row, start_position) = self
.grapheme_position(start.line, start.index)
.unwrap_or_default();
let (end_row, end_position) = self
.grapheme_position(end.line, end.index)
.unwrap_or_default();
(
end_row.saturating_sub(start_row) + 1,
start_position,
end_position,
)
}
fn grapheme_position(
&self,
line: usize,
index: usize,
) -> Option<(usize, Point)> {
use unicode_segmentation::UnicodeSegmentation;
let mut first_run_index = None;
let mut last_run_index = None;
let mut last_start = None;
let mut last_grapheme_count = 0;
let mut last_run_graphemes = 0;
let mut real_index = 0;
let mut graphemes_seen = 0;
let mut glyphs = self
.paragraph
.buffer()
.layout_runs()
.enumerate()
.filter(|(_, run)| run.line_i == line)
.flat_map(|(run_idx, run)| {
let line_top = run.line_top;
if first_run_index.is_none() {
first_run_index = Some(run_idx);
}
run.glyphs.iter().map(move |glyph| {
let mut glyph = glyph.clone();
glyph.y += line_top;
(run_idx, glyph, run.text)
})
});
let (_, glyph, _) = glyphs
.find(|(run_idx, glyph, text)| {
if Some(glyph.start) != last_start {
last_grapheme_count =
text[glyph.start..glyph.end].graphemes(false).count();
last_start = Some(glyph.start);
graphemes_seen += last_grapheme_count;
last_run_graphemes += last_grapheme_count;
real_index += last_grapheme_count;
if Some(*run_idx) != last_run_index
&& graphemes_seen < index
{
real_index = last_grapheme_count;
last_run_graphemes = last_grapheme_count;
}
} else if Some(*run_idx) != last_run_index
&& graphemes_seen < index
{
real_index = 0;
last_run_graphemes = 0;
}
last_run_index = Some(*run_idx);
graphemes_seen >= index
})
.or_else(|| glyphs.last())?;
real_index -= graphemes_seen.saturating_sub(index);
real_index =
real_index.saturating_sub(last_run_index? - first_run_index?);
last_run_graphemes = last_run_graphemes
.saturating_sub(last_run_index? - first_run_index?);
let advance = if last_run_index? - first_run_index? <= 1 {
if real_index == 0 {
0.0
} else {
glyph.w
* (1.0
- last_run_graphemes.saturating_sub(real_index) as f32
/ last_grapheme_count.max(1) as f32)
- glyph.w * (last_run_index? - first_run_index?) as f32
}
} else {
-(glyph.w
* (1.0
+ last_run_graphemes.saturating_sub(real_index) as f32
/ last_grapheme_count.max(1) as f32))
};
Some((
last_run_index?,
Point::new(
glyph.x + glyph.x_offset * glyph.font_size + advance,
glyph.y - glyph.y_offset * glyph.font_size,
),
))
}
fn update(&mut self, text: text::Text<&str, Font>) {
if self.content != text.content {
text.content.clone_into(&mut self.content);
self.paragraph = Paragraph::with_text(text);
return;
}
match self.paragraph.compare(text.with_content(())) {
text::Difference::None => {}
text::Difference::Bounds => self.paragraph.resize(text.bounds),
text::Difference::Shape => {
self.paragraph = Paragraph::with_text(text);
}
}
}
}
impl Widget
for Text<'_, Theme, Renderer>
where
Theme: Catalog,
Renderer: text::Renderer,
{
fn tag(&self) -> tree::Tag {
tree::Tag::of::()
}
fn state(&self) -> tree::State {
tree::State::new(State::default())
}
fn size(&self) -> Size {
Size {
width: self.format.width,
height: self.format.height,
}
}
fn layout(
&mut self,
tree: &mut Tree,
renderer: &Renderer,
limits: &layout::Limits,
) -> layout::Node {
layout(
tree.state.downcast_mut::(),
renderer,
limits,
&self.fragment,
self.format,
)
}
fn update(
&mut self,
tree: &mut Tree,
event: &Event,
layout: Layout<'_>,
cursor: mouse::Cursor,
_renderer: &Renderer,
clipboard: &mut dyn core::Clipboard,
shell: &mut core::Shell<'_, Message>,
viewport: &core::Rectangle,
) {
let state = tree.state.downcast_mut::();
let bounds = layout.bounds();
let click_position = cursor.position_in(bounds);
if viewport.intersection(&bounds).is_none()
&& state.selection == Selection::default()
&& state.dragging.is_none()
{
return;
}
let was_hovered = state.is_hovered;
let selection_before = state.selection;
state.is_hovered = click_position.is_some();
match event {
Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left))
| Event::Touch(touch::Event::FingerPressed { .. }) => {
if let Some(position) = click_position {
let click = mouse::Click::new(
position,
mouse::Button::Left,
state.last_click,
);
let (line, index) = state
.grapheme_line_and_index(position)
.unwrap_or((0, 0));
match click.kind() {
click::Kind::Single => {
let new_end = SelectionEnd { line, index };
if state.keyboard_modifiers.shift() {
state.selection.change_selection(new_end);
} else {
state.selection.select_range(new_end, new_end);
}
state.dragging = Some(Dragging::Grapheme);
}
click::Kind::Double => {
state.selection.select_word(
line,
index,
&state.paragraph,
);
state.dragging = Some(Dragging::Word);
}
click::Kind::Triple => {
state.selection.select_line(line, &state.paragraph);
state.dragging = Some(Dragging::Line);
}
}
state.last_click = Some(click);
shell.capture_event();
} else {
state.selection = Selection::default();
}
}
Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Left))
| Event::Touch(touch::Event::FingerLifted { .. })
| Event::Touch(touch::Event::FingerLost { .. }) => {
state.dragging = None;
}
Event::Mouse(mouse::Event::CursorMoved { .. })
| Event::Touch(touch::Event::FingerMoved { .. }) => {
if let Some(position) = click_position
&& let Some(dragging) = state.dragging
{
let (line, index) = state
.grapheme_line_and_index(position)
.unwrap_or((0, 0));
match dragging {
Dragging::Grapheme => {
let new_end = SelectionEnd { line, index };
state.selection.change_selection(new_end);
}
Dragging::Word => {}
Dragging::Line => {
state.selection.change_selection_by_line(
line,
&state.paragraph,
);
}
};
}
}
Event::Keyboard(keyboard::Event::KeyPressed { key, .. }) => {
match key.as_ref() {
keyboard::Key::Character("c")
if state.keyboard_modifiers.command()
&& !state.selection.is_empty() =>
{
clipboard.write(
clipboard::Kind::Standard,
state.selection.text(&state.paragraph),
);
shell.capture_event();
}
keyboard::Key::Character("a")
if state.keyboard_modifiers.command()
&& state.selection != Selection::default() =>
{
state.selection.select_all(&state.paragraph);
shell.capture_event();
}
keyboard::Key::Named(key::Named::Home)
if state.keyboard_modifiers.shift()
&& state.selection != Selection::default() =>
{
if state.keyboard_modifiers.jump() {
state.selection.select_beginning();
} else {
state.selection.select_line_beginning();
}
shell.capture_event();
}
keyboard::Key::Named(key::Named::End)
if state.keyboard_modifiers.shift()
&& state.selection != Selection::default() =>
{
if state.keyboard_modifiers.jump() {
state.selection.select_end(&state.paragraph);
} else {
state.selection.select_line_end(&state.paragraph);
}
shell.capture_event();
}
keyboard::Key::Named(key::Named::ArrowLeft)
if state.keyboard_modifiers.shift()
&& state.selection != Selection::default() =>
{
if state.keyboard_modifiers.macos_command() {
state.selection.select_line_beginning();
} else if state.keyboard_modifiers.jump() {
state
.selection
.select_left_by_words(&state.paragraph);
} else {
state.selection.select_left(&state.paragraph);
}
shell.capture_event();
}
keyboard::Key::Named(key::Named::ArrowRight)
if state.keyboard_modifiers.shift()
&& state.selection != Selection::default() =>
{
if state.keyboard_modifiers.macos_command() {
state.selection.select_line_end(&state.paragraph);
} else if state.keyboard_modifiers.jump() {
state
.selection
.select_right_by_words(&state.paragraph);
} else {
state.selection.select_right(&state.paragraph);
}
shell.capture_event();
}
keyboard::Key::Named(key::Named::ArrowUp)
if state.keyboard_modifiers.shift()
&& state.selection != Selection::default() =>
{
if state.keyboard_modifiers.macos_command() {
state.selection.select_beginning();
} else if state.keyboard_modifiers.jump() {
state.selection.select_line_beginning();
} else {
state.selection.select_up(&state.paragraph);
}
shell.capture_event();
}
keyboard::Key::Named(key::Named::ArrowDown)
if state.keyboard_modifiers.shift()
&& state.selection != Selection::default() =>
{
if state.keyboard_modifiers.macos_command() {
state.selection.select_end(&state.paragraph);
} else if state.keyboard_modifiers.jump() {
state.selection.select_line_end(&state.paragraph);
} else {
state.selection.select_down(&state.paragraph);
}
shell.capture_event();
}
keyboard::Key::Named(key::Named::Escape) => {
state.dragging = None;
state.selection = Selection::default();
state.keyboard_modifiers =
keyboard::Modifiers::default();
if state.selection != selection_before {
shell.capture_event();
}
}
_ => {}
}
}
Event::Keyboard(keyboard::Event::ModifiersChanged(modifiers)) => {
state.keyboard_modifiers = *modifiers;
}
_ => {}
}
if state.is_hovered != was_hovered
|| state.selection != selection_before
{
shell.request_redraw();
}
}
fn draw(
&self,
tree: &Tree,
renderer: &mut Renderer,
theme: &Theme,
defaults: &renderer::Style,
layout: Layout<'_>,
_cursor_position: mouse::Cursor,
viewport: &core::Rectangle,
) {
if !layout.bounds().intersects(viewport) {
return;
}
let state = tree.state.downcast_ref::();
let style = theme.style(&self.class);
if !state.selection.is_empty() {
let bounds = layout.bounds();
let (rows, mut start, mut end) = state.selection_end_points();
start = start + core::Vector::new(bounds.x, bounds.y);
end = end + core::Vector::new(bounds.x, bounds.y);
let line_height = self
.format
.line_height
.to_absolute(
self.format.size.unwrap_or_else(|| renderer.default_size()),
)
.0;
let baseline_y = bounds.y
+ (((start.y - bounds.y) * 10.0).ceil() / 10.0 / line_height)
.floor()
* line_height;
for row in 0..rows {
let (x, width) = if row == 0 {
(
start.x,
if rows == 1 {
end.x.min(bounds.x + bounds.width) - start.x
} else {
bounds.x + bounds.width - start.x
},
)
} else if row == rows - 1 {
(bounds.x, end.x - bounds.x)
} else {
(bounds.x, bounds.width)
};
let y = baseline_y + row as f32 * line_height;
renderer.fill_quad(
renderer::Quad {
bounds: core::Rectangle {
x,
y,
width,
height: line_height,
},
snap: true,
..Default::default()
},
style.selection,
);
}
}
draw(
renderer,
defaults,
layout.bounds(),
&state.paragraph,
style,
viewport,
);
}
fn operate(
&mut self,
_state: &mut Tree,
layout: Layout<'_>,
_renderer: &Renderer,
operation: &mut dyn Operation,
) {
operation.text(None, layout.bounds(), &self.fragment);
}
fn mouse_interaction(
&self,
tree: &Tree,
_layout: Layout<'_>,
_cursor: mouse::Cursor,
_viewport: &core::Rectangle,
_renderer: &Renderer,
) -> mouse::Interaction {
let state = tree.state.downcast_ref::();
if state.is_hovered {
mouse::Interaction::Text
} else {
mouse::Interaction::default()
}
}
}
/// Produces the [`layout::Node`] of a [`Text`] widget.
///
/// [`layout::Node`]: https://docs.iced.rs/iced_core/layout/struct.Node.html
pub fn layout(
state: &mut State,
renderer: &Renderer,
limits: &layout::Limits,
content: &str,
format: Format,
) -> layout::Node
where
Renderer: text::Renderer,
{
layout::sized(limits, format.width, format.height, |limits| {
let bounds = limits.max();
let size = format.size.unwrap_or_else(|| renderer.default_size());
let font = format.font.unwrap_or_else(|| renderer.default_font());
state.update(text::Text {
content,
bounds,
size,
line_height: format.line_height,
font,
align_x: format.align_x,
align_y: format.align_y,
shaping: format.shaping,
wrapping: format.wrapping,
});
state.paragraph.min_bounds()
})
}
/// Draws text using the same logic as the [`Text`] widget.
pub fn draw(
renderer: &mut Renderer,
style: &renderer::Style,
bounds: core::Rectangle,
paragraph: &Paragraph,
appearance: Style,
viewport: &core::Rectangle,
) where
Renderer: text::Renderer,
{
let anchor = bounds.anchor(
paragraph.min_bounds(),
paragraph.align_x(),
paragraph.align_y(),
);
renderer.fill_paragraph(
paragraph,
anchor,
appearance.color.unwrap_or(style.text_color),
*viewport,
);
}
impl<'a, Message, Theme, Renderer> From>
for Element<'a, Message, Theme, Renderer>
where
Theme: Catalog + 'a,
Renderer: text::Renderer + 'a,
{
fn from(
text: Text<'a, Theme, Renderer>,
) -> Element<'a, Message, Theme, Renderer> {
Element::new(text)
}
}
impl<'a, Theme, Renderer> From<&'a str> for Text<'a, Theme, Renderer>
where
Theme: Catalog + 'a,
Renderer: text::Renderer + 'a,
{
fn from(content: &'a str) -> Self {
Self::new(content)
}
}
/// The appearance of some text.
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub struct Style {
/// The [`Color`] of the text.
///
/// The default, `None`, means using the inherited color.
pub color: Option,
/// The [`Color`] of text selections.
pub selection: Color,
}
/// The theme catalog of a [`Text`].
pub trait Catalog: Sized {
/// The item class of this [`Catalog`].
type Class<'a>;
/// The default class produced by this [`Catalog`].
fn default<'a>() -> Self::Class<'a>;
/// The [`Style`] of a class with the given status.
fn style(&self, item: &Self::Class<'_>) -> Style;
}
/// A styling function for a [`Text`].
///
/// This is just a boxed closure: `Fn(&Theme, Status) -> Style`.
pub type StyleFn<'a, Theme> = Box Style + 'a>;
impl Catalog for Theme {
type Class<'a> = StyleFn<'a, Self>;
fn default<'a>() -> Self::Class<'a> {
Box::new(default)
}
fn style(&self, class: &Self::Class<'_>) -> Style {
class(self)
}
}
/// The default text styling; color is inherited.
pub fn default(theme: &Theme) -> Style {
Style {
color: None,
selection: theme.extended_palette().primary.weak.color,
}
}