cursive/src/views/text_area.rs

485 lines
15 KiB
Rust
Raw Normal View History

2016-10-02 22:22:29 +00:00
2016-08-02 07:32:16 +00:00
2016-08-03 04:48:12 +00:00
use {Printer, With, XY};
2016-08-02 07:32:16 +00:00
use direction::Direction;
use event::{Event, EventResult, Key};
2016-10-02 22:22:29 +00:00
use odds::vec::VecExt;
use theme::{ColorStyle, Effect};
use unicode_segmentation::UnicodeSegmentation;
use unicode_width::UnicodeWidthStr;
use utils::{LinesIterator, Row, prefix};
2016-10-02 22:22:29 +00:00
use vec::Vec2;
2016-08-02 07:32:16 +00:00
use view::{ScrollBase, SizeCache, View};
/// Multi-lines text editor.
///
2017-04-21 22:03:13 +00:00
/// A `TextArea` will attempt to grow vertically and horizontally
/// dependent on the content. Wrap it in a `BoxView` to
/// constrain its size.
2016-08-02 07:32:16 +00:00
pub struct TextArea {
// TODO: use a smarter data structure (rope?)
content: String,
/// Byte offsets within `content` representing text rows
rows: Vec<Row>,
/// When `false`, we don't take any input.
enabled: bool,
/// Base for scrolling features
scrollbase: ScrollBase,
/// Cache to avoid re-computing layout on no-op events
last_size: Option<XY<SizeCache>>,
/// Byte offset of the currently selected grapheme.
cursor: usize,
}
fn make_rows(text: &str, width: usize) -> Vec<Row> {
LinesIterator::new(text, width).show_spaces().collect()
2016-08-02 07:32:16 +00:00
}
2016-08-03 06:26:59 +00:00
new_default!(TextArea);
2016-08-02 07:32:16 +00:00
impl TextArea {
/// Creates a new, empty TextArea.
pub fn new() -> Self {
TextArea {
content: String::new(),
rows: Vec::new(),
2016-08-02 07:32:16 +00:00
enabled: true,
scrollbase: ScrollBase::new().right_padding(0),
2016-08-02 07:32:16 +00:00
last_size: None,
cursor: 0,
}
}
/// Retrieves the content of the view.
pub fn get_content(&self) -> &str {
&self.content
}
2016-08-03 04:48:12 +00:00
fn invalidate(&mut self) {
self.last_size = None;
}
/// Sets the content of the view.
pub fn set_content<S: Into<String>>(&mut self, content: S) {
self.content = content.into();
if let Some(size) = self.last_size.map(|s| s.map(|s| s.value)) {
self.compute_rows(size);
}
}
/// Sets the content of the view.
///
/// Chainable variant.
pub fn content<S: Into<String>>(self, content: S) -> Self {
self.with(|s| s.set_content(content))
}
2016-08-02 07:32:16 +00:00
/// Finds the row containing the grapheme at the given offset
fn row_at(&self, offset: usize) -> usize {
debug!("Offset: {}", offset);
2016-08-02 07:32:16 +00:00
self.rows
.iter()
.enumerate()
.take_while(|&(_, row)| row.start <= offset)
.map(|(i, _)| i)
.last()
.unwrap()
}
fn col_at(&self, offset: usize) -> usize {
let row_id = self.row_at(offset);
let row = self.rows[row_id];
// Number of cells to the left of the cursor
self.content[row.start..offset].width()
}
2016-08-02 07:32:16 +00:00
/// Finds the row containing the cursor
fn selected_row(&self) -> usize {
self.row_at(self.cursor)
}
fn page_up(&mut self) {
for _ in 0..5 {
self.move_up();
}
}
fn page_down(&mut self) {
for _ in 0..5 {
self.move_down();
}
}
fn move_up(&mut self) {
let row_id = self.selected_row();
if row_id == 0 {
return;
}
// Number of cells to the left of the cursor
let x = self.col_at(self.cursor);
2016-08-02 07:32:16 +00:00
let prev_row = self.rows[row_id - 1];
let prev_text = &self.content[prev_row.start..prev_row.end];
let offset = prefix(prev_text.graphemes(true), x, "").length;
2016-08-02 07:32:16 +00:00
self.cursor = prev_row.start + offset;
}
fn move_down(&mut self) {
let row_id = self.selected_row();
if row_id + 1 == self.rows.len() {
return;
}
let x = self.col_at(self.cursor);
2016-08-02 07:32:16 +00:00
let next_row = self.rows[row_id + 1];
let next_text = &self.content[next_row.start..next_row.end];
let offset = prefix(next_text.graphemes(true), x, "").length;
2016-08-02 07:32:16 +00:00
self.cursor = next_row.start + offset;
}
/// Moves the cursor to the left.
///
/// Wraps the previous line if required.
fn move_left(&mut self) {
let len = {
// We don't want to utf8-parse the entire content.
// So only consider the last row.
2016-08-02 07:32:16 +00:00
let mut row = self.selected_row();
if self.rows[row].start == self.cursor {
row = row.saturating_sub(1);
2016-08-02 07:32:16 +00:00
}
let text = &self.content[self.rows[row].start..self.cursor];
text.graphemes(true).last().unwrap().len()
2016-08-02 07:32:16 +00:00
};
self.cursor -= len;
}
/// Moves the cursor to the right.
///
/// Jumps to the next line is required.
fn move_right(&mut self) {
let len = self.content[self.cursor..]
.graphemes(true)
.next()
.unwrap()
.len();
self.cursor += len;
}
fn is_cache_valid(&self, size: Vec2) -> bool {
2016-08-03 04:48:12 +00:00
match self.last_size {
None => false,
Some(ref last) => last.x.accept(size.x) && last.y.accept(size.y),
}
2016-08-02 07:32:16 +00:00
}
// If we are editing the text, we add a fake "space" character for the cursor to indicate
// where the next character will appear.
// If the current line is full, adding a character will overflow into the next line. To
// show that, we need to add a fake "ghost" row, just for the cursor.
fn fix_ghost_row(&mut self) {
if self.rows.is_empty() ||
self.rows.last().unwrap().end != self.content.len()
{
// Add a fake, empty row at the end.
self.rows.push(Row {
start: self.content.len(),
end: self.content.len(),
width: 0,
});
}
}
2016-08-02 07:32:16 +00:00
fn compute_rows(&mut self, size: Vec2) {
2016-08-03 04:48:12 +00:00
if self.is_cache_valid(size) {
return;
}
debug!("Computing! Oh yeah!");
2016-08-03 04:48:12 +00:00
2016-08-02 07:32:16 +00:00
let mut available = size.x;
self.rows = make_rows(&self.content, available);
self.fix_ghost_row();
2016-08-02 07:32:16 +00:00
if self.rows.len() > size.y {
available = available.saturating_sub(1);
// Apparently we'll need a scrollbar. Doh :(
self.rows = make_rows(&self.content, available);
self.fix_ghost_row();
2016-08-02 07:32:16 +00:00
}
if !self.rows.is_empty() {
self.last_size = Some(SizeCache::build(size, size));
}
self.scrollbase.set_heights(size.y, self.rows.len());
2016-08-02 07:32:16 +00:00
}
fn backspace(&mut self) {
if self.cursor != 0 {
self.move_left();
self.delete();
}
}
fn delete(&mut self) {
2016-08-03 06:24:47 +00:00
if self.cursor == self.content.len() {
return;
}
debug!("Rows: {:?}", self.rows);
2016-08-02 07:32:16 +00:00
let len = self.content[self.cursor..]
.graphemes(true)
.next()
.unwrap()
.len();
let start = self.cursor;
let end = self.cursor + len;
debug!("Start/end: {}/{}", start, end);
debug!("Content: `{}`", self.content);
2016-08-02 07:32:16 +00:00
for _ in self.content.drain(start..end) {}
debug!("Content: `{}`", self.content);
2016-08-02 07:32:16 +00:00
let selected_row = self.selected_row();
debug!("Selected row: {}", selected_row);
if self.cursor == self.rows[selected_row].end {
// We're removing an (implicit) newline.
// This means merging two rows.
2016-08-03 06:24:47 +00:00
let new_end = self.rows[selected_row + 1].end;
self.rows[selected_row].end = new_end;
self.rows.remove(selected_row + 1);
}
2016-08-03 06:24:47 +00:00
self.rows[selected_row].end -= len;
// update all the rows downstream
for row in &mut self.rows.iter_mut().skip(1 + selected_row) {
row.rev_shift(len);
}
debug!("Rows: {:?}", self.rows);
2016-08-03 06:24:47 +00:00
self.fix_damages();
debug!("Rows: {:?}", self.rows);
2016-08-02 07:32:16 +00:00
}
fn insert(&mut self, ch: char) {
// First, we inject the data, but keep the cursor unmoved
// (So the cursor is to the left of the injected char)
self.content.insert(self.cursor, ch);
// Then, we shift the indexes of every row after this one.
2016-08-02 07:32:16 +00:00
let shift = ch.len_utf8();
// The current row grows, every other is just shifted.
2016-08-02 07:32:16 +00:00
let selected_row = self.selected_row();
self.rows[selected_row].end += shift;
for row in &mut self.rows.iter_mut().skip(1 + selected_row) {
row.shift(shift);
2016-08-02 07:32:16 +00:00
}
self.cursor += shift;
// Finally, rows may not have the correct width anymore, so fix them.
2016-08-03 06:24:47 +00:00
self.fix_damages();
}
2016-08-02 07:32:16 +00:00
/// Fix a damage located at the cursor.
///
/// The only damages are assumed to have occured around the cursor.
2016-08-03 06:24:47 +00:00
fn fix_damages(&mut self) {
2016-08-03 04:48:12 +00:00
if self.last_size.is_none() {
// If we don't know our size, it means we'll get a layout command soon.
// So no need to do that here.
return;
}
2016-08-02 07:32:16 +00:00
let size = self.last_size.unwrap().map(|s| s.value);
// Find affected text.
2016-08-03 06:24:47 +00:00
// We know the damage started at this row, so it'll need to go.
//
2016-08-03 06:24:47 +00:00
// Actually, if possible, also re-compute the previous row.
// Indeed, the previous row may have been cut short, and if we now
// break apart a big word, maybe the first half can go up one level.
let first_row = self.selected_row().saturating_sub(1);
2016-08-03 06:24:47 +00:00
let first_byte = self.rows[first_row].start;
// We don't need to go beyond a newline.
// If we don't find one, end of the text it is.
debug!("Cursor: {}", self.cursor);
let last_byte = self.content[self.cursor..].find('\n').map(|i| {
1 + i + self.cursor
});
let last_row = last_byte.map_or(self.rows.len(), |last_byte| {
self.row_at(last_byte)
});
2017-01-19 19:11:57 +00:00
let last_byte = last_byte.unwrap_or_else(|| self.content.len());
2016-08-03 06:24:47 +00:00
debug!("Content: `{}` (len={})",
self.content,
self.content.len());
debug!("start/end: {}/{}", first_byte, last_byte);
debug!("start/end rows: {}/{}", first_row, last_row);
// Do we have access to the entire width?...
let mut available = size.x;
let scrollable = self.rows.len() > size.y;
if scrollable {
// ... not if a scrollbar is there
available = available.saturating_sub(1);
}
// First attempt, if scrollbase status didn't change.
debug!("Rows: {:?}", self.rows);
let new_rows =
make_rows(&self.content[first_byte..last_byte], available);
// How much did this add?
debug!("New rows: {:?}", new_rows);
debug!("{}-{}", first_row, last_row);
2016-08-03 06:24:47 +00:00
let new_row_count = self.rows.len() + new_rows.len() + first_row -
last_row;
if !scrollable && new_row_count > size.y {
// We just changed scrollable status.
// This changes everything.
// TODO: compute_rows() currently makes a scroll-less attempt.
// Here, we know it's just no gonna happen.
2016-08-03 04:48:12 +00:00
self.invalidate();
self.compute_rows(size);
return;
}
// Otherwise, replace stuff.
2016-08-03 06:24:47 +00:00
let affected_rows = first_row..last_row;
let replacement_rows =
new_rows.into_iter().map(|row| row.shifted(first_byte));
VecExt::splice(&mut self.rows, affected_rows, replacement_rows);
self.fix_ghost_row();
2016-08-03 06:24:47 +00:00
self.scrollbase.set_heights(size.y, self.rows.len());
2016-08-02 07:32:16 +00:00
}
}
impl View for TextArea {
2017-04-21 21:03:10 +00:00
fn required_size(&mut self, constraint: Vec2) -> Vec2 {
// Make sure our structure is up to date
2017-04-21 21:03:10 +00:00
self.compute_rows(constraint);
// Ideally, we'd want x = the longest row + 1
// (we always keep a space at the end)
// And y = number of rows
debug!("{:?}", self.rows);
let scroll_width = if self.rows.len() > constraint.y { 1 } else { 0 };
2017-04-21 21:58:19 +00:00
Vec2::new(
scroll_width + 1 + self.rows.iter().map(|r| r.width).max().unwrap_or(1),
self.rows.len(),
2017-04-21 21:58:19 +00:00
)
2017-04-21 21:03:10 +00:00
}
2016-08-02 07:32:16 +00:00
fn draw(&self, printer: &Printer) {
printer.with_color(ColorStyle::Secondary, |printer| {
let effect = if self.enabled {
Effect::Reverse
} else {
Effect::Simple
};
let w = if self.scrollbase.scrollable() {
printer.size.x.saturating_sub(1)
2016-08-02 07:32:16 +00:00
} else {
printer.size.x
};
printer.with_effect(
effect,
|printer| for y in 0..printer.size.y {
printer.print_hline((0, y), w, " ");
},
);
2016-08-02 07:32:16 +00:00
debug!("Content: `{}`", &self.content);
2016-08-02 07:32:16 +00:00
self.scrollbase.draw(printer, |printer, i| {
debug!("Drawing row {}", i);
2016-08-02 07:32:16 +00:00
let row = &self.rows[i];
debug!("row: {:?}", row);
2016-08-02 07:32:16 +00:00
let text = &self.content[row.start..row.end];
debug!("row text: `{}`", text);
printer.with_effect(
effect,
|printer| { printer.print((0, 0), text); },
);
2016-08-02 07:32:16 +00:00
if printer.focused && i == self.selected_row() {
let cursor_offset = self.cursor - row.start;
let c = if cursor_offset == text.len() {
"_"
} else {
text[cursor_offset..].graphemes(true).next().expect(
"Found no char!",
)
2016-08-02 07:32:16 +00:00
};
let offset = text[..cursor_offset].width();
printer.print((offset, 0), c);
}
});
});
}
fn on_event(&mut self, event: Event) -> EventResult {
match event {
Event::Char(ch) => self.insert(ch),
Event::Key(Key::Enter) => self.insert('\n'),
Event::Key(Key::Backspace) if self.cursor > 0 => self.backspace(),
Event::Key(Key::Del) if self.cursor < self.content.len() => {
self.delete()
}
Event::Key(Key::End) => {
let row = self.selected_row();
self.cursor = self.rows[row].end;
if row + 1 < self.rows.len() &&
self.cursor == self.rows[row + 1].start
{
2016-08-02 07:32:16 +00:00
self.move_left();
}
}
Event::Ctrl(Key::Home) => self.cursor = 0,
Event::Ctrl(Key::End) => self.cursor = self.content.len(),
2016-08-02 07:32:16 +00:00
Event::Key(Key::Home) => {
self.cursor = self.rows[self.selected_row()].start
}
Event::Key(Key::Up) if self.selected_row() > 0 => self.move_up(),
Event::Key(Key::Down)
if self.selected_row() + 1 < self.rows.len() => {
self.move_down()
}
2016-08-02 07:32:16 +00:00
Event::Key(Key::PageUp) => self.page_up(),
Event::Key(Key::PageDown) => self.page_down(),
Event::Key(Key::Left) if self.cursor > 0 => self.move_left(),
Event::Key(Key::Right) if self.cursor < self.content.len() => {
self.move_right()
}
_ => return EventResult::Ignored,
}
debug!("Rows: {:?}", self.rows);
2016-08-02 07:32:16 +00:00
let focus = self.selected_row();
self.scrollbase.scroll_to(focus);
EventResult::Consumed(None)
}
fn take_focus(&mut self, _: Direction) -> bool {
self.enabled
}
fn layout(&mut self, size: Vec2) {
2016-08-03 04:48:12 +00:00
self.compute_rows(size);
2016-08-02 07:32:16 +00:00
}
}