use std::ops::Deref;
use std::sync::Arc;
use std::sync::{Mutex, MutexGuard};
use owning_ref::{ArcRef, OwningHandle};
use unicode_width::UnicodeWidthStr;
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};
type InnerContentType = Arc<StyledString>;
#[derive(Clone)]
pub struct TextContent {
content: Arc<Mutex<TextContentInner>>,
}
impl TextContent {
pub fn new<S>(content: S) -> Self
where
S: Into<StyledString>,
{
let content = Arc::new(content.into());
TextContent {
content: Arc::new(Mutex::new(TextContentInner {
content_value: content,
content_cache: Arc::new(StyledString::default()),
size_cache: None,
})),
}
}
}
pub struct TextContentRef {
_handle: OwningHandle<
ArcRef<Mutex<TextContentInner>>,
MutexGuard<'static, TextContentInner>,
>,
data: Arc<StyledString>,
}
impl Deref for TextContentRef {
type Target = StyledString;
fn deref(&self) -> &StyledString {
self.data.as_ref()
}
}
impl TextContent {
pub fn set_content<S>(&self, content: S)
where
S: Into<StyledString>,
{
self.with_content(|c| {
*Arc::make_mut(&mut c.content_value) = content.into();
});
}
pub fn append<S>(&self, content: S)
where
S: Into<StyledString>,
{
self.with_content(|c| {
Arc::make_mut(&mut c.content_value).append(content);
})
}
pub fn get_content(&self) -> TextContentRef {
TextContentInner::get_content(&self.content)
}
fn with_content<F, O>(&self, f: F) -> O
where
F: FnOnce(&mut TextContentInner) -> O,
{
let mut content = self.content.lock().unwrap();
let out = f(&mut content);
content.size_cache = None;
out
}
}
struct TextContentInner {
content_value: InnerContentType,
content_cache: InnerContentType,
size_cache: Option<XY<SizeCache>>,
}
impl TextContentInner {
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()
});
let data = Arc::clone(&_handle.content_value);
TextContentRef { _handle, data }
}
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),
}
}
fn get_cache(&self) -> &InnerContentType {
&self.content_cache
}
}
pub struct TextView {
content: TextContent,
rows: Vec<Row>,
align: Align,
effect: Effect,
wrap: bool,
last_size: Vec2,
width: Option<usize>,
}
impl TextView {
pub fn new<S>(content: S) -> Self
where
S: Into<StyledString>,
{
Self::new_with_content(TextContent::new(content))
}
pub fn new_with_content(content: TextContent) -> Self {
TextView {
content,
effect: Effect::Simple,
rows: Vec::new(),
wrap: true,
align: Align::top_left(),
last_size: Vec2::zero(),
width: None,
}
}
pub fn empty() -> Self {
TextView::new("")
}
pub fn set_effect(&mut self, effect: Effect) {
self.effect = effect;
}
pub fn effect(self, effect: Effect) -> Self {
self.with(|s| s.set_effect(effect))
}
pub fn no_wrap(self) -> Self {
self.with(|s| s.set_content_wrap(false))
}
pub fn set_content_wrap(&mut self, wrap: bool) {
self.wrap = wrap;
}
pub fn h_align(mut self, h: HAlign) -> Self {
self.align.h = h;
self
}
pub fn v_align(mut self, v: VAlign) -> Self {
self.align.v = v;
self
}
pub fn align(mut self, a: Align) -> Self {
self.align = a;
self
}
pub fn center(mut self) -> Self {
self.align = Align::center();
self
}
pub fn content<S>(self, content: S) -> Self
where
S: Into<StyledString>,
{
self.with(|s| s.set_content(content))
}
pub fn set_content<S>(&mut self, content: S)
where
S: Into<StyledString>,
{
self.content.set_content(content);
}
pub fn append<S>(&mut self, content: S)
where
S: Into<StyledString>,
{
self.content.append(content);
}
pub fn get_content(&self) -> TextContentRef {
TextContentInner::get_content(&self.content.content)
}
pub fn get_shared_content(&mut self) -> TextContent {
TextContent {
content: Arc::clone(&self.content.content),
}
}
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();
if content.is_cache_valid(size) {
return;
}
content.size_cache = None;
content.content_cache = Arc::clone(&content.content_value);
if size.x == 0 {
return;
}
self.rows =
LinesIterator::new(content.get_cache().as_ref(), size.x).collect();
self.width = self.rows.iter().map(|row| row.width).max();
}
}
impl View for TextView {
fn draw(&self, printer: &Printer<'_, '_>) {
let h = self.rows.len();
let offset = self.align.v.get_offset(h, printer.size.y);
let printer = &printer.offset((0, offset));
let content = self.content.content.lock().unwrap();
printer.with_effect(self.effect, |printer| {
for (y, row) in self.rows.iter().enumerate() {
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();
});
}
}
});
}
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);
Vec2::new(self.width.unwrap_or(0), self.rows.len())
}
fn layout(&mut self, size: Vec2) {
self.last_size = size;
self.compute_rows(size);
let my_size = Vec2::new(self.width.unwrap_or(0), self.rows.len());
let mut content = self.content.content.lock().unwrap();
content.size_cache = Some(SizeCache::build(my_size, size));
}
}