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};
#[derive(Clone, Copy)]
pub(crate) struct TextClick {
pub(crate) id: NodeId,
time: u32,
at: Point,
count: u8,
index: usize,
}
#[derive(Clone, Copy, PartialEq)]
enum Unit {
Word,
Line,
}
#[derive(Clone, Copy)]
enum Select {
Place(usize),
Extend(usize),
Units(Unit, usize, usize),
All,
}
impl Tree {
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,
}
}
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);
}
}
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,
});
}
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);
}
}
pub(crate) fn press_text(&mut self, id: NodeId, at: Point, time: u32) {
let Some((index, upstream)) = self.text_index(id, at) else {
return;
};
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);
}
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,
}
}
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
}
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);
}
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| {
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();
});
}
}
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()))
}
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))
}
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)
}
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
}
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)
})
}
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()
}
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),
};
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();
}
}
}
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
}