cursive/src/view/text_view.rs

291 lines
8.4 KiB
Rust
Raw Normal View History

use std::cmp::max;
use vec::Vec2;
2016-06-28 05:10:59 +00:00
use view::{DimensionRequest, SizeRequest, View};
use div::*;
use printer::Printer;
use align::*;
use event::*;
use super::scroll::ScrollBase;
/// A simple view showing a fixed text
pub struct TextView {
content: String,
rows: Vec<Row>,
align: Align,
2016-06-28 05:10:59 +00:00
// ScrollBase make many scrolling-related things easier
scrollbase: ScrollBase,
}
2015-05-25 08:24:40 +00:00
// Subset of the main content representing a row on the display.
struct Row {
start: usize,
end: usize,
}
2015-05-25 08:24:40 +00:00
// If the last character is a newline, strip it.
fn strip_last_newline(content: &str) -> &str {
if !content.is_empty() && content.chars().last().unwrap() == '\n' {
&content[..content.len() - 1]
} else {
content
}
}
/// Returns the number of lines required to display the given text with the
/// specified maximum line width.
2015-05-15 00:48:24 +00:00
fn get_line_span(line: &str, max_width: usize) -> usize {
2015-05-25 08:24:40 +00:00
// TODO: this method is stupid. Look at LinesIterator and do the same
// (Or use a common function? Better!)
let mut lines = 1;
let mut length = 0;
2016-06-28 05:40:11 +00:00
for l in line.split(' ').map(|word| word.chars().count()) {
2015-05-15 00:48:24 +00:00
length += l;
2015-05-25 08:30:18 +00:00
if length > max_width {
2015-05-15 00:48:24 +00:00
length = l;
lines += 1;
}
length += 1;
2015-05-15 00:48:24 +00:00
}
lines
}
impl TextView {
/// Creates a new TextView with the given content.
pub fn new(content: &str) -> Self {
let content = strip_last_newline(content);
TextView {
content: content.to_string(),
rows: Vec::new(),
scrollbase: ScrollBase::new(),
align: Align::top_left(),
}
}
2015-06-03 22:36:51 +00:00
/// Sets the horizontal alignment for this view.
pub fn h_align(mut self, h: HAlign) -> Self {
self.align.h = h;
self
}
2015-06-03 22:36:51 +00:00
/// Sets the vertical alignment for this view.
pub fn v_align(mut self, v: VAlign) -> Self {
self.align.v = v;
self
}
2015-06-03 22:36:51 +00:00
/// Sets the alignment for this view.
pub fn align(mut self, a: Align) -> Self {
self.align = a;
self
}
2015-05-23 23:46:38 +00:00
/// Replace the text in this view.
2015-05-23 17:33:29 +00:00
pub fn set_content(&mut self, content: &str) {
let content = strip_last_newline(content);
2015-05-23 17:33:29 +00:00
self.content = content.to_string();
}
2015-05-23 23:46:38 +00:00
/// Returns the current text in this view.
pub fn get_content(&self) -> &str {
&self.content
}
/// Returns the number of lines required to display the content
/// with the given width.
2015-05-15 00:48:24 +00:00
fn get_num_lines(&self, max_width: usize) -> usize {
2016-03-15 22:37:57 +00:00
self.content
2016-06-28 05:40:11 +00:00
.split('\n')
2015-05-15 00:48:24 +00:00
.map(|line| get_line_span(line, max_width))
.fold(0, |sum, x| sum + x)
}
2016-06-28 05:10:59 +00:00
// Given the specified height,
// how many columns do we need to properly display?
2015-05-15 00:48:24 +00:00
fn get_num_cols(&self, max_height: usize) -> usize {
let len = self.content.chars().count();
(div_up_usize(len, max_height)..len)
2015-05-15 00:48:24 +00:00
.find(|w| self.get_num_lines(*w) <= max_height)
.unwrap()
}
2015-05-25 08:24:40 +00:00
// In the absence of any constraint, what size would we like?
fn get_ideal_size(&self) -> Vec2 {
2015-05-18 22:31:55 +00:00
let mut max_width = 0;
let mut height = 0;
2016-06-28 05:40:11 +00:00
for line in self.content.split('\n') {
height += 1;
max_width = max(max_width, line.chars().count());
}
2015-05-18 22:31:55 +00:00
Vec2::new(max_width, height)
}
}
2015-05-25 08:24:40 +00:00
// Given a multiline string, and a given maximum width,
// iterates on the computed rows.
2015-05-15 22:00:20 +00:00
struct LinesIterator<'a> {
content: &'a str,
2015-05-15 22:00:20 +00:00
start: usize,
width: usize,
}
2016-06-25 23:36:22 +00:00
impl<'a> LinesIterator<'a> {
2015-05-25 08:24:40 +00:00
// Start an iterator on the given content.
fn new(content: &'a str, width: usize) -> Self {
LinesIterator {
content: content,
width: width,
start: 0,
2015-05-15 22:00:20 +00:00
}
}
}
2016-06-25 23:36:22 +00:00
impl<'a> Iterator for LinesIterator<'a> {
type Item = Row;
fn next(&mut self) -> Option<Row> {
if self.start >= self.content.len() {
2015-05-25 08:24:40 +00:00
// This is the end.
return None;
}
let start = self.start;
let content = &self.content[self.start..];
2016-06-28 05:40:11 +00:00
if let Some(next) = content.find('\n') {
if content[..next].chars().count() <= self.width {
2015-05-25 08:24:40 +00:00
// We found a newline before the allowed limit.
// Break early.
2016-03-15 22:37:57 +00:00
self.start += next + 1;
return Some(Row {
start: start,
end: next + start,
});
2015-05-15 23:06:48 +00:00
}
2015-05-15 22:00:20 +00:00
}
let content_len = content.chars().count();
if content_len <= self.width {
2015-05-25 08:24:40 +00:00
// I thought it would be longer! -- that's what she said :(
self.start += content.len();
2016-03-15 22:37:57 +00:00
return Some(Row {
start: start,
end: start + content.len(),
});
}
2016-03-15 22:37:57 +00:00
let i = if content_len == self.width + 1 {
2016-06-28 05:10:59 +00:00
// We can't look at the index
// if we're looking at the end of the string
content.len()
} else {
2016-03-15 22:37:57 +00:00
content.char_indices().nth(self.width + 1).unwrap().0
};
let substr = &content[..i];
2016-06-28 05:40:11 +00:00
if let Some(i) = substr.rfind(' ') {
2015-05-25 08:24:40 +00:00
// If we have to break, try to find a whitespace for that.
2016-03-15 22:37:57 +00:00
self.start += i + 1;
return Some(Row {
start: start,
end: i + start,
});
}
2015-05-25 08:24:40 +00:00
// Meh, no whitespace, so just cut in this mess.
// TODO: look for ponctuation instead?
self.start += self.width;
2016-06-28 05:40:11 +00:00
Some(Row {
start: start,
end: start + self.width,
2016-06-28 05:40:11 +00:00
})
2015-05-15 22:00:20 +00:00
}
}
impl View for TextView {
fn draw(&mut self, printer: &Printer) {
let h = self.rows.len();
let offset = self.align.v.get_offset(h, printer.size.y);
let printer = &printer.sub_printer(Vec2::new(0, offset), printer.size, true);
self.scrollbase.draw(printer, |printer, i| {
let row = &self.rows[i];
let text = &self.content[row.start..row.end];
let l = text.chars().count();
let x = self.align.h.get_offset(l, printer.size.x);
2016-03-15 22:37:57 +00:00
printer.print((x, 0), text);
});
2015-05-26 05:35:50 +00:00
}
fn on_event(&mut self, event: Event) -> EventResult {
if !self.scrollbase.scrollable() {
2015-05-26 05:35:50 +00:00
return EventResult::Ignored;
}
match event {
2016-06-28 05:40:11 +00:00
Event::Key(Key::Home) => self.scrollbase.scroll_top(),
Event::Key(Key::End) => self.scrollbase.scroll_bottom(),
Event::Key(Key::Up) if self.scrollbase.can_scroll_up() => self.scrollbase.scroll_up(1),
2016-06-28 05:40:11 +00:00
Event::Key(Key::Down) if self.scrollbase
.can_scroll_down() => self.scrollbase.scroll_down(1),
2016-06-28 05:40:11 +00:00
Event::Key(Key::PageDown) => self.scrollbase.scroll_down(10),
Event::Key(Key::PageUp) => self.scrollbase.scroll_up(10),
2015-05-26 05:35:50 +00:00
_ => return EventResult::Ignored,
}
2016-06-28 05:40:11 +00:00
EventResult::Consumed(None)
}
fn get_min_size(&self, size: SizeRequest) -> Vec2 {
2016-03-15 22:37:57 +00:00
match (size.w, size.h) {
// If we have no directive, ask for a single big line.
// TODO: what if the text has newlines??
(DimensionRequest::Unknown, DimensionRequest::Unknown) => self.get_ideal_size(),
2016-03-15 22:37:57 +00:00
(DimensionRequest::Fixed(w), _) => {
2016-06-28 05:10:59 +00:00
// In a BoxView or something.
let h = self.get_num_lines(w);
Vec2::new(w, h)
2016-03-15 22:37:57 +00:00
}
(_, DimensionRequest::Fixed(h)) => {
let w = self.get_num_cols(h);
Vec2::new(w, h)
2016-03-15 22:37:57 +00:00
}
(DimensionRequest::AtMost(w), _) => {
// Don't _force_ the max width, but take it if we have to.
let ideal = self.get_ideal_size();
if w >= ideal.x {
2016-06-28 05:10:59 +00:00
// This is the cheap path
ideal
2015-05-15 23:06:48 +00:00
} else {
2016-06-28 05:10:59 +00:00
// This is the expensive one :(
let h = self.get_num_lines(w);
2015-05-15 23:06:48 +00:00
Vec2::new(w, h)
}
2016-03-15 22:37:57 +00:00
}
_ => unreachable!(),
}
}
fn take_focus(&mut self) -> bool {
self.scrollbase.scrollable()
}
fn layout(&mut self, size: Vec2) {
// Compute the text rows.
self.rows = LinesIterator::new(&self.content, size.x).collect();
2015-05-26 05:35:50 +00:00
if self.rows.len() > size.y {
self.rows = LinesIterator::new(&self.content, size.x - 2).collect();
2015-05-26 05:35:50 +00:00
}
self.scrollbase.set_heights(size.y, self.rows.len());
}
}