yandex-music-rs/src/engine/text.rs

1257 lines
43 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

use std::collections::HashMap;
use std::hash::{Hash, Hasher};
use cosmic_text::{
Action, Align, Attrs, Buffer, CacheKey, Color as CosmicColor, Cursor, Edit, Editor, Ellipsize,
EllipsizeHeightLimit, Family, FontSystem, Metrics, Motion, Selection, Shaping, SwashCache,
SwashContent, Weight, Wrap,
};
use crate::engine::input::{InputState, Key};
use crate::engine::textures::TextureRegistry;
use crate::engine::types::{
Color, DisplayList, Pos2, Rect, Vec2, GLYPH_ATLAS_TEXTURE_ID,
};
const ATLAS_SIZE: u32 = 1024;
/// The 4 official Yandex Music 5.129.0 font roles loaded from `assets/fonts/`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum FontRole {
/// `YSText-Regular.ttf` (weight 400)
Regular,
/// `YSText-Medium.ttf` (weight 500)
Medium,
/// `YSText-Bold.ttf` (weight 700)
Bold,
/// `YSMusic-HeadlineBold.ttf` (display headline font)
Headline,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum TextAlign {
Left,
Center,
Right,
}
impl TextAlign {
fn to_cosmic(self) -> Align {
match self {
TextAlign::Left => Align::Left,
TextAlign::Center => Align::Center,
TextAlign::Right => Align::Right,
}
}
}
#[derive(Debug, Clone, Copy)]
pub struct TextStyle {
pub role: FontRole,
pub size: f32,
pub line_height: f32,
pub color: Color,
}
impl TextStyle {
#[inline]
pub fn regular(size: f32, color: Color) -> Self {
Self {
role: FontRole::Regular,
size,
line_height: default_line_height(size),
color,
}
}
#[inline]
pub fn medium(size: f32, color: Color) -> Self {
Self {
role: FontRole::Medium,
size,
line_height: default_line_height(size),
color,
}
}
#[inline]
pub fn bold(size: f32, color: Color) -> Self {
Self {
role: FontRole::Bold,
size,
line_height: default_line_height(size),
color,
}
}
#[inline]
pub fn headline(size: f32, color: Color) -> Self {
Self {
role: FontRole::Headline,
size,
line_height: default_line_height(size),
color,
}
}
#[inline]
pub fn with_line_height(mut self, lh: f32) -> Self {
self.line_height = lh.max(self.size);
self
}
#[inline]
pub fn with_color(mut self, color: Color) -> Self {
self.color = color;
self
}
}
#[inline]
fn default_line_height(size: f32) -> f32 {
// Matches Yandex Music CSS line-height ratios (e.g. 14px->20px, 13px->18px, 16px->22px, 24px->28px)
if (size - 12.0).abs() < 0.5 {
16.0
} else if (size - 13.0).abs() < 0.5 {
18.0
} else if (size - 14.0).abs() < 0.5 {
20.0
} else if (size - 16.0).abs() < 0.5 {
22.0
} else if (size - 20.0).abs() < 0.5 {
24.0
} else {
(size * 1.3).round().max(size + 2.0)
}
}
/// Multi-span rich text segment (used for clickable `SeparatedArtists`, Track title + version, etc.).
#[derive(Debug, Clone, Copy)]
pub struct RichSpan<'a> {
pub text: &'a str,
pub style: TextStyle,
/// Optional semantic ID (0 = non-interactive separator/plain text; >0 = clickable span tag).
pub metadata: usize,
}
impl<'a> RichSpan<'a> {
#[inline]
pub fn new(text: &'a str, style: TextStyle) -> Self {
Self {
text,
style,
metadata: 0,
}
}
#[inline]
pub fn tagged(text: &'a str, style: TextStyle, metadata: usize) -> Self {
Self {
text,
style,
metadata,
}
}
}
#[derive(Debug, Clone, Copy)]
struct AtlasEntry {
uv: Rect,
width: u32,
height: u32,
left: i32,
top: i32,
}
/// Dynamic R8 GPU glyph atlas synced to `GLYPH_ATLAS_TEXTURE_ID` via `TextureRegistry`.
struct GlyphAtlas {
width: u32,
height: u32,
cursor_x: u32,
cursor_y: u32,
row_height: u32,
initialized: bool,
entries: HashMap<CacheKey, Option<AtlasEntry>>,
}
impl GlyphAtlas {
fn new() -> Self {
Self {
width: ATLAS_SIZE,
height: ATLAS_SIZE,
cursor_x: 1,
cursor_y: 1,
row_height: 0,
initialized: false,
entries: HashMap::with_capacity(1024),
}
}
fn ensure_initialized(&mut self, textures: &mut TextureRegistry) {
if !self.initialized {
let blank = vec![0u8; (self.width * self.height) as usize];
textures.upload_r8_with_id(GLYPH_ATLAS_TEXTURE_ID, self.width, self.height, blank);
self.initialized = true;
}
}
fn reset(&mut self, textures: &mut TextureRegistry) {
self.cursor_x = 1;
self.cursor_y = 1;
self.row_height = 0;
self.entries.clear();
let blank = vec![0u8; (self.width * self.height) as usize];
textures.upload_r8_with_id(GLYPH_ATLAS_TEXTURE_ID, self.width, self.height, blank);
self.initialized = true;
}
fn get_or_insert(
&mut self,
key: CacheKey,
font_system: &mut FontSystem,
swash: &mut SwashCache,
textures: &mut TextureRegistry,
) -> Option<AtlasEntry> {
self.ensure_initialized(textures);
if let Some(cached) = self.entries.get(&key) {
return *cached;
}
let Some(img) = swash.get_image_uncached(font_system, key) else {
self.entries.insert(key, None);
return None;
};
let gw = img.placement.width;
let gh = img.placement.height;
if gw == 0 || gh == 0 {
self.entries.insert(key, None);
return None;
}
// Convert to single-channel R8 coverage mask
let r8_pixels: Vec<u8> = match img.content {
SwashContent::Mask => img.data,
SwashContent::Color => img
.data
.chunks_exact(4)
.map(|px| px[3])
.collect(),
SwashContent::SubpixelMask => img
.data
.chunks_exact(4)
.map(|px| ((px[0] as u16 + px[1] as u16 + px[2] as u16) / 3) as u8)
.collect(),
};
// Allocate in shelf packer with 1px padding to avoid bilinear bleed
if self.cursor_x + gw + 1 >= self.width {
self.cursor_x = 1;
self.cursor_y += self.row_height + 1;
self.row_height = 0;
}
if self.cursor_y + gh + 1 >= self.height {
self.reset(textures);
}
let ax = self.cursor_x;
let ay = self.cursor_y;
self.cursor_x += gw + 1;
self.row_height = self.row_height.max(gh);
textures.update_r8_region(GLYPH_ATLAS_TEXTURE_ID, ax, ay, gw, gh, r8_pixels);
let inv_w = 1.0 / self.width as f32;
let inv_h = 1.0 / self.height as f32;
let entry = AtlasEntry {
uv: Rect::from_xywh(
ax as f32 * inv_w,
ay as f32 * inv_h,
gw as f32 * inv_w,
gh as f32 * inv_h,
),
width: gw,
height: gh,
left: img.placement.left,
top: img.placement.top,
};
self.entries.insert(key, Some(entry));
Some(entry)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
struct ShapeCacheKey {
text_hash: u64,
text_len: usize,
role: FontRole,
size_bits: u32,
lh_bits: u32,
max_w_bits: u32,
max_lines: u16,
ellipsize: bool,
align: TextAlign,
}
/// Core text shaping, measurement, rich-text, and R8 GPU glyph atlas engine
/// built on `cosmic-text 0.19` + `swash` with all 4 embedded official Yandex fonts.
pub struct TextEngine {
pub font_system: FontSystem,
swash_cache: SwashCache,
atlas: GlyphAtlas,
scale_factor: f32,
ys_text_family: String,
ys_headline_family: String,
shape_cache: HashMap<ShapeCacheKey, (Buffer, Vec2)>,
}
impl Default for TextEngine {
fn default() -> Self {
Self::new()
}
}
impl TextEngine {
/// Initialize `cosmic_text::FontSystem` with all 4 official Yandex Music TTF fonts
/// (`YSText-Regular`, `YSText-Medium`, `YSText-Bold`, `YSMusic-HeadlineBold`) plus system fallbacks.
pub fn new() -> Self {
let mut db = cosmic_text::fontdb::Database::new();
// Load official embedded Yandex fonts first and detect their exact internal family names
let regular_bytes = include_bytes!("../../assets/fonts/YSText-Regular.ttf");
let medium_bytes = include_bytes!("../../assets/fonts/YSText-Medium.ttf");
let bold_bytes = include_bytes!("../../assets/fonts/YSText-Bold.ttf");
let headline_bytes = include_bytes!("../../assets/fonts/YSMusic-HeadlineBold.ttf");
let ys_text_family = load_font_and_detect_family(&mut db, regular_bytes)
.unwrap_or_else(|| "YS Text".to_string());
let _ = load_font_and_detect_family(&mut db, medium_bytes);
let _ = load_font_and_detect_family(&mut db, bold_bytes);
let ys_headline_family = load_font_and_detect_family(&mut db, headline_bytes)
.unwrap_or_else(|| "YSMusic Headline".to_string());
db.set_sans_serif_family(&ys_text_family);
// On Linux, avoid indexing all 400+ system fonts (saves 20-40 MB RSS from Noto CJK/Emoji);
// load only 1-2 lean symbol/fallback faces alongside our 4 embedded official Yandex fonts.
#[cfg(target_os = "linux")]
{
for path in [
"/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
"/usr/share/fonts/truetype/liberation/LiberationSans-Regular.ttf",
"/usr/share/fonts/truetype/noto/NotoSansSymbols2-Regular.ttf",
] {
if std::path::Path::new(path).is_file() {
let _ = db.load_font_file(path);
}
}
}
#[cfg(not(target_os = "linux"))]
{
// Load system fallback fonts for rare symbols / emoji / CJK
db.load_system_fonts();
}
let font_system = FontSystem::new_with_locale_and_db("ru-RU".to_string(), db);
Self {
font_system,
swash_cache: SwashCache::new(),
atlas: GlyphAtlas::new(),
scale_factor: 1.0,
ys_text_family,
ys_headline_family,
shape_cache: HashMap::with_capacity(256),
}
}
#[inline]
pub fn set_scale_factor(&mut self, scale: f32) {
self.scale_factor = scale.clamp(0.5, 4.0);
}
#[inline]
pub fn scale_factor(&self) -> f32 {
self.scale_factor
}
pub fn attrs_for(&self, style: TextStyle) -> Attrs<'_> {
let (family, weight) = match style.role {
FontRole::Regular => (Family::Name(&self.ys_text_family), Weight::NORMAL),
FontRole::Medium => (Family::Name(&self.ys_text_family), Weight::MEDIUM),
FontRole::Bold => (Family::Name(&self.ys_text_family), Weight::BOLD),
FontRole::Headline => (Family::Name(&self.ys_headline_family), Weight::BOLD),
};
Attrs::new()
.family(family)
.weight(weight)
.color(to_cosmic_color(style.color))
}
/// Measure text size (width, height) in logical pixels.
pub fn measure(&mut self, text: &str, style: TextStyle, max_width: Option<f32>) -> Vec2 {
if text.is_empty() {
return Vec2::new(0.0, style.line_height);
}
let (_, size) = self.get_or_shape(text, style, max_width, None, false, TextAlign::Left);
size
}
/// Measure single-line unwrapped text size in logical pixels.
#[inline]
pub fn measure_single_line(&mut self, text: &str, style: TextStyle) -> Vec2 {
self.measure(text, style, None)
}
/// Draw text starting at `pos` (top-left of text block; if `max_width` is `Some`, respects `align`).
pub fn draw_text(
&mut self,
dl: &mut DisplayList,
textures: &mut TextureRegistry,
text: &str,
style: TextStyle,
pos: Pos2,
max_width: Option<f32>,
align: TextAlign,
) -> Vec2 {
if text.is_empty() || style.color.a == 0 {
return Vec2::new(0.0, style.line_height);
}
let (key, size) = self.get_or_shape(text, style, max_width, None, false, align);
self.emit_cached_buffer(dl, textures, key, pos, style.color, None);
size
}
/// Draw single-line text vertically centered inside `rect`, truncating with `…` if wider than `rect.w`.
pub fn draw_text_ellipsis(
&mut self,
dl: &mut DisplayList,
textures: &mut TextureRegistry,
text: &str,
style: TextStyle,
rect: Rect,
align: TextAlign,
) -> Vec2 {
if text.is_empty() || style.color.a == 0 || rect.w <= 1.0 {
return Vec2::ZERO;
}
let (key, size) =
self.get_or_shape(text, style, Some(rect.w), Some(1), true, align);
let y = rect.center_y() - size.y * 0.5 + 1.0;
let x = rect.x;
self.emit_cached_buffer(dl, textures, key, Pos2::new(x, y), style.color, Some(1));
size
}
/// Draw wrapped multi-line text inside `rect`, optionally clamping to `max_lines` with trailing `…`.
pub fn draw_text_wrapped(
&mut self,
dl: &mut DisplayList,
textures: &mut TextureRegistry,
text: &str,
style: TextStyle,
rect: Rect,
max_lines: Option<usize>,
align: TextAlign,
) -> Vec2 {
if text.is_empty() || style.color.a == 0 || rect.w <= 1.0 {
return Vec2::ZERO;
}
let (key, size) = self.get_or_shape(
text,
style,
Some(rect.w),
max_lines,
max_lines.is_some(),
align,
);
self.emit_cached_buffer(dl, textures, key, rect.min(), style.color, max_lines);
size
}
/// Draw wrapped multi-line text vertically centered inside `rect` and uniformly scaled
/// around `rect.center()` by `scale` (1-to-1 CSS `transform: scale(...)` with zero wrap-jump
/// or fractional-size glyph atlas churn).
#[allow(clippy::too_many_arguments)]
pub fn draw_text_wrapped_scaled(
&mut self,
dl: &mut DisplayList,
textures: &mut TextureRegistry,
text: &str,
style: TextStyle,
rect: Rect,
scale: f32,
align: TextAlign,
) -> Vec2 {
if text.is_empty() || style.color.a == 0 || rect.w <= 1.0 || scale <= 0.001 {
return Vec2::ZERO;
}
let (key, size) = self.get_or_shape(text, style, Some(rect.w), None, false, align);
let origin = Pos2::new(rect.x, rect.center_y() - size.y * 0.5);
if (scale - 1.0).abs() < 0.0005 {
self.emit_cached_buffer(dl, textures, key, origin, style.color, None);
return size;
}
let Some((buffer, _)) = self.shape_cache.get(&key) else {
return size;
};
let dpi = self.scale_factor;
let inv_dpi = 1.0 / dpi;
let origin_px = (origin.x * dpi).round();
let center = rect.center();
let mut glyphs_to_draw = Vec::with_capacity(64);
for run in buffer.layout_runs() {
let baseline_py = ((origin.y + run.line_y) * dpi).floor();
for glyph in run.glyphs.iter() {
let phys = glyph.physical((0.0, 0.0), dpi);
glyphs_to_draw.push((phys, baseline_py));
}
}
for (phys, baseline_py) in glyphs_to_draw {
if let Some(entry) = self.atlas.get_or_insert(
phys.cache_key,
&mut self.font_system,
&mut self.swash_cache,
textures,
) {
let gx = (origin_px + (phys.x + entry.left) as f32) * inv_dpi;
let gy = (baseline_py + (phys.y - entry.top) as f32) * inv_dpi;
let gw = entry.width as f32 * inv_dpi;
let gh = entry.height as f32 * inv_dpi;
let sx = center.x + (gx - center.x) * scale;
let sy = center.y + (gy - center.y) * scale;
let sw = gw * scale;
let sh = gh * scale;
dl.push_glyph(Rect::from_xywh(sx, sy, sw, sh), entry.uv, style.color);
}
}
size
}
/// Draw multi-span rich text (e.g. clickable `SeparatedArtists` or `Title + Version`) inside `rect`.
/// Returns screen-space bounding `Rect`s for every span whose `metadata != 0` so callers can
/// perform exact per-span hover & click hit-testing!
pub fn draw_rich_text(
&mut self,
dl: &mut DisplayList,
textures: &mut TextureRegistry,
spans: &[RichSpan<'_>],
rect: Rect,
max_lines: Option<usize>,
align: TextAlign,
) -> Vec<(usize, Rect)> {
if spans.is_empty() || rect.w <= 1.0 {
return Vec::new();
}
let base_style = spans[0].style;
let metrics = Metrics::new(base_style.size, base_style.line_height);
let mut buffer = Buffer::new(&mut self.font_system, metrics);
buffer.set_wrap(if max_lines == Some(1) {
Wrap::None
} else {
Wrap::WordOrGlyph
});
if let Some(n) = max_lines {
buffer.set_ellipsize(Ellipsize::End(EllipsizeHeightLimit::Lines(n)));
}
buffer.set_size(Some(rect.w), Some(rect.h.max(base_style.line_height)));
let default_attrs = self.attrs_for(base_style);
let rich_items: Vec<(&str, Attrs<'_>)> = spans
.iter()
.map(|sp| {
let a = self.attrs_for(sp.style).metadata(sp.metadata);
(sp.text, a)
})
.collect();
buffer.set_rich_text(
rich_items,
&default_attrs,
Shaping::Advanced,
Some(align.to_cosmic()),
);
buffer.shape_until_scroll(&mut self.font_system, false);
// Vertically center if single-line inside a taller box
let content_h = measure_buffer_size(&buffer, max_lines).y;
let origin_y = if max_lines == Some(1) && rect.h > content_h {
rect.center_y() - content_h * 0.5
} else {
rect.y
};
let origin = Pos2::new(rect.x, origin_y);
let mut span_rects: HashMap<usize, Rect> = HashMap::new();
let scale = self.scale_factor;
let inv_scale = 1.0 / scale;
let origin_px = (origin.x * scale).round();
for (run_idx, run) in buffer.layout_runs().enumerate() {
if let Some(limit) = max_lines {
if run_idx >= limit {
break;
}
}
let baseline_py = ((origin.y + run.line_y) * scale).floor();
for glyph in run.glyphs.iter() {
let col = glyph
.color_opt
.map(from_cosmic_color)
.unwrap_or(base_style.color);
if glyph.metadata != 0 {
let g_rect = Rect::from_xywh(
origin.x + glyph.x,
origin.y + run.line_top,
glyph.w.max(1.0),
run.line_height,
);
span_rects
.entry(glyph.metadata)
.and_modify(|r| *r = r.union(g_rect))
.or_insert(g_rect);
}
let phys = glyph.physical((0.0, 0.0), scale);
if let Some(entry) = self.atlas.get_or_insert(
phys.cache_key,
&mut self.font_system,
&mut self.swash_cache,
textures,
) {
let gx = (origin_px + (phys.x + entry.left) as f32) * inv_scale;
let gy = (baseline_py + (phys.y - entry.top) as f32) * inv_scale;
let gw = entry.width as f32 * inv_scale;
let gh = entry.height as f32 * inv_scale;
dl.push_glyph(Rect::from_xywh(gx, gy, gw, gh), entry.uv, col);
}
}
}
let mut out: Vec<(usize, Rect)> = span_rects.into_iter().collect();
out.sort_by_key(|(id, _)| *id);
out
}
fn get_or_shape(
&mut self,
text: &str,
style: TextStyle,
max_width: Option<f32>,
max_lines: Option<usize>,
ellipsize: bool,
align: TextAlign,
) -> (ShapeCacheKey, Vec2) {
let mut hasher = std::collections::hash_map::DefaultHasher::new();
text.hash(&mut hasher);
let key = ShapeCacheKey {
text_hash: hasher.finish(),
text_len: text.len(),
role: style.role,
size_bits: style.size.to_bits(),
lh_bits: style.line_height.to_bits(),
max_w_bits: max_width.unwrap_or(-1.0).to_bits(),
max_lines: max_lines.unwrap_or(0) as u16,
ellipsize,
align,
};
if let Some((_, size)) = self.shape_cache.get(&key) {
return (key, *size);
}
// Bound cache memory so RAM stays tiny even during infinite browsing
if self.shape_cache.len() > 640 {
self.shape_cache.clear();
}
let metrics = Metrics::new(style.size, style.line_height);
let mut buffer = Buffer::new(&mut self.font_system, metrics);
let wrap = if max_width.is_none() || max_lines == Some(1) {
Wrap::None
} else {
Wrap::WordOrGlyph
};
buffer.set_wrap(wrap);
if ellipsize {
let lines = max_lines.unwrap_or(1).max(1);
buffer.set_ellipsize(Ellipsize::End(EllipsizeHeightLimit::Lines(lines)));
}
buffer.set_size(max_width, None);
let attrs = self.attrs_for(style);
let cosmic_align = if max_width.is_some() {
Some(align.to_cosmic())
} else {
None
};
buffer.set_text(text, &attrs, Shaping::Advanced, cosmic_align);
buffer.shape_until_scroll(&mut self.font_system, false);
let size = measure_buffer_size(&buffer, max_lines);
self.shape_cache.insert(key, (buffer, size));
(key, size)
}
fn emit_cached_buffer(
&mut self,
dl: &mut DisplayList,
textures: &mut TextureRegistry,
key: ShapeCacheKey,
origin: Pos2,
color: Color,
max_lines: Option<usize>,
) {
let Some((buffer, _)) = self.shape_cache.get(&key) else {
return;
};
// Collect physical glyphs first so we don't hold an immutable borrow of `self.shape_cache`
// while mutably borrowing `self.font_system`, `self.swash_cache`, and `self.atlas`.
let scale = self.scale_factor;
let inv_scale = 1.0 / scale;
let origin_px = (origin.x * scale).round();
let mut glyphs_to_draw = Vec::with_capacity(64);
for (run_idx, run) in buffer.layout_runs().enumerate() {
if let Some(limit) = max_lines {
if run_idx >= limit {
break;
}
}
let baseline_py = ((origin.y + run.line_y) * scale).floor();
for glyph in run.glyphs.iter() {
let phys = glyph.physical((0.0, 0.0), scale);
glyphs_to_draw.push((phys, baseline_py));
}
}
for (phys, baseline_py) in glyphs_to_draw {
if let Some(entry) = self.atlas.get_or_insert(
phys.cache_key,
&mut self.font_system,
&mut self.swash_cache,
textures,
) {
let gx = (origin_px + (phys.x + entry.left) as f32) * inv_scale;
let gy = (baseline_py + (phys.y - entry.top) as f32) * inv_scale;
let gw = entry.width as f32 * inv_scale;
let gh = entry.height as f32 * inv_scale;
dl.push_glyph(Rect::from_xywh(gx, gy, gw, gh), entry.uv, color);
}
}
}
/// Draw single-line text with smooth per-glyph transparent alpha fade across
/// `[left, left + left_fade_px]` and `[right - right_fade_px, right]` of `clip_rect`
/// (zero opaque boxes over translucent glass; `<= 0.01` keeps that edge at 100% alpha).
#[allow(clippy::too_many_arguments)]
pub fn draw_text_marquee_fade(
&mut self,
dl: &mut DisplayList,
textures: &mut TextureRegistry,
text: &str,
style: TextStyle,
origin_x: f32,
center_y: f32,
clip_rect: Rect,
left_fade_px: f32,
right_fade_px: f32,
) -> Vec2 {
if text.is_empty() || style.color.a == 0 || clip_rect.is_empty() {
return Vec2::ZERO;
}
let (key, size) = self.get_or_shape(text, style, None, Some(1), false, TextAlign::Left);
let Some((buffer, _)) = self.shape_cache.get(&key) else {
return size;
};
let scale = self.scale_factor;
let inv_scale = 1.0 / scale;
let origin_y = center_y - size.y * 0.5 + 1.0;
let origin_px = (origin_x * scale).round();
let mut glyphs_to_draw = Vec::with_capacity(64);
let mut baseline_py = (origin_y * scale).floor();
if let Some(run) = buffer.layout_runs().next() {
baseline_py = ((origin_y + run.line_y) * scale).floor();
for glyph in run.glyphs.iter() {
glyphs_to_draw.push(glyph.physical((0.0, 0.0), scale));
}
}
dl.push_clip(clip_rect, 0.0);
let left_fade = left_fade_px.max(0.0);
let right_fade = right_fade_px.max(0.0);
for phys in glyphs_to_draw {
if let Some(entry) = self.atlas.get_or_insert(
phys.cache_key,
&mut self.font_system,
&mut self.swash_cache,
textures,
) {
let gx = (origin_px + (phys.x + entry.left) as f32) * inv_scale;
let gy = (baseline_py + (phys.y - entry.top) as f32) * inv_scale;
let gw = entry.width as f32 * inv_scale;
let gh = entry.height as f32 * inv_scale;
if gx + gw <= clip_rect.left() || gx >= clip_rect.right() {
continue;
}
let mut alpha_mul = 1.0f32;
let gcx = gx + gw * 0.5;
if left_fade > 0.01 && gcx < clip_rect.left() + left_fade {
let t = ((gcx - clip_rect.left()) / left_fade).clamp(0.0, 1.0);
alpha_mul *= t * t * (3.0 - 2.0 * t);
}
if right_fade > 0.01 && gcx > clip_rect.right() - right_fade {
let t = ((clip_rect.right() - gcx) / right_fade).clamp(0.0, 1.0);
alpha_mul *= t * t * (3.0 - 2.0 * t);
}
let col = style.color.scale_alpha(alpha_mul);
if col.a > 0 {
dl.push_glyph(Rect::from_xywh(gx, gy, gw, gh), entry.uv, col);
}
}
}
dl.pop_clip();
size
}
}
fn measure_buffer_size(buffer: &Buffer, max_lines: Option<usize>) -> Vec2 {
let mut max_w = 0.0f32;
let mut total_h = 0.0f32;
let mut count = 0usize;
for run in buffer.layout_runs() {
if let Some(limit) = max_lines {
if count >= limit {
break;
}
}
max_w = max_w.max(run.line_w);
total_h = total_h.max(run.line_top + run.line_height);
count += 1;
}
if count == 0 {
total_h = buffer.metrics().line_height;
}
Vec2::new(max_w.ceil(), total_h.ceil())
}
fn load_font_and_detect_family(
db: &mut cosmic_text::fontdb::Database,
bytes: &'static [u8],
) -> Option<String> {
let ids = db.load_font_source(cosmic_text::fontdb::Source::Binary(
std::sync::Arc::new(bytes),
));
let id = ids.into_iter().next()?;
let face = db.face(id)?;
face.families.first().map(|(name, _)| name.clone())
}
#[inline]
fn to_cosmic_color(c: Color) -> CosmicColor {
CosmicColor::rgba(c.r, c.g, c.b, c.a)
}
#[inline]
fn from_cosmic_color(c: CosmicColor) -> Color {
Color::rgba(c.r(), c.g(), c.b(), c.a())
}
/// Events emitted by `TextInputState::handle_input`.
#[derive(Debug, Clone, Copy, Default)]
pub struct TextInputEvent {
pub changed: bool,
pub submitted: bool,
pub escaped: bool,
}
/// Full single-line RU/EN text editor wrapping `cosmic_text::Editor<'static>` + `arboard` clipboard.
/// Supports typing, selection, caret blink, mouse click/drag/double-click,
/// Ctrl+C / Ctrl+X / Ctrl+V / Ctrl+A, Backspace, Delete, Left, Right, Home, End.
pub struct TextInputState {
editor: Editor<'static>,
initialized: bool,
scroll_x: f32,
last_edit_time: f64,
cached_text: String,
dragging_selection: bool,
}
impl Default for TextInputState {
fn default() -> Self {
Self::new("")
}
}
impl TextInputState {
pub fn new(initial: &str) -> Self {
let buffer = Buffer::new_empty(Metrics::new(14.0, 20.0));
let editor = Editor::new(buffer);
Self {
editor,
initialized: false,
scroll_x: 0.0,
last_edit_time: 0.0,
cached_text: initial.to_string(),
dragging_selection: false,
}
}
fn ensure_init(&mut self, text_engine: &mut TextEngine, style: TextStyle) {
if self.initialized {
return;
}
let metrics = Metrics::new(style.size, style.line_height);
let initial = self.cached_text.clone();
let attrs = text_engine.attrs_for(style);
self.editor.with_buffer_mut(|buf| {
buf.set_metrics(metrics);
buf.set_wrap(Wrap::None);
buf.set_size(None, None);
buf.set_text(&initial, &attrs, Shaping::Advanced, None);
});
self.editor
.with_buffer_mut(|buf| buf.shape_until_scroll(&mut text_engine.font_system, false));
let end_idx = initial.len();
self.editor.set_cursor(Cursor::new(0, end_idx));
self.editor.set_selection(Selection::None);
self.initialized = true;
}
/// Current plain text content.
pub fn text(&self) -> String {
if !self.initialized {
return self.cached_text.clone();
}
self.editor.with_buffer(|buf| {
buf.lines
.first()
.map(|l| l.text().to_string())
.unwrap_or_default()
})
}
pub fn is_empty(&self) -> bool {
if !self.initialized {
return self.cached_text.is_empty();
}
self.editor.with_buffer(|buf| {
buf.lines.first().map_or(true, |l| l.text().is_empty())
})
}
/// Synchronize external `&str` into the editor if it differs from internal buffer.
pub fn sync_external(&mut self, text_engine: &mut TextEngine, external: &str, style: TextStyle) {
self.ensure_init(text_engine, style);
if self.text() != external {
self.set_text(text_engine, external, style);
}
}
pub fn set_text(&mut self, text_engine: &mut TextEngine, text: &str, style: TextStyle) {
let single_line = text.replace(['\r', '\n'], " ");
self.cached_text = single_line.clone();
let metrics = Metrics::new(style.size, style.line_height);
let attrs = text_engine.attrs_for(style);
self.editor.with_buffer_mut(|buf| {
buf.set_metrics(metrics);
buf.set_wrap(Wrap::None);
buf.set_size(None, None);
buf.set_text(&single_line, &attrs, Shaping::Advanced, None);
});
self.editor
.with_buffer_mut(|buf| buf.shape_until_scroll(&mut text_engine.font_system, false));
self.editor.set_cursor(Cursor::new(0, single_line.len()));
self.editor.set_selection(Selection::None);
self.scroll_x = 0.0;
self.initialized = true;
}
pub fn clear(&mut self, text_engine: &mut TextEngine, style: TextStyle) {
self.set_text(text_engine, "", style);
}
pub fn select_all(&mut self) {
let len = self.editor.with_buffer(|buf| {
buf.lines.first().map_or(0, |l| l.text().len())
});
self.editor.set_selection(Selection::Normal(Cursor::new(0, 0)));
self.editor.set_cursor(Cursor::new(0, len));
}
/// Process keyboard, clipboard, and mouse interactions for this text input.
pub fn handle_input(
&mut self,
text_engine: &mut TextEngine,
input: &InputState,
text_rect: Rect,
style: TextStyle,
focused: bool,
) -> TextInputEvent {
self.ensure_init(text_engine, style);
let mut ev = TextInputEvent::default();
if !focused {
self.dragging_selection = false;
return ev;
}
let before = self.text();
// Pointer click / double-click / drag selection inside text_rect
if let Some(pos) = input.pointer_pos {
let local_x = ((pos.x - text_rect.x + self.scroll_x).round()) as i32;
let local_y = (style.line_height * 0.5).round() as i32;
if text_rect.contains(pos) && input.left_pressed {
self.last_edit_time = input.time;
if input.left_double_clicked {
self.editor.action(
&mut text_engine.font_system,
Action::DoubleClick { x: local_x, y: local_y },
);
} else {
self.editor.action(
&mut text_engine.font_system,
Action::Click { x: local_x, y: local_y },
);
}
self.dragging_selection = true;
} else if self.dragging_selection && input.left_down {
self.editor.action(
&mut text_engine.font_system,
Action::Drag { x: local_x, y: local_y },
);
}
}
if !input.left_down {
self.dragging_selection = false;
}
// Keyboard shortcuts & navigation
for kp in &input.key_events {
let cmd = kp.modifiers.command();
let shift = kp.modifiers.shift;
self.last_edit_time = input.time;
if cmd {
if let Key::Char(ch) = kp.key {
match ch.to_ascii_lowercase() {
'a' | 'ф' => {
self.select_all();
continue;
}
'c' | 'с' => {
if let Some(sel) = self.editor.copy_selection() {
copy_to_clipboard(&sel);
}
continue;
}
'x' | 'ч' => {
if let Some(sel) = self.editor.copy_selection() {
copy_to_clipboard(&sel);
self.editor.delete_selection();
self.editor.shape_as_needed(&mut text_engine.font_system, false);
}
continue;
}
'v' | 'м' => {
if let Some(clip) = paste_from_clipboard() {
let clean = clip.replace(['\r', '\n'], " ");
self.editor.delete_selection();
self.editor.insert_string(&clean, None);
self.editor.shape_as_needed(&mut text_engine.font_system, false);
}
continue;
}
_ => {}
}
}
}
match kp.key {
Key::Enter => {
ev.submitted = true;
}
Key::Escape => {
self.editor.set_selection(Selection::None);
ev.escaped = true;
}
Key::Backspace => {
self.editor.action(&mut text_engine.font_system, Action::Backspace);
}
Key::Delete => {
self.editor.action(&mut text_engine.font_system, Action::Delete);
}
Key::ArrowLeft => {
let motion = if cmd { Motion::LeftWord } else { Motion::Left };
self.apply_motion(&mut text_engine.font_system, motion, shift);
}
Key::ArrowRight => {
let motion = if cmd { Motion::RightWord } else { Motion::Right };
self.apply_motion(&mut text_engine.font_system, motion, shift);
}
Key::Home => {
self.apply_motion(&mut text_engine.font_system, Motion::Home, shift);
}
Key::End => {
self.apply_motion(&mut text_engine.font_system, Motion::End, shift);
}
_ => {}
}
}
// Committed UTF-8 text (handles RU Cyrillic, EN Latin, numbers, punctuation seamlessly!)
if !input.text_input.is_empty() {
self.last_edit_time = input.time;
for ch in input.text_input.chars() {
if !ch.is_control() {
self.editor.action(&mut text_engine.font_system, Action::Insert(ch));
}
}
}
self.editor.shape_as_needed(&mut text_engine.font_system, false);
let after = self.text();
if after != before {
self.cached_text = after;
ev.changed = true;
}
ev
}
fn apply_motion(&mut self, font_system: &mut FontSystem, motion: Motion, shift: bool) {
if shift {
if self.editor.selection() == Selection::None {
let c = self.editor.cursor();
self.editor.set_selection(Selection::Normal(c));
}
self.editor.action(font_system, Action::Motion(motion));
} else {
self.editor.set_selection(Selection::None);
self.editor.action(font_system, Action::Motion(motion));
}
}
/// Render the text input contents, selection highlight, placeholder, and blinking caret inside `text_rect`.
#[allow(clippy::too_many_arguments)]
pub fn draw(
&mut self,
dl: &mut DisplayList,
textures: &mut TextureRegistry,
text_engine: &mut TextEngine,
text_rect: Rect,
style: TextStyle,
placeholder: &str,
placeholder_color: Color,
selection_bg: Color,
cursor_color: Color,
focused: bool,
time: f64,
) {
self.ensure_init(text_engine, style);
// Update horizontal scroll so cursor always stays inside `text_rect`
let cursor = self.editor.cursor();
let cursor_x_px = self.editor.with_buffer(|buf| {
buf.layout_runs()
.next()
.and_then(|run| run.cursor_position(&cursor))
.unwrap_or(0.0)
});
let pad_right = 4.0;
if cursor_x_px - self.scroll_x > text_rect.w - pad_right {
self.scroll_x = (cursor_x_px - (text_rect.w - pad_right)).max(0.0);
} else if cursor_x_px - self.scroll_x < 0.0 {
self.scroll_x = cursor_x_px.max(0.0);
}
dl.push_clip(text_rect, 0.0);
let is_empty = self.is_empty();
if is_empty && !placeholder.is_empty() {
let ph_style = style.with_color(placeholder_color);
text_engine.draw_text_ellipsis(dl, textures, placeholder, ph_style, text_rect, TextAlign::Left);
}
let origin_y = text_rect.center_y() - style.line_height * 0.5;
let origin_x = text_rect.x - self.scroll_x;
// Selection highlight
if focused {
if let Some((start, end)) = self.editor.selection_bounds() {
self.editor.with_buffer(|buf| {
if let Some(run) = buf.layout_runs().next() {
for (hx, hw) in run.highlight(start, end) {
dl.push_rect(
Rect::from_xywh(origin_x + hx, origin_y + run.line_top, hw, run.line_height),
3.0,
selection_bg,
);
}
}
});
}
}
// Draw glyphs (single integer physical baseline per line)
if !is_empty {
let scale = text_engine.scale_factor();
let inv_scale = 1.0 / scale;
let origin_px = (origin_x * scale).round();
let mut baseline_py = (origin_y * scale).floor();
let mut glyphs = Vec::with_capacity(64);
self.editor.with_buffer(|buf| {
if let Some(run) = buf.layout_runs().next() {
baseline_py = ((origin_y + run.line_y) * scale).floor();
for g in run.glyphs.iter() {
glyphs.push(g.physical((0.0, 0.0), scale));
}
}
});
for phys in glyphs {
if let Some(entry) = text_engine.atlas.get_or_insert(
phys.cache_key,
&mut text_engine.font_system,
&mut text_engine.swash_cache,
textures,
) {
let gx = (origin_px + (phys.x + entry.left) as f32) * inv_scale;
let gy = (baseline_py + (phys.y - entry.top) as f32) * inv_scale;
let gw = entry.width as f32 * inv_scale;
let gh = entry.height as f32 * inv_scale;
dl.push_glyph(Rect::from_xywh(gx, gy, gw, gh), entry.uv, style.color);
}
}
}
// Blinking caret (solid for 0.5s after edit, then 1Hz blink)
if focused {
let since_edit = (time - self.last_edit_time).max(0.0);
let visible = since_edit < 0.5 || ((since_edit * 2.0) as u64 % 2 == 0);
if visible {
let cx = origin_x + cursor_x_px;
let caret_h = (style.size * 1.25).min(text_rect.h);
let cy = text_rect.center_y() - caret_h * 0.5;
dl.push_rect(Rect::from_xywh(cx, cy, 1.5, caret_h), 0.75, cursor_color);
}
}
dl.pop_clip();
}
}
/// Write text to OS clipboard using `arboard 3`.
pub fn copy_to_clipboard(text: &str) -> bool {
if let Ok(mut cb) = arboard::Clipboard::new() {
return cb.set_text(text.to_string()).is_ok();
}
false
}
/// Read text from OS clipboard using `arboard 3`.
pub fn paste_from_clipboard() -> Option<String> {
let mut cb = arboard::Clipboard::new().ok()?;
cb.get_text().ok()
}