cursive/cursive-core/src/views/text_view.rs

406 lines
11 KiB
Rust
Raw Normal View History

use std::ops::Deref;
use std::sync::Arc;
2018-05-18 00:37:39 +00:00
use std::sync::{Mutex, MutexGuard};
2018-06-20 18:44:09 +00:00
use owning_ref::{ArcRef, OwningHandle};
use unicode_width::UnicodeWidthStr;
2018-06-20 18:44:09 +00:00
use crate::align::*;
use crate::theme::Effect;
use crate::utils::lines::spans::{LinesIterator, Row};
use crate::utils::markup::StyledString;
use crate::view::{SizeCache, View};
use crate::{Printer, Vec2, With, XY};
2016-07-13 04:01:11 +00:00
// Content type used internally for caching and storage
2019-08-16 17:15:00 +00:00
type InnerContentType = Arc<StyledString>;
2017-12-31 18:49:13 +00:00
/// Provides access to the content of a [`TextView`].
///
/// Cloning this object will still point to the same content.
///
/// # Examples
///
/// ```rust
/// # use cursive_core::views::{TextView, TextContent};
2017-12-31 18:49:13 +00:00
/// let mut content = TextContent::new("content");
/// let view = TextView::new_with_content(content.clone());
///
/// // Later, possibly in a different thread
/// content.set_content("new content");
/// assert!(view.get_content().source().contains("new"));
2017-12-31 18:49:13 +00:00
/// ```
#[derive(Clone)]
pub struct TextContent {
content: Arc<Mutex<TextContentInner>>,
}
impl TextContent {
2018-01-10 22:58:29 +00:00
/// Creates a new text content around the given value.
///
/// Parses the given value.
pub fn new<S>(content: S) -> Self
2018-01-10 22:58:29 +00:00
where
S: Into<StyledString>,
2018-01-10 22:58:29 +00:00
{
let content = Arc::new(content.into());
2018-01-10 22:58:29 +00:00
TextContent {
content: Arc::new(Mutex::new(TextContentInner {
2019-08-16 17:15:00 +00:00
content_value: content,
content_cache: Arc::new(StyledString::default()),
size_cache: None,
})),
}
}
}
/// A reference to the text content.
///
/// This can be deref'ed into a [`StyledString`].
///
/// This keeps the content locked. Do not store this!
pub struct TextContentRef {
_handle: OwningHandle<
ArcRef<Mutex<TextContentInner>>,
MutexGuard<'static, TextContentInner>,
>,
// We also need to keep a copy of Arc so `deref` can return
// a reference to the `StyledString`
data: Arc<StyledString>,
}
impl Deref for TextContentRef {
type Target = StyledString;
fn deref(&self) -> &StyledString {
self.data.as_ref()
}
}
impl TextContent {
/// Replaces the content with the given value.
2019-10-07 23:14:35 +00:00
pub fn set_content<S>(&self, content: S)
2018-01-10 22:58:29 +00:00
where
S: Into<StyledString>,
2018-01-10 22:58:29 +00:00
{
self.with_content(|c| {
2019-08-16 17:15:00 +00:00
*Arc::make_mut(&mut c.content_value) = content.into();
});
}
/// Append `content` to the end of a `TextView`.
2019-10-07 23:14:35 +00:00
pub fn append<S>(&self, content: S)
2018-01-10 22:58:29 +00:00
where
S: Into<StyledString>,
2018-01-10 22:58:29 +00:00
{
self.with_content(|c| {
// This will only clone content if content_cached and content_value
// are sharing the same underlying Rc.
2019-08-16 17:15:00 +00:00
Arc::make_mut(&mut c.content_value).append(content);
})
}
/// Returns a reference to the content.
///
/// This locks the data while the returned value is alive,
/// so don't keep it too long.
pub fn get_content(&self) -> TextContentRef {
TextContentInner::get_content(&self.content)
}
2019-10-07 23:14:35 +00:00
/// Apply the given closure to the inner content, and bust the cache afterward.
fn with_content<F, O>(&self, f: F) -> O
where
F: FnOnce(&mut TextContentInner) -> O,
{
2019-08-16 17:15:00 +00:00
let mut content = self.content.lock().unwrap();
2019-08-16 17:15:00 +00:00
let out = f(&mut content);
2019-08-16 17:15:00 +00:00
content.size_cache = None;
2018-01-10 22:58:29 +00:00
out
}
}
2018-01-22 22:47:56 +00:00
/// Internel representation of the content for a `TextView`.
///
2018-01-22 22:47:56 +00:00
/// This is mostly just a `StyledString`.
///
/// Can be shared (through a `Arc<Mutex>`).
struct TextContentInner {
2018-01-10 22:58:29 +00:00
// content: String,
content_value: InnerContentType,
content_cache: InnerContentType,
2018-01-10 22:58:29 +00:00
// We keep the cache here so it can be busted when we change the content.
size_cache: Option<XY<SizeCache>>,
}
impl TextContentInner {
/// From a shareable content (Arc + Mutex), return a
fn get_content(content: &Arc<Mutex<TextContentInner>>) -> TextContentRef {
let arc_ref: ArcRef<Mutex<TextContentInner>> =
ArcRef::new(Arc::clone(content));
let _handle = OwningHandle::new_with_fn(arc_ref, |mutex| unsafe {
(*mutex).lock().unwrap()
});
2019-08-16 17:15:00 +00:00
let data = Arc::clone(&_handle.content_value);
TextContentRef { _handle, data }
}
2018-01-05 13:17:47 +00:00
fn is_cache_valid(&self, size: Vec2) -> bool {
match self.size_cache {
None => false,
Some(ref last) => last.x.accept(size.x) && last.y.accept(size.y),
}
}
2019-08-16 17:15:00 +00:00
fn get_cache(&self) -> &InnerContentType {
&self.content_cache
}
}
2017-12-31 18:49:13 +00:00
/// A simple view showing a fixed text.
///
/// # Examples
///
/// ```rust
/// # use cursive_core::Cursive;
/// # use cursive_core::views::TextView;
/// let mut siv = Cursive::dummy();
2017-12-31 18:49:13 +00:00
///
/// siv.add_layer(TextView::new("Hello world!"));
/// ```
pub struct TextView {
// content: String,
content: TextContent,
rows: Vec<Row>,
align: Align,
2018-01-05 13:14:24 +00:00
effect: Effect,
// True if we can wrap long lines.
wrap: bool,
2016-07-17 00:08:17 +00:00
2016-06-28 05:10:59 +00:00
// ScrollBase make many scrolling-related things easier
last_size: Vec2,
width: Option<usize>,
}
impl TextView {
/// Creates a new TextView with the given content.
2018-01-10 22:58:29 +00:00
pub fn new<S>(content: S) -> Self
where
S: Into<StyledString>,
2018-01-10 22:58:29 +00:00
{
Self::new_with_content(TextContent::new(content))
}
/// Creates a new TextView using the given `TextContent`.
2017-12-31 18:49:13 +00:00
///
/// If you kept a clone of the given content, you'll be able to update it
/// remotely.
///
/// # Examples
///
/// ```rust
/// # use cursive_core::views::{TextView, TextContent};
2017-12-31 18:49:13 +00:00
/// let mut content = TextContent::new("content");
/// let view = TextView::new_with_content(content.clone());
///
/// // Later, possibly in a different thread
/// content.set_content("new content");
/// assert!(view.get_content().source().contains("new"));
2017-12-31 18:49:13 +00:00
/// ```
pub fn new_with_content(content: TextContent) -> Self {
TextView {
2019-08-16 17:15:00 +00:00
content,
2018-01-05 13:14:24 +00:00
effect: Effect::Simple,
rows: Vec::new(),
wrap: true,
align: Align::top_left(),
last_size: Vec2::zero(),
width: None,
}
}
/// Creates a new empty `TextView`.
pub fn empty() -> Self {
TextView::new("")
}
2018-01-05 13:14:24 +00:00
/// Sets the effect for the entire content.
pub fn set_effect(&mut self, effect: Effect) {
self.effect = effect;
}
/// Sets the effect for the entire content.
///
/// Chainable variant.
pub fn effect(self, effect: Effect) -> Self {
self.with(|s| s.set_effect(effect))
}
/// Disables content wrap for this view.
///
/// This may be useful if you want horizontal scrolling.
pub fn no_wrap(self) -> Self {
self.with(|s| s.set_content_wrap(false))
}
/// Controls content wrap for this view.
///
/// If `true` (the default), text will wrap long lines when needed.
pub fn set_content_wrap(&mut self, wrap: bool) {
self.wrap = wrap;
}
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
}
/// Center the text horizontally and vertically inside the view.
pub fn center(mut self) -> Self {
self.align = Align::center();
self
}
/// Replace the text in this view.
///
/// Chainable variant.
2018-01-10 22:58:29 +00:00
pub fn content<S>(self, content: S) -> Self
where
S: Into<StyledString>,
2018-01-10 22:58:29 +00:00
{
self.with(|s| s.set_content(content))
2018-01-10 22:58:29 +00:00
}
/// Replace the text in this view.
pub fn set_content<S>(&mut self, content: S)
where
S: Into<StyledString>,
2018-01-10 22:58:29 +00:00
{
self.content.set_content(content);
2015-05-23 17:33:29 +00:00
}
/// Append `content` to the end of a `TextView`.
pub fn append<S>(&mut self, content: S)
2018-01-10 22:58:29 +00:00
where
S: Into<StyledString>,
2018-01-10 22:58:29 +00:00
{
self.content.append(content);
}
2015-05-23 23:46:38 +00:00
/// Returns the current text in this view.
pub fn get_content(&self) -> TextContentRef {
TextContentInner::get_content(&self.content.content)
}
/// Returns a shared reference to the content, allowing content mutation.
pub fn get_shared_content(&mut self) -> TextContent {
// We take &mut here without really needing it,
// because it sort of "makes sense".
TextContent {
content: Arc::clone(&self.content.content),
}
2015-05-23 23:46:38 +00:00
}
// This must be non-destructive, as it may be called
// multiple times during layout.
fn compute_rows(&mut self, size: Vec2) {
let size = if self.wrap { size } else { Vec2::max_value() };
let mut content = self.content.content.lock().unwrap();
2018-01-05 13:17:47 +00:00
if content.is_cache_valid(size) {
2017-01-21 23:06:31 +00:00
return;
}
// Completely bust the cache
// Just in case we fail, we don't want to leave a bad cache.
content.size_cache = None;
2019-08-16 17:15:00 +00:00
content.content_cache = Arc::clone(&content.content_value);
2017-01-21 23:06:31 +00:00
if size.x == 0 {
// Nothing we can do at this point.
return;
}
self.rows =
LinesIterator::new(content.get_cache().as_ref(), size.x).collect();
2017-01-21 23:06:31 +00:00
// Desired width
self.width = self.rows.iter().map(|row| row.width).max();
}
}
impl View for TextView {
2019-02-28 23:55:02 +00:00
fn draw(&self, printer: &Printer<'_, '_>) {
let h = self.rows.len();
2017-10-12 01:06:58 +00:00
// If the content is smaller than the view, align it somewhere.
let offset = self.align.v.get_offset(h, printer.size.y);
let printer = &printer.offset((0, offset));
let content = self.content.content.lock().unwrap();
2018-01-05 13:14:24 +00:00
printer.with_effect(self.effect, |printer| {
for (y, row) in self.rows.iter().enumerate() {
2018-01-10 22:58:29 +00:00
let l = row.width;
let mut x = self.align.h.get_offset(l, printer.size.x);
for span in row.resolve(content.get_cache().as_ref()) {
printer.with_style(*span.attr, |printer| {
printer.print((x, y), span.content);
x += span.content.width();
2018-01-10 22:58:29 +00:00
});
}
2017-10-12 01:06:58 +00:00
}
});
}
fn needs_relayout(&self) -> bool {
let content = self.content.content.lock().unwrap();
content.size_cache.is_none()
}
fn required_size(&mut self, size: Vec2) -> Vec2 {
self.compute_rows(size);
2016-07-17 00:08:17 +00:00
Vec2::new(self.width.unwrap_or(0), self.rows.len())
}
fn layout(&mut self, size: Vec2) {
// Compute the text rows.
self.last_size = size;
self.compute_rows(size);
2018-08-20 20:30:42 +00:00
// The entire "virtual" size (includes all rows)
let my_size = Vec2::new(self.width.unwrap_or(0), self.rows.len());
// Build a fresh cache.
let mut content = self.content.content.lock().unwrap();
2018-08-20 20:30:42 +00:00
content.size_cache = Some(SizeCache::build(my_size, size));
}
}