text update for more code reuse + much better caching
This commit is contained in:
117
src/core/text/build.rs
Normal file
117
src/core/text/build.rs
Normal file
@@ -0,0 +1,117 @@
|
||||
use std::marker::{PhantomData, Sized};
|
||||
|
||||
use crate::prelude::*;
|
||||
use cosmic_text::{Attrs, Family, Metrics, Shaping};
|
||||
|
||||
pub trait TextBuilderOutput: Sized {
|
||||
type Output;
|
||||
fn run(ui: &mut Ui, builder: TextBuilder<Self>) -> Self::Output;
|
||||
}
|
||||
|
||||
pub struct TextBuilder<O = TextOutput> {
|
||||
pub content: String,
|
||||
pub attrs: TextAttrs,
|
||||
_pd: PhantomData<O>,
|
||||
}
|
||||
|
||||
impl<O> TextBuilder<O> {
|
||||
pub fn size(mut self, size: impl UiNum) -> Self {
|
||||
self.attrs.font_size = size.to_f32();
|
||||
self.attrs.line_height = self.attrs.font_size * 1.1;
|
||||
self
|
||||
}
|
||||
pub fn color(mut self, color: UiColor) -> Self {
|
||||
self.attrs.color = color;
|
||||
self
|
||||
}
|
||||
pub fn family(mut self, family: Family<'static>) -> Self {
|
||||
self.attrs.family = family;
|
||||
self
|
||||
}
|
||||
pub fn line_height(mut self, height: f32) -> Self {
|
||||
self.attrs.line_height = height;
|
||||
self
|
||||
}
|
||||
pub fn text_align(mut self, align: Align) -> Self {
|
||||
self.attrs.align = align;
|
||||
self
|
||||
}
|
||||
pub fn wrap(mut self, wrap: bool) -> Self {
|
||||
self.attrs.wrap = wrap;
|
||||
self
|
||||
}
|
||||
pub fn editable(self) -> TextBuilder<TextEditOutput> {
|
||||
TextBuilder {
|
||||
content: self.content,
|
||||
attrs: self.attrs,
|
||||
_pd: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct TextOutput;
|
||||
impl TextBuilderOutput for TextOutput {
|
||||
type Output = Text;
|
||||
|
||||
fn run(ui: &mut Ui, builder: TextBuilder<Self>) -> Self::Output {
|
||||
let mut buf = TextBuffer::new_empty(Metrics::new(
|
||||
builder.attrs.font_size,
|
||||
builder.attrs.line_height,
|
||||
));
|
||||
let font_system = &mut ui.data.text.font_system;
|
||||
buf.set_text(
|
||||
font_system,
|
||||
&builder.content,
|
||||
&Attrs::new(),
|
||||
Shaping::Advanced,
|
||||
);
|
||||
let mut text = Text {
|
||||
content: builder.content.into(),
|
||||
view: TextView::new(buf, builder.attrs),
|
||||
};
|
||||
text.content.changed = false;
|
||||
builder.attrs.apply(font_system, &mut text.view.buf, None);
|
||||
text
|
||||
}
|
||||
}
|
||||
|
||||
pub struct TextEditOutput;
|
||||
impl TextBuilderOutput for TextEditOutput {
|
||||
type Output = TextEdit;
|
||||
|
||||
fn run(ui: &mut Ui, builder: TextBuilder<Self>) -> Self::Output {
|
||||
let buf = TextBuffer::new_empty(Metrics::new(
|
||||
builder.attrs.font_size,
|
||||
builder.attrs.line_height,
|
||||
));
|
||||
let mut text = TextEdit {
|
||||
view: TextView::new(buf, builder.attrs),
|
||||
cursor: None,
|
||||
};
|
||||
let font_system = &mut ui.data.text.font_system;
|
||||
text.buf.set_text(
|
||||
font_system,
|
||||
&builder.content,
|
||||
&Attrs::new(),
|
||||
Shaping::Advanced,
|
||||
);
|
||||
builder.attrs.apply(font_system, &mut text.buf, None);
|
||||
text
|
||||
}
|
||||
}
|
||||
|
||||
impl<O: TextBuilderOutput> FnOnce<(&mut Ui,)> for TextBuilder<O> {
|
||||
type Output = O::Output;
|
||||
|
||||
extern "rust-call" fn call_once(self, args: (&mut Ui,)) -> Self::Output {
|
||||
O::run(args.0, self)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn text(content: impl Into<String>) -> TextBuilder {
|
||||
TextBuilder {
|
||||
content: content.into(),
|
||||
attrs: TextAttrs::default(),
|
||||
_pd: PhantomData,
|
||||
}
|
||||
}
|
||||
268
src/core/text/edit.rs
Normal file
268
src/core/text/edit.rs
Normal file
@@ -0,0 +1,268 @@
|
||||
use std::ops::{Deref, DerefMut};
|
||||
|
||||
use crate::prelude::*;
|
||||
use cosmic_text::{Affinity, Attrs, Cursor, FontSystem, Motion, Shaping};
|
||||
use unicode_segmentation::UnicodeSegmentation;
|
||||
use winit::{
|
||||
event::KeyEvent,
|
||||
keyboard::{Key, NamedKey},
|
||||
};
|
||||
|
||||
pub struct TextEdit {
|
||||
pub(super) view: TextView,
|
||||
pub(super) cursor: Option<Cursor>,
|
||||
}
|
||||
|
||||
impl TextEdit {
|
||||
pub fn region(&self) -> UiRegion {
|
||||
UiRegion::from_size_align(
|
||||
self.tex().map(|t| t.size()).unwrap_or(Vec2::ZERO),
|
||||
self.align,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl Widget for TextEdit {
|
||||
fn draw(&mut self, painter: &mut Painter) {
|
||||
let tex = self.view.draw(&mut painter.size_ctx());
|
||||
let region = text_region(&tex, self.align);
|
||||
painter.texture_within(&tex.handle, region);
|
||||
|
||||
if let Some(cursor) = &self.cursor
|
||||
&& let Some(offset) = cursor_pos(cursor, &self.buf)
|
||||
{
|
||||
let size = vec2(1, self.attrs.line_height);
|
||||
painter.primitive_within(
|
||||
RectPrimitive::color(Color::WHITE),
|
||||
UiRegion::from_size_align(size, Align::TopLeft)
|
||||
.offset(offset)
|
||||
.within(®ion),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn desired_size(&mut self, ctx: &mut SizeCtx) -> UiVec2 {
|
||||
UiVec2::abs(self.view.draw(ctx).size())
|
||||
}
|
||||
}
|
||||
|
||||
/// copied & modified from fn found in Editor in cosmic_text
|
||||
fn cursor_pos(cursor: &Cursor, buf: &TextBuffer) -> Option<(f32, f32)> {
|
||||
let mut prev = None;
|
||||
for run in buf
|
||||
.layout_runs()
|
||||
.skip_while(|r| r.line_i < cursor.line)
|
||||
.take_while(|r| r.line_i == cursor.line)
|
||||
{
|
||||
prev = Some((run.line_w, run.line_top));
|
||||
for glyph in run.glyphs.iter() {
|
||||
if cursor.index == glyph.start {
|
||||
return Some((glyph.x, run.line_top));
|
||||
} else if cursor.index > glyph.start && cursor.index < glyph.end {
|
||||
// Guess x offset based on characters
|
||||
let mut before = 0;
|
||||
let mut total = 0;
|
||||
|
||||
let cluster = &run.text[glyph.start..glyph.end];
|
||||
for (i, _) in cluster.grapheme_indices(true) {
|
||||
if glyph.start + i < cursor.index {
|
||||
before += 1;
|
||||
}
|
||||
total += 1;
|
||||
}
|
||||
|
||||
let offset = glyph.w * (before as f32) / (total as f32);
|
||||
return Some((glyph.x + offset, run.line_top));
|
||||
}
|
||||
}
|
||||
}
|
||||
prev
|
||||
}
|
||||
|
||||
pub struct TextEditCtx<'a> {
|
||||
pub text: &'a mut TextEdit,
|
||||
pub font_system: &'a mut FontSystem,
|
||||
}
|
||||
|
||||
impl<'a> TextEditCtx<'a> {
|
||||
pub fn take(&mut self) -> String {
|
||||
let text = self
|
||||
.text
|
||||
.buf
|
||||
.lines
|
||||
.drain(..)
|
||||
.map(|l| l.into_text())
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
self.text
|
||||
.buf
|
||||
.set_text(self.font_system, "", &Attrs::new(), Shaping::Advanced);
|
||||
if let Some(cursor) = &mut self.text.cursor {
|
||||
cursor.line = 0;
|
||||
cursor.index = 0;
|
||||
cursor.affinity = Affinity::default();
|
||||
}
|
||||
text
|
||||
}
|
||||
|
||||
pub fn motion(&mut self, motion: Motion) {
|
||||
if let Some(cursor) = self.text.cursor
|
||||
&& let Some((cursor, _)) =
|
||||
self.text
|
||||
.buf
|
||||
.cursor_motion(self.font_system, cursor, None, motion)
|
||||
{
|
||||
self.text.cursor = Some(cursor);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn insert(&mut self, text: &str) {
|
||||
let mut lines = text.split('\n');
|
||||
let Some(first) = lines.next() else {
|
||||
return;
|
||||
};
|
||||
self.insert_inner(first);
|
||||
for line in lines {
|
||||
self.newline();
|
||||
self.insert_inner(line);
|
||||
}
|
||||
}
|
||||
|
||||
fn insert_inner(&mut self, text: &str) {
|
||||
if let Some(cursor) = &mut self.text.cursor {
|
||||
let line = &mut self.text.view.buf.lines[cursor.line];
|
||||
let mut line_text = line.text().to_string();
|
||||
line_text.insert_str(cursor.index, text);
|
||||
line.set_text(line_text, line.ending(), line.attrs_list().clone());
|
||||
for _ in 0..text.len() {
|
||||
self.motion(Motion::Right);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn newline(&mut self) {
|
||||
if let Some(cursor) = &mut self.text.cursor {
|
||||
let lines = &mut self.text.view.buf.lines;
|
||||
let line = &mut lines[cursor.line];
|
||||
let new = line.split_off(cursor.index);
|
||||
cursor.line += 1;
|
||||
lines.insert(cursor.line, new);
|
||||
cursor.index = 0;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn backspace(&mut self) {
|
||||
if let Some(cursor) = &mut self.text.cursor
|
||||
&& (cursor.index != 0 || cursor.line != 0)
|
||||
{
|
||||
self.motion(Motion::Left);
|
||||
self.delete();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn delete(&mut self) {
|
||||
if let Some(cursor) = &mut self.text.cursor {
|
||||
let lines = &mut self.text.view.buf.lines;
|
||||
let line = &mut lines[cursor.line];
|
||||
if cursor.index == line.text().len() {
|
||||
if cursor.line == lines.len() - 1 {
|
||||
return;
|
||||
}
|
||||
let add = lines.remove(cursor.line + 1).into_text();
|
||||
let line = &mut lines[cursor.line];
|
||||
let mut cur = line.text().to_string();
|
||||
cur.push_str(&add);
|
||||
line.set_text(cur, line.ending(), line.attrs_list().clone());
|
||||
} else {
|
||||
let mut text = line.text().to_string();
|
||||
text.remove(cursor.index);
|
||||
line.set_text(text, line.ending(), line.attrs_list().clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn select(&mut self, pos: Vec2, size: Vec2) {
|
||||
let pos = pos - self.text.region().top_left.to_size(size);
|
||||
self.text.cursor = self.text.buf.hit(pos.x, pos.y);
|
||||
}
|
||||
|
||||
pub fn deselect(&mut self) {
|
||||
self.text.cursor = None;
|
||||
}
|
||||
|
||||
pub fn apply_event(&mut self, event: &KeyEvent, modifiers: &Modifiers) -> TextInputResult {
|
||||
match &event.logical_key {
|
||||
Key::Named(named) => match named {
|
||||
NamedKey::Backspace => self.backspace(),
|
||||
NamedKey::Delete => self.delete(),
|
||||
NamedKey::Space => self.insert(" "),
|
||||
NamedKey::Enter => {
|
||||
if modifiers.shift {
|
||||
self.newline();
|
||||
} else {
|
||||
return TextInputResult::Submit;
|
||||
}
|
||||
}
|
||||
NamedKey::ArrowRight => self.motion(Motion::Right),
|
||||
NamedKey::ArrowLeft => self.motion(Motion::Left),
|
||||
NamedKey::ArrowUp => self.motion(Motion::Up),
|
||||
NamedKey::ArrowDown => self.motion(Motion::Down),
|
||||
NamedKey::Escape => {
|
||||
self.deselect();
|
||||
return TextInputResult::Unfocus;
|
||||
}
|
||||
_ => return TextInputResult::Unused,
|
||||
},
|
||||
Key::Character(text) => {
|
||||
if modifiers.control && text == "v" {
|
||||
return TextInputResult::Paste;
|
||||
} else {
|
||||
self.insert(text)
|
||||
}
|
||||
}
|
||||
_ => return TextInputResult::Unused,
|
||||
}
|
||||
TextInputResult::Used
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct Modifiers {
|
||||
pub shift: bool,
|
||||
pub control: bool,
|
||||
}
|
||||
|
||||
impl Modifiers {
|
||||
pub fn clear(&mut self) {
|
||||
self.shift = false;
|
||||
self.control = false;
|
||||
}
|
||||
}
|
||||
|
||||
pub enum TextInputResult {
|
||||
Used,
|
||||
Unused,
|
||||
Unfocus,
|
||||
Submit,
|
||||
Paste,
|
||||
}
|
||||
|
||||
impl TextInputResult {
|
||||
pub fn unfocus(&self) -> bool {
|
||||
matches!(self, TextInputResult::Unfocus)
|
||||
}
|
||||
}
|
||||
|
||||
impl Deref for TextEdit {
|
||||
type Target = TextView;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.view
|
||||
}
|
||||
}
|
||||
|
||||
impl DerefMut for TextEdit {
|
||||
fn deref_mut(&mut self) -> &mut Self::Target {
|
||||
&mut self.view
|
||||
}
|
||||
}
|
||||
130
src/core/text/mod.rs
Normal file
130
src/core/text/mod.rs
Normal file
@@ -0,0 +1,130 @@
|
||||
mod build;
|
||||
mod edit;
|
||||
|
||||
pub use build::*;
|
||||
pub use edit::*;
|
||||
|
||||
use crate::{prelude::*, util::MutDetect};
|
||||
use cosmic_text::{Attrs, Metrics, Shaping};
|
||||
use std::ops::{Deref, DerefMut};
|
||||
|
||||
pub struct Text {
|
||||
pub content: MutDetect<String>,
|
||||
view: TextView,
|
||||
}
|
||||
|
||||
pub struct TextView {
|
||||
pub attrs: MutDetect<TextAttrs>,
|
||||
pub buf: MutDetect<TextBuffer>,
|
||||
// cache
|
||||
tex: Option<TextTexture>,
|
||||
width: Option<f32>,
|
||||
}
|
||||
|
||||
impl TextView {
|
||||
pub fn new(buf: TextBuffer, attrs: TextAttrs) -> Self {
|
||||
Self {
|
||||
attrs: attrs.into(),
|
||||
buf: buf.into(),
|
||||
tex: None,
|
||||
width: None,
|
||||
}
|
||||
}
|
||||
pub fn draw(&mut self, ctx: &mut SizeCtx) -> TextTexture {
|
||||
let width = if self.attrs.wrap {
|
||||
Some(ctx.px_size().x)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if width == self.width
|
||||
&& let Some(tex) = &self.tex
|
||||
&& !self.attrs.changed
|
||||
&& !self.buf.changed
|
||||
{
|
||||
return tex.clone();
|
||||
}
|
||||
self.width = width;
|
||||
let font_system = &mut ctx.text.font_system;
|
||||
self.attrs.apply(font_system, &mut self.buf, width);
|
||||
self.buf.shape_until_scroll(font_system, false);
|
||||
let tex = ctx.draw_text(&mut self.buf, &self.attrs);
|
||||
self.tex = Some(tex.clone());
|
||||
self.attrs.changed = false;
|
||||
self.buf.changed = false;
|
||||
tex
|
||||
}
|
||||
pub fn tex(&self) -> Option<&TextTexture> {
|
||||
self.tex.as_ref()
|
||||
}
|
||||
}
|
||||
|
||||
impl Text {
|
||||
pub fn new(content: impl Into<String>) -> Self {
|
||||
let attrs = TextAttrs::default();
|
||||
let buf = TextBuffer::new_empty(Metrics::new(attrs.font_size, attrs.line_height));
|
||||
Self {
|
||||
content: content.into().into(),
|
||||
view: TextView::new(buf, attrs),
|
||||
}
|
||||
}
|
||||
fn update_buf(&mut self, ctx: &mut SizeCtx) -> TextTexture {
|
||||
if self.content.changed {
|
||||
self.content.changed = false;
|
||||
self.view.buf.set_text(
|
||||
&mut ctx.text.font_system,
|
||||
&self.content,
|
||||
&Attrs::new().family(self.view.attrs.family),
|
||||
Shaping::Advanced,
|
||||
);
|
||||
}
|
||||
self.view.draw(ctx)
|
||||
}
|
||||
}
|
||||
|
||||
impl Widget for Text {
|
||||
fn draw(&mut self, painter: &mut Painter) {
|
||||
let tex = self.update_buf(&mut painter.size_ctx());
|
||||
let region = text_region(&tex, self.align);
|
||||
painter.texture_within(&tex.handle, region);
|
||||
}
|
||||
|
||||
fn desired_size(&mut self, ctx: &mut SizeCtx) -> UiVec2 {
|
||||
UiVec2::abs(self.update_buf(ctx).size())
|
||||
}
|
||||
}
|
||||
|
||||
pub fn text_region(tex: &TextTexture, align: Align) -> UiRegion {
|
||||
let tex_dims = tex.handle.size();
|
||||
let mut region = UiRegion::from_size_align(tex.size(), align);
|
||||
region.top_left.abs += tex.top_left;
|
||||
region.bot_right.abs = region.top_left.abs + tex_dims;
|
||||
region
|
||||
}
|
||||
|
||||
impl Deref for Text {
|
||||
type Target = TextAttrs;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.view
|
||||
}
|
||||
}
|
||||
|
||||
impl DerefMut for Text {
|
||||
fn deref_mut(&mut self) -> &mut Self::Target {
|
||||
&mut self.view
|
||||
}
|
||||
}
|
||||
|
||||
impl Deref for TextView {
|
||||
type Target = TextAttrs;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.attrs
|
||||
}
|
||||
}
|
||||
|
||||
impl DerefMut for TextView {
|
||||
fn deref_mut(&mut self) -> &mut Self::Target {
|
||||
&mut self.attrs
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user