use std::{borrow::Cow, collections::VecDeque, ops::Range, sync::Arc};
use cosmic_text::LayoutGlyph;
use super::GlyphEngine;
#[cfg(test)]
use super::attrs_for_style;
use crate::{
layout::{
Size,
text_style::{TextShadow, TextStyle},
},
node::{
color::Color,
text_selection::{CaretPosition, CaretPositions, TextSelectionRange},
},
};
mod alignment;
mod chunks;
#[cfg(test)]
#[path = "../../../../tests/input/text_input/crlf_geometry.rs"]
mod crlf_tests;
mod geometry;
mod justification;
mod paint;
#[cfg(test)]
#[path = "../../../../tests/input/text_input/paint_oracle.rs"]
pub(crate) mod paint_oracle;
mod paragraphs;
mod pieces;
mod rows;
#[cfg(test)]
#[path = "../../../../tests/input/text_input/scroll_geometry.rs"]
mod scroll_tests;
#[cfg(test)]
#[path = "../../../../tests/input/text_input/rtl_geometry.rs"]
mod tests;
#[derive(Clone, PartialEq)]
pub(crate) struct TokenStyle {
pub(crate) range: Range<usize>,
pub(crate) text: TextStyle,
pub(crate) padding: f32,
pub(crate) fill: Option<(Color, f32)>,
pub(crate) lines: TextLines,
pub(crate) chip: TokenChip,
}
impl TokenStyle {
pub(crate) fn padding_end(&self) -> f32 {
self.chip.padding_end.unwrap_or(self.padding)
}
}
#[derive(Clone, Default, PartialEq)]
pub(crate) struct TokenChip {
pub(crate) padding_end: Option<f32>,
pub(crate) height: Option<f32>,
pub(crate) border: Option<(f32, Color)>,
pub(crate) icon: Option<TokenIcon>,
pub(crate) atomic: bool,
pub(crate) over_selection: bool,
pub(crate) object: Option<(f32, f32)>,
}
#[derive(Clone, PartialEq)]
pub(crate) struct TokenIcon {
pub(crate) style: TextStyle,
pub(crate) glyph: char,
pub(crate) size: f32,
pub(crate) inset: f32,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) struct TextLines {
pub(crate) underline: bool,
pub(crate) strikethrough: bool,
}
pub(crate) const OBJECT_CARET_ROOM: f32 = 2.0;
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct InputObjectBox {
pub(crate) byte: usize,
pub(crate) x: f32,
pub(crate) y: f32,
pub(crate) width: f32,
pub(crate) height: f32,
row: usize,
}
#[derive(Clone, PartialEq)]
pub(crate) struct InputConfig {
pub(crate) source: Arc<str>,
pub(crate) base: TextStyle,
pub(crate) styles: Vec<TokenStyle>,
pub(crate) width: f32,
pub(crate) min_width: f32,
pub(crate) wrap: bool,
pub(crate) paragraphs: Vec<ParagraphFormat>,
pub(crate) exact_rows: bool,
}
impl InputConfig {
pub(crate) fn object_size(&self, token: usize) -> Option<(f32, f32)> {
let (width, height) = self.styles.get(token)?.chip.object?;
let (width, height) = (width.max(0.0), height.max(0.0));
let room = (self.width - OBJECT_CARET_ROOM).max(0.0);
if width > room && room.is_finite() && width > 0.0 {
return Some((room, height * (room / width)));
}
Some((width, height))
}
fn has_objects(&self) -> bool {
self.styles.iter().any(|style| style.chip.object.is_some())
}
}
#[derive(Clone, PartialEq)]
pub(crate) struct ParagraphFormat {
pub(crate) base: TextStyle,
pub(crate) indent: f32,
pub(crate) gap_before: f32,
pub(crate) marker: ParagraphMark,
pub(crate) fill: Option<(Color, f32)>,
pub(crate) continues: bool,
}
#[derive(Clone, PartialEq)]
#[cfg_attr(not(feature = "markdown"), allow(dead_code))]
pub(crate) enum ParagraphMark {
None,
Dot {
size: f32,
gap: f32,
color: Color,
},
Text {
text: Arc<str>,
gap: f32,
color: Color,
},
Bar {
width: f32,
color: Color,
},
}
#[derive(Clone, Copy)]
pub(crate) struct InputCaret {
pub(crate) byte: usize,
pub(crate) x: f32,
pub(crate) y: f32,
pub(crate) height: f32,
pub(crate) font_size: f32,
pub(crate) row: usize,
}
pub(crate) struct InputGlyph {
pub(crate) glyph: LayoutGlyph,
pub(crate) baseline: f32,
row: usize,
pub(crate) color: Color,
pub(crate) shadow: Option<TextShadow>,
}
pub(crate) struct InputFragment {
pub(crate) x: f32,
pub(crate) y: f32,
pub(crate) width: f32,
pub(crate) height: f32,
pub(crate) color: Color,
pub(crate) radius: f32,
pub(crate) token: Option<(usize, Option<(f32, Color)>)>,
row: usize,
}
pub(crate) struct ClusterInterval {
range: Range<usize>,
x: f32,
right: f32,
y: f32,
}
#[doc(hidden)]
pub struct DecoratedInputLayout {
pub(crate) config: InputConfig,
pub(crate) revision: u64,
pub(crate) glyphs: Vec<InputGlyph>,
pub(crate) fragments: Vec<InputFragment>,
pub(crate) carets: Vec<InputCaret>,
pub(crate) objects: Vec<InputObjectBox>,
rows: Vec<InputRow>,
intervals: Vec<ClusterInterval>,
pub(crate) size: Size,
pub(crate) line_height: f32,
pub(crate) viewport_width: f32,
}
struct InputRow {
range: Range<usize>,
ending: Option<Range<usize>>,
y: f32,
height: f32,
band_top: f32,
band_height: f32,
left: f32,
width: f32,
rtl: bool,
indent: f32,
}
impl DecoratedInputLayout {
fn empty(config: InputConfig, revision: u64) -> Self {
Self {
config,
revision,
glyphs: Vec::new(),
fragments: Vec::new(),
carets: Vec::new(),
objects: Vec::new(),
rows: Vec::new(),
intervals: Vec::new(),
size: Size::default(),
line_height: 1.0,
viewport_width: 0.0,
}
}
}
impl std::fmt::Debug for DecoratedInputLayout {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("DecoratedInputLayout").finish_non_exhaustive()
}
}
#[derive(Default)]
pub(crate) struct InputCache {
revision: u64,
entries: VecDeque<Arc<DecoratedInputLayout>>,
paragraphs: pieces::ParagraphCache,
raster: paint::RasterCache,
chunks: chunks::ChunkCache,
whole_paragraphs: bool,
}
impl InputCache {
pub(super) fn clear(&mut self) {
self.revision = self.revision.wrapping_add(1);
self.entries.clear();
self.paragraphs.clear();
self.raster.clear();
self.chunks.clear();
}
fn find(&self, key: &InputConfig) -> Option<Arc<DecoratedInputLayout>> {
self.entries.iter().find(|layout| &layout.config == key).cloned()
}
pub(super) fn estimated_memory_bytes(&self) -> usize {
self.entries.capacity() * std::mem::size_of::<Arc<DecoratedInputLayout>>()
+ self
.entries
.iter()
.map(|layout| layout.allocated_bytes())
.sum::<usize>()
+ self.paragraphs.estimated_memory_bytes()
+ self.raster.estimated_memory_bytes()
+ self.chunks.estimated_memory_bytes()
}
fn insert(&mut self, layout: Arc<DecoratedInputLayout>) {
while self.entries.len() >= 16
|| self.entries.iter().map(|entry| entry.allocated_bytes()).sum::<usize>() + layout.allocated_bytes()
> 8 * 1024 * 1024
{
if self.entries.pop_front().is_none() {
break;
}
}
if layout.allocated_bytes() <= 8 * 1024 * 1024 {
self.entries.push_back(layout);
}
}
}
impl GlyphEngine {
pub(crate) fn decorated_input(&mut self, config: InputConfig) -> Arc<DecoratedInputLayout> {
if let Some(layout) = self.input_cache.find(&config) {
return layout;
}
let mut output = DecoratedInputLayout::empty(config, self.input_cache.revision);
self.shape_input(&mut output);
let output = Arc::new(output);
self.input_cache.insert(output.clone());
output
}
fn shape_input(&mut self, output: &mut DecoratedInputLayout) {
if output.config.wrap && output.config.base.text_align != crate::layout::text_style::TextAlign::Justified {
self.shape_paragraphs(output);
} else {
self.shape_rows(output);
}
output.finish_carets();
output.align_viewport();
}
fn shape_rows(&mut self, output: &mut DecoratedInputLayout) {
let config = &output.config;
let presentation = if config.wrap {
Cow::Borrowed(config.source.as_ref())
} else {
Cow::Owned(config.source.replace(['\r', '\n'], " "))
};
let object_band = if config.has_objects() {
let base = config.base.clone();
self.line_ascent_descent(&base)
} else {
None
};
let mut buffer = self.input_paragraphs(config, &presentation);
let mut offset = 0;
let mut prepared = Vec::new();
for line in &mut buffer.lines {
let bytes = line.text().len();
let chunked = self.shape_in_chunks(line.text(), line.attrs_list());
let shape = match &chunked {
Some(shape) => shape,
None => line.shape(&mut self.font_system, 8),
};
rows::paragraph(&mut prepared, shape, offset, bytes, &output.config, object_band);
let ending = offset + bytes..offset + bytes + line.ending().as_str().len();
rows::set_ending(&mut prepared, ending.clone());
offset = ending.end;
}
rows::finish(output, prepared);
self.buffer_pool.push(buffer);
}
}