crabshell-ui 0.7.0

Widgets, styles, layout, text and text editing, focus, hit testing and invalidation for Crabshell
Documentation
//! Selecting text with the pointer, in a field or a selectable text. A
//! left press places the caret, a drag selects from there to the pointer
//! wherever it goes, a second press close in time and place selects a
//! word and a third the line, a drag after them goes by whole words or
//! lines, and Shift+press extends the selection. The drag is the
//! pointer's own, so it follows the pointer out of the text and keeps it
//! from scrolling a view.

use std::ops::Range;

use cosmic_text::{Buffer, Cursor};

use crate::edit::{Edit, word_at};
use crate::geometry::{Point, Rect};
use crate::input::{DOUBLE_CLICK_DISTANCE, DOUBLE_CLICK_MS, distance};
use crate::keyboard::{Clipboard, Key, KeyEvent};
use crate::text::TextNode;
use crate::tree::{Change, NodeId, NodeKind, Tree};

/// The last left press on text, which the next may make a double or
/// triple click.
#[derive(Clone, Copy)]
pub(crate) struct TextClick {
  pub(crate) id: NodeId,
  /// When it went down.
  time: u32,
  /// Where it went down, in the window.
  at: Point,
  /// 1, 2 or 3: a single, double or triple click.
  count: u8,
  /// The byte it went down at, which a drag after a double or triple
  /// click keeps the word or line of.
  index: usize,
}

/// What a double or triple click selects.
#[derive(Clone, Copy, PartialEq)]
enum Unit {
  Word,
  /// A line between line breaks.
  Line,
}

/// What a press or a drag does to the selection.
#[derive(Clone, Copy)]
enum Select {
  /// Puts the caret here, with nothing selected.
  Place(usize),
  /// Moves the caret here, keeping the other end.
  Extend(usize),
  /// Selects the word or line at the first byte, and on to the whole one
  /// at the second, either side of it.
  Units(Unit, usize, usize),
  /// Selects the whole text.
  All,
}

impl Tree {
  /// Whether node `id` selects text under the pointer: a field, or a
  /// selectable text.
  pub(crate) fn selects(&self, id: NodeId) -> bool {
    match self.node(id).map(|node| &node.kind) {
      Some(NodeKind::Input(_)) => true,
      Some(NodeKind::Text(text)) => text.selectable,
      _ => false,
    }
  }

  /// A left press on `on`, or on nothing: a selectable text holding the
  /// focus elsewhere lets go of it, and so of its selection.
  pub(crate) fn press_away(&mut self, on: Option<NodeId>) {
    let focused = self.keyboard.focused.filter(|&id| Some(id) != on);
    if focused.is_some_and(|id| {
      matches!(
        self.node(id).map(|node| &node.kind),
        Some(NodeKind::Text(_))
      )
    }) {
      self.focus(None);
    }
  }

  /// Drops the selection of text `id`, as it loses the focus.
  pub(crate) fn drop_selection(&mut self, id: NodeId) {
    self.update(id, |node| match &mut node.kind {
      NodeKind::Text(text) => match text.anchor.take() {
        Some(_) => Change::Paint,
        None => Change::None,
      },
      _ => Change::None,
    });
  }

  /// Makes text `id` selectable or not. Turned off, it drops the focus,
  /// and so its selection: only the focused text holds one.
  pub(crate) fn set_selectable(&mut self, id: NodeId, selectable: bool) {
    if let Some(NodeKind::Text(text)) = self.node_mut(id).map(|node| &mut node.kind) {
      text.selectable = selectable;
    }
    if !selectable && self.keyboard.focused == Some(id) && self.keyboard.link.is_none() {
      self.focus(None);
    }
  }

  /// A left press at `at` on `id`, which selects text, at `time`: it
  /// takes the focus, then places the caret, or extends the selection
  /// with Shift held, or selects the word on a double click and the line
  /// on a triple one.
  pub(crate) fn press_text(&mut self, id: NodeId, at: Point, time: u32) {
    let Some((index, upstream)) = self.text_index(id, at) else {
      return;
    };
    // Timed from press to press, each to the one before: the release
    // comes after a drag. A fourth starts again.
    let count = match self.pointer.text_click {
      Some(last)
        if last.id == id
          && time.wrapping_sub(last.time) <= DOUBLE_CLICK_MS
          && distance(last.at, at) <= DOUBLE_CLICK_DISTANCE =>
      {
        last.count % 3 + 1
      }
      _ => 1,
    };
    self.pointer.text_click = Some(TextClick {
      id,
      time,
      at,
      count,
      index,
    });
    let how = match count {
      2 => Select::Units(Unit::Word, index, index),
      3 => Select::Units(Unit::Line, index, index),
      _ if self.keyboard.modifiers.shift && self.keyboard.focused == Some(id) => {
        Select::Extend(index)
      }
      _ => Select::Place(index),
    };
    self.focus(Some(id));
    self.select(id, how, upstream);
  }

  /// What node `id` has selected, which becomes the primary selection: a
  /// field's selection, never a password's, or a selectable text's.
  pub(crate) fn selected_text(&self, id: NodeId) -> Option<String> {
    match &self.node(id)?.kind {
      NodeKind::Input(input) if !input.password => {
        Some(input.edit.text.get(input.edit.selection()?)?.to_owned())
      }
      NodeKind::Text(text) => Some(text.content.get(text_selection(text)?)?.to_owned()),
      _ => None,
    }
  }

  /// A middle press at `at` on `id`: a field takes the focus and the
  /// caret goes there, with nothing selected, for the primary selection
  /// to paste at. Returns whether `id` is a field.
  pub(crate) fn press_middle(&mut self, id: NodeId, at: Point) -> bool {
    if !matches!(
      self.node(id).map(|node| &node.kind),
      Some(NodeKind::Input(_))
    ) {
      return false;
    }
    let Some((index, upstream)) = self.text_index(id, at) else {
      return false;
    };
    self.focus(Some(id));
    self.select(id, Select::Place(index), upstream);
    true
  }

  /// The left button held on `id` moved to `at`: the selection runs to
  /// the pointer, by whole words or lines after a double or triple click.
  pub(crate) fn drag_text(&mut self, id: NodeId, at: Point) {
    let Some((index, upstream)) = self.text_index(id, at) else {
      return;
    };
    let how = match self.pointer.text_click {
      Some(click) if click.id == id && click.count == 2 => {
        Select::Units(Unit::Word, click.index, index)
      }
      Some(click) if click.id == id && click.count == 3 => {
        Select::Units(Unit::Line, click.index, index)
      }
      _ => Select::Extend(index),
    };
    self.select(id, how, upstream);
  }

  /// The text position nearest `at`, in window coordinates, in node `id`,
  /// and whether it is the end of a field's wrapped line rather than the
  /// start of the next.
  fn text_index(&self, id: NodeId, at: Point) -> Option<(usize, bool)> {
    let point = self.local_point(id, at)?;
    match &self.node(id)?.kind {
      NodeKind::Input(input) => Some(input.hit(point)),
      NodeKind::Text(text) if text.selectable => Some((text_hit(text, point), false)),
      _ => None,
    }
  }

  fn select(&mut self, id: NodeId, how: Select, upstream: bool) {
    if let Some(NodeKind::Text(_)) = self.node(id).map(|node| &node.kind) {
      self.update(id, |node| match &mut node.kind {
        NodeKind::Text(TextNode {
          content,
          cursor,
          anchor,
          ..
        }) => {
          apply(content, cursor, anchor, how);
          Change::Paint
        }
        _ => Change::None,
      });
      return;
    }
    self.update_input(id, |input| {
      // A password's words would show where its spaces are.
      let how = match how {
        Select::Units(..) if input.password => Select::All,
        how => how,
      };
      let Edit {
        text,
        cursor,
        anchor,
        ..
      } = &mut input.edit;
      apply(text, cursor, anchor, how);
      input.upstream = upstream.then_some(*cursor);
      input.goal = None;
      input.refresh();
    });
  }
}

/// What a selectable text copies on Ctrl+C: its selection, if any.
pub(crate) fn copy_key(text: &TextNode, event: &KeyEvent) -> Option<Clipboard> {
  let ctrl_c =
    event.modifiers.ctrl && !event.modifiers.alt && matches!(event.key, Key::Character('c' | 'C'));
  let range = ctrl_c.then(|| text_selection(text)).flatten()?;
  Some(Clipboard::Copy(text.content.get(range)?.to_owned()))
}

/// The bytes a selectable text has selected, if any.
pub(crate) fn text_selection(text: &TextNode) -> Option<Range<usize>> {
  let anchor = text
    .anchor
    .filter(|&anchor| text.selectable && anchor != text.cursor)?;
  Some(anchor.min(text.cursor)..anchor.max(text.cursor))
}

/// The cosmic-text cursor at byte `at` of the text `buffer` holds, which
/// it splits into lines at each line break.
pub(crate) fn cursor_at(buffer: &Buffer, at: usize) -> Cursor {
  let mut start = 0;
  let last = buffer.lines.len().saturating_sub(1);
  for (index, line) in buffer.lines.iter().enumerate() {
    let length = line.text().len();
    let next = start + length + line.ending().as_str().len();
    if at < next || index == last {
      return Cursor::new(index, at.saturating_sub(start).min(length));
    }
    start = next;
  }
  Cursor::new(0, 0)
}

/// The byte of the text `buffer` holds that `cursor` points at.
pub(crate) fn index_of(buffer: &Buffer, cursor: Cursor) -> usize {
  let before: usize = buffer.lines[..cursor.line.min(buffer.lines.len())]
    .iter()
    .map(|line| line.text().len() + line.ending().as_str().len())
    .sum();
  before + cursor.index
}

/// The byte of `text` nearest `point`, in window coordinates. On a line
/// whose leading blanks were dropped, cosmic-text is asked where its own
/// layout has the glyph drawn there, and nothing before the first glyph
/// shown is hit.
pub(crate) fn text_hit(text: &TextNode, point: Point) -> usize {
  let (x, y) = (point.x - text.origin.x, point.y - text.origin.y);
  let run = text
    .runs()
    .find(|run| y >= run.line_top && y < run.line_top + run.line_height);
  let (line, shift, first) = run.map_or((0, 0.0, 0), |run| (run.line_i, run.shift, run.first));
  text.buffer.hit(x + shift, y).map_or(0, |mut cursor| {
    if cursor.line == line {
      cursor.index = cursor.index.max(first);
    }
    index_of(&text.buffer, cursor)
  })
}

/// Where bytes `range` of `text` show, in window coordinates: a rectangle
/// for each line they cover, or more where right-to-left and
/// left-to-right text mix. An empty line whose break is selected shows
/// half an em, so the selection reads as one across it.
pub(crate) fn highlights(text: &TextNode, range: Range<usize>) -> Vec<Rect> {
  let (start, end) = (
    cursor_at(&text.buffer, range.start),
    cursor_at(&text.buffer, range.end),
  );
  let origin = text.origin;
  let half_em = text.buffer.metrics().font_size / 2.0;
  let width = text.layout_width();
  text
    .runs()
    .filter(|run| (start.line..=end.line).contains(&run.line_i))
    .flat_map(|run| {
      let empty = (run.glyphs.is_empty() && run.line_i < end.line).then(|| {
        let x = text.empty_line_place(run.rtl) * (width - half_em).max(0.0);
        (x, half_em)
      });
      run
        .layout()
        .highlight(start, end)
        .chain(empty)
        .map(move |(x, width)| {
          Rect::new(
            origin.x + x,
            origin.y + run.line_top,
            width,
            run.line_height,
          )
        })
    })
    .collect()
}

/// Changes a caret and the other end of the selection in `text` as `how`
/// says.
fn apply(text: &str, cursor: &mut usize, anchor: &mut Option<usize>, how: Select) {
  match how {
    Select::Place(at) => {
      *cursor = at;
      *anchor = Some(at);
    }
    Select::Extend(at) => {
      anchor.get_or_insert(*cursor);
      *cursor = at;
    }
    Select::Units(unit, from, to) => {
      let unit_at = |at: usize| match unit {
        Unit::Word => word_at(text, at),
        Unit::Line => line_at(text, at),
      };
      // The text may have changed under a held press.
      let first = unit_at(if text.is_char_boundary(from) {
        from
      } else {
        to
      });
      let last = unit_at(to);
      if last.start < first.start {
        *anchor = Some(first.end);
        *cursor = last.start;
      } else {
        *anchor = Some(first.start);
        *cursor = last.end.max(first.end);
      }
    }
    Select::All => {
      *anchor = Some(0);
      *cursor = text.len();
    }
  }
}

/// The line around byte `at` of `text`, between line breaks and without
/// them: what a triple click selects. cosmic-text breaks lines at `\n`,
/// `\r`, `\r\n` and `\n\r`, so each `\r` and `\n` ends one.
fn line_at(text: &str, at: usize) -> Range<usize> {
  const BREAKS: [char; 2] = ['\n', '\r'];
  let at = at.min(text.len());
  let start = text[..at].rfind(BREAKS).map_or(0, |found| found + 1);
  let end = text[at..]
    .find(BREAKS)
    .map_or(text.len(), |found| at + found);
  start..end
}