New TextMetrics type

This commit is contained in:
Jeremy Soller 2022-10-18 17:04:22 -06:00
parent fa8ed07dab
commit de572b1645
No known key found for this signature in database
GPG key ID: 87F211AF2BE4C2FE
4 changed files with 103 additions and 116 deletions

View file

@ -7,10 +7,8 @@ use cosmic::{
Element, Element,
Theme, Theme,
widget::{ widget::{
container,
column, column,
pick_list, pick_list,
radio,
row, row,
text, text,
}, },
@ -21,6 +19,7 @@ use cosmic_text::{
FontMatches, FontMatches,
FontSystem, FontSystem,
TextBuffer, TextBuffer,
TextMetrics,
}; };
use std::{ use std::{
env, env,
@ -39,35 +38,13 @@ lazy_static::lazy_static! {
//TODO: find out how to do this! //TODO: find out how to do this!
static mut FONT_MATCHES: Option<FontMatches<'static>> = None; static mut FONT_MATCHES: Option<FontMatches<'static>> = None;
#[derive(Clone, Copy, Debug, Eq, PartialEq)] static FONT_SIZES: &'static [TextMetrics] = &[
pub struct FontMetrics { TextMetrics::new(10, 14), // Caption
pub font_size: i32, TextMetrics::new(14, 20), // Body
pub line_height: i32, TextMetrics::new(20, 28), // Title 4
} TextMetrics::new(24, 32), // Title 3
TextMetrics::new(28, 36), // Title 2
impl fmt::Display for FontMetrics { TextMetrics::new(32, 44), // Title 1
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
//TODO: should line height also be shown?
write!(f, "{}", self.font_size)
}
}
impl FontMetrics {
pub const fn new(font_size: i32, line_height: i32) -> Self {
Self {
font_size,
line_height,
}
}
}
static FONT_SIZES: &'static [FontMetrics] = &[
FontMetrics::new(10, 14), // Caption
FontMetrics::new(14, 20), // Body
FontMetrics::new(20, 28), // Title 4
FontMetrics::new(24, 32), // Title 3
FontMetrics::new(28, 36), // Title 2
FontMetrics::new(32, 44), // Title 1
]; ];
fn main() -> cosmic::iced::Result { fn main() -> cosmic::iced::Result {
@ -118,7 +95,7 @@ pub struct Window {
#[allow(dead_code)] #[allow(dead_code)]
#[derive(Clone, Copy, Debug)] #[derive(Clone, Copy, Debug)]
pub enum Message { pub enum Message {
FontSize(FontMetrics), MetricsChanged(TextMetrics),
ThemeChanged(&'static str), ThemeChanged(&'static str),
} }
@ -143,10 +120,7 @@ impl Application for Window {
let buffer = Arc::new(Mutex::new(TextBuffer::new( let buffer = Arc::new(Mutex::new(TextBuffer::new(
unsafe { FONT_MATCHES.as_ref().unwrap() }, unsafe { FONT_MATCHES.as_ref().unwrap() },
&text, &text,
FONT_SIZES[font_size_i].font_size, FONT_SIZES[font_size_i],
FONT_SIZES[font_size_i].line_height,
0,
0
))); )));
let window = Window { let window = Window {
@ -167,9 +141,9 @@ impl Application for Window {
fn update(&mut self, message: Message) -> iced::Command<Self::Message> { fn update(&mut self, message: Message) -> iced::Command<Self::Message> {
match message { match message {
Message::FontSize(font_metrics) => { Message::MetricsChanged(metrics) => {
let mut buffer = self.buffer.lock().unwrap(); let mut buffer = self.buffer.lock().unwrap();
buffer.set_font_metrics(font_metrics.font_size, font_metrics.line_height); buffer.set_metrics(metrics);
}, },
Message::ThemeChanged(theme) => match theme { Message::ThemeChanged(theme) => match theme {
"Dark" => self.theme = Theme::Dark, "Dark" => self.theme = Theme::Dark,
@ -196,8 +170,8 @@ impl Application for Window {
let buffer = self.buffer.lock().unwrap(); let buffer = self.buffer.lock().unwrap();
pick_list( pick_list(
FONT_SIZES, FONT_SIZES,
Some(FontMetrics::new(buffer.font_size(), buffer.line_height())), Some(buffer.metrics()),
Message::FontSize Message::MetricsChanged
) )
}; };

View file

@ -116,8 +116,8 @@ where
let buffer = self.buffer.lock().unwrap(); let buffer = self.buffer.lock().unwrap();
let font_size = buffer.font_size(); let font_size = buffer.metrics().font_size;
let line_height = buffer.line_height(); let line_height = buffer.metrics().line_height;
let instant = Instant::now(); let instant = Instant::now();

View file

@ -1,4 +1,4 @@
use cosmic_text::{FontLineIndex, FontSystem, TextAction, TextBuffer, TextCursor}; use cosmic_text::{FontLineIndex, FontSystem, TextAction, TextBuffer, TextCursor, TextMetrics};
use orbclient::{Color, EventOption, Renderer, Window, WindowFlag}; use orbclient::{Color, EventOption, Renderer, Window, WindowFlag};
use std::{cmp, env, fs, time::Instant}; use std::{cmp, env, fs, time::Instant};
@ -61,12 +61,12 @@ fn main() {
let bg_color = Color::rgb(0x34, 0x34, 0x34); let bg_color = Color::rgb(0x34, 0x34, 0x34);
let font_color = Color::rgb(0xFF, 0xFF, 0xFF); let font_color = Color::rgb(0xFF, 0xFF, 0xFF);
let font_sizes = [ let font_sizes = [
(10, 14), // Caption TextMetrics::new(10, 14).scale(display_scale), // Caption
(14, 20), // Body TextMetrics::new(14, 20).scale(display_scale), // Body
(20, 28), // Title 4 TextMetrics::new(20, 28).scale(display_scale), // Title 4
(24, 32), // Title 3 TextMetrics::new(24, 32).scale(display_scale), // Title 3
(28, 36), // Title 2 TextMetrics::new(28, 36).scale(display_scale), // Title 2
(32, 44), // Title 1 TextMetrics::new(32, 44).scale(display_scale), // Title 1
]; ];
let font_size_default = 1; // Body let font_size_default = 1; // Body
let mut font_size_i = font_size_default; let mut font_size_i = font_size_default;
@ -85,8 +85,9 @@ fn main() {
let mut buffer = TextBuffer::new( let mut buffer = TextBuffer::new(
&font_matches, &font_matches,
&text, &text,
font_sizes[font_size_i].0 * display_scale, font_sizes[font_size_i]
font_sizes[font_size_i].1 * display_scale, );
buffer.set_size(
window.width() as i32 - line_x * 2, window.width() as i32 - line_x * 2,
window.height() as i32 window.height() as i32
); );
@ -97,8 +98,8 @@ fn main() {
let mut mouse_left = false; let mut mouse_left = false;
let mut rehit = false; let mut rehit = false;
loop { loop {
let font_size = buffer.font_size(); let font_size = buffer.metrics().font_size;
let line_height = buffer.line_height(); let line_height = buffer.metrics().line_height;
if rehit { if rehit {
let instant = Instant::now(); let instant = Instant::now();
@ -252,27 +253,18 @@ fn main() {
orbclient::K_PGDN if event.pressed => buffer.action(TextAction::PageDown), orbclient::K_PGDN if event.pressed => buffer.action(TextAction::PageDown),
orbclient::K_0 if event.pressed && ctrl_pressed => { orbclient::K_0 if event.pressed && ctrl_pressed => {
font_size_i = font_size_default; font_size_i = font_size_default;
buffer.set_font_metrics( buffer.set_metrics(font_sizes[font_size_i]);
font_sizes[font_size_i].0 * display_scale,
font_sizes[font_size_i].1 * display_scale,
);
}, },
orbclient::K_MINUS if event.pressed && ctrl_pressed => { orbclient::K_MINUS if event.pressed && ctrl_pressed => {
if font_size_i > 0 { if font_size_i > 0 {
font_size_i -= 1; font_size_i -= 1;
buffer.set_font_metrics( buffer.set_metrics(font_sizes[font_size_i]);
font_sizes[font_size_i].0 * display_scale,
font_sizes[font_size_i].1 * display_scale,
);
} }
}, },
orbclient::K_EQUALS if event.pressed && ctrl_pressed => { orbclient::K_EQUALS if event.pressed && ctrl_pressed => {
if font_size_i + 1 < font_sizes.len() { if font_size_i + 1 < font_sizes.len() {
font_size_i += 1; font_size_i += 1;
buffer.set_font_metrics( buffer.set_metrics(font_sizes[font_size_i]);
font_sizes[font_size_i].0 * display_scale,
font_sizes[font_size_i].1 * display_scale,
);
} }
}, },
orbclient::K_D if event.pressed && ctrl_pressed => { orbclient::K_D if event.pressed && ctrl_pressed => {

View file

@ -1,10 +1,12 @@
use std::{ use std::{
cmp, cmp,
fmt,
time::Instant, time::Instant,
}; };
use crate::{FontLayoutLine, FontLineIndex, FontMatches, FontShapeLine}; use crate::{FontLayoutLine, FontLineIndex, FontMatches, FontShapeLine};
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum TextAction { pub enum TextAction {
Left, Left,
Right, Right,
@ -15,28 +17,53 @@ pub enum TextAction {
PageUp, PageUp,
PageDown, PageDown,
Insert(char), Insert(char),
Click { x: i32, y: i32 },
Scroll(i32), Scroll(i32),
} }
#[derive(Default, Eq, PartialEq)] #[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct TextCursor { pub struct TextCursor {
pub line: usize, pub line: usize,
pub glyph: usize, pub glyph: usize,
} }
impl TextCursor { impl TextCursor {
pub fn new(line: usize, glyph: usize) -> Self { pub const fn new(line: usize, glyph: usize) -> Self {
Self { line, glyph } Self { line, glyph }
} }
} }
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct TextMetrics {
pub font_size: i32,
pub line_height: i32,
}
impl TextMetrics {
pub const fn new(font_size: i32, line_height: i32) -> Self {
Self { font_size, line_height }
}
pub const fn scale(self, scale: i32) -> Self {
Self {
font_size: self.font_size * scale,
line_height: self.line_height * scale,
}
}
}
impl fmt::Display for TextMetrics {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}px / {}px", self.font_size, self.line_height)
}
}
pub struct TextBuffer<'a> { pub struct TextBuffer<'a> {
font_matches: &'a FontMatches<'a>, font_matches: &'a FontMatches<'a>,
text_lines: Vec<String>, text_lines: Vec<String>,
shape_lines: Vec<FontShapeLine<'a>>, shape_lines: Vec<FontShapeLine<'a>>,
layout_lines: Vec<FontLayoutLine<'a>>, layout_lines: Vec<FontLayoutLine<'a>>,
font_size: i32, metrics: TextMetrics,
line_height: i32,
width: i32, width: i32,
height: i32, height: i32,
scroll: i32, scroll: i32,
@ -48,32 +75,27 @@ impl<'a> TextBuffer<'a> {
pub fn new( pub fn new(
font_matches: &'a FontMatches<'a>, font_matches: &'a FontMatches<'a>,
text: &str, text: &str,
font_size: i32, metrics: TextMetrics,
line_height: i32,
width: i32,
height: i32,
) -> Self { ) -> Self {
let mut text_lines: Vec<String> = text.lines().map(String::from).collect(); let mut text_lines: Vec<String> = text.lines().map(String::from).collect();
if text_lines.is_empty() { if text_lines.is_empty() {
text_lines.push(String::new()); text_lines.push(String::new());
} }
let mut buffer = Self { Self {
font_matches, font_matches,
text_lines, text_lines,
shape_lines: Vec::new(), shape_lines: Vec::new(),
layout_lines: Vec::new(), layout_lines: Vec::new(),
font_size, metrics,
line_height, width: 0,
width, height: 0,
height, scroll: 0,
cursor: TextCursor::default(), cursor: TextCursor::default(),
redraw: false, redraw: false,
scroll: 0, }
};
buffer.shape_until_scroll();
buffer
} }
///TODO: do not allow access
pub fn shape_until(&mut self, lines: i32) { pub fn shape_until(&mut self, lines: i32) {
let instant = Instant::now(); let instant = Instant::now();
@ -92,7 +114,7 @@ impl<'a> TextBuffer<'a> {
} }
} }
pub fn shape_until_scroll(&mut self) { fn shape_until_scroll(&mut self) {
let lines = self.lines(); let lines = self.lines();
let scroll_end = self.scroll + lines; let scroll_end = self.scroll + lines;
@ -107,7 +129,7 @@ impl<'a> TextBuffer<'a> {
); );
} }
pub fn reshape_line(&mut self, line_i: FontLineIndex) { fn reshape_line(&mut self, line_i: FontLineIndex) {
let instant = Instant::now(); let instant = Instant::now();
let shape_line = self let shape_line = self
@ -125,14 +147,14 @@ impl<'a> TextBuffer<'a> {
self.relayout_line(line_i); self.relayout_line(line_i);
} }
pub fn relayout(&mut self) { fn relayout(&mut self) {
let instant = Instant::now(); let instant = Instant::now();
self.layout_lines.clear(); self.layout_lines.clear();
for line in self.shape_lines.iter() { for line in self.shape_lines.iter() {
let layout_i = self.layout_lines.len(); let layout_i = self.layout_lines.len();
line.layout( line.layout(
self.font_size, self.metrics.font_size,
self.width, self.width,
&mut self.layout_lines, &mut self.layout_lines,
layout_i, layout_i,
@ -145,7 +167,7 @@ impl<'a> TextBuffer<'a> {
log::debug!("relayout: {:?}", duration); log::debug!("relayout: {:?}", duration);
} }
pub fn relayout_line(&mut self, line_i: FontLineIndex) { fn relayout_line(&mut self, line_i: FontLineIndex) {
let instant = Instant::now(); let instant = Instant::now();
let mut insert_opt = None; let mut insert_opt = None;
@ -166,7 +188,7 @@ impl<'a> TextBuffer<'a> {
let shape_line = &self.shape_lines[line_i.get()]; let shape_line = &self.shape_lines[line_i.get()];
shape_line.layout( shape_line.layout(
self.font_size, self.metrics.font_size,
self.width, self.width,
&mut self.layout_lines, &mut self.layout_lines,
insert_i, insert_i,
@ -182,43 +204,26 @@ impl<'a> TextBuffer<'a> {
&self.font_matches &self.font_matches
} }
pub fn font_size(&self) -> i32 { /// Get the current [TextMetrics]
self.font_size pub fn metrics(&self) -> TextMetrics {
self.metrics
} }
pub fn line_height(&self) -> i32 { /// Set the current [TextMetrics]
self.line_height pub fn set_metrics(&mut self, metrics: TextMetrics) {
} if metrics != self.metrics {
self.metrics = metrics;
pub fn set_font_metrics(&mut self, font_size: i32, line_height: i32) {
if font_size != self.font_size {
self.font_size = font_size;
self.relayout(); self.relayout();
self.shape_until_scroll(); self.shape_until_scroll();
} }
if line_height != self.line_height {
self.line_height = line_height;
self.shape_until_scroll();
}
} }
pub fn width(&self) -> i32 { /// Get the current buffer dimensions (width, height)
self.width pub fn size(&self) -> (i32, i32) {
} (self.width, self.height)
pub fn height(&self) -> i32 {
self.height
}
pub fn scroll(&self) -> i32 {
self.scroll
}
pub fn lines(&self) -> i32 {
self.height / self.line_height
} }
/// Set the current buffer dimensions
pub fn set_size(&mut self, width: i32, height: i32) { pub fn set_size(&mut self, width: i32, height: i32) {
if width != self.width { if width != self.width {
self.width = width; self.width = width;
@ -232,14 +237,27 @@ impl<'a> TextBuffer<'a> {
} }
} }
/// Get the current scroll location
pub fn scroll(&self) -> i32 {
self.scroll
}
/// Get the number of lines that can be viewed in the buffer
pub fn lines(&self) -> i32 {
self.height / self.metrics.line_height
}
/// Get the lines after layout for rendering
pub fn layout_lines(&self) -> &[FontLayoutLine] { pub fn layout_lines(&self) -> &[FontLayoutLine] {
&self.layout_lines &self.layout_lines
} }
/// Get the lines of the original text
pub fn text_lines(&self) -> &[String] { pub fn text_lines(&self) -> &[String] {
&self.text_lines &self.text_lines
} }
/// Perform a [TextAction] on the buffer
pub fn action(&mut self, action: TextAction) { pub fn action(&mut self, action: TextAction) {
match action { match action {
TextAction::Left => { TextAction::Left => {
@ -349,6 +367,9 @@ impl<'a> TextBuffer<'a> {
self.cursor.glyph += 1; self.cursor.glyph += 1;
self.reshape_line(line.line_i); self.reshape_line(line.line_i);
} }
},
TextAction::Click { x, y } => {
}, },
TextAction::Scroll(lines) => { TextAction::Scroll(lines) => {
self.scroll += lines; self.scroll += lines;