Improvements to syntax editor, integrate with libcosmic editor

This commit is contained in:
Jeremy Soller 2022-11-09 10:44:51 -07:00
parent 1663bfc96c
commit bbe7d77b7b
No known key found for this signature in database
GPG key ID: 87F211AF2BE4C2FE
9 changed files with 386 additions and 69 deletions

View file

@ -7,7 +7,7 @@ license = "MIT OR Apache-2.0"
publish = false
[dependencies]
cosmic-text = { path = "../../" }
cosmic-text = { path = "../../", features = ["syntect"] }
env_logger = "0.9"
fontdb = "0.9"
lazy_static = "1.4"

View file

@ -27,9 +27,10 @@ use cosmic_text::{
Attrs,
AttrsList,
Buffer,
Editor,
FontSystem,
Metrics,
SyntaxEditor,
SyntaxSystem,
};
use std::{
env,
@ -38,6 +39,9 @@ use std::{
sync::Mutex,
};
use self::syntax_text_box::syntax_text_box;
mod syntax_text_box;
use self::text::text;
mod text;
@ -46,6 +50,7 @@ mod text_box;
lazy_static::lazy_static! {
static ref FONT_SYSTEM: FontSystem = FontSystem::new();
static ref SYNTAX_SYSTEM: SyntaxSystem = SyntaxSystem::new();
}
static FONT_SIZES: &'static [Metrics] = &[
@ -69,7 +74,7 @@ pub struct Window {
theme: Theme,
path_opt: Option<PathBuf>,
attrs: Attrs<'static>,
editor: Mutex<Editor<'static>>,
editor: Mutex<SyntaxEditor<'static>>,
}
#[allow(dead_code)]
@ -87,15 +92,13 @@ pub enum Message {
impl Window {
pub fn open(&mut self, path: PathBuf) {
let mut editor = self.editor.lock().unwrap();
match fs::read_to_string(&path) {
Ok(text) => {
match editor.load_text(&path, self.attrs) {
Ok(()) => {
log::info!("opened '{}'", path.display());
editor.buffer.set_text(&text, self.attrs);
self.path_opt = Some(path);
},
Err(err) => {
log::error!("failed to open '{}': {}", path.display(), err);
editor.buffer.set_text("", self.attrs);
self.path_opt = None;
}
}
@ -113,10 +116,11 @@ impl Application for Window {
.monospaced(true)
.family(cosmic_text::Family::Monospace);
let mut editor = Editor::new(Buffer::new(
&FONT_SYSTEM,
FONT_SIZES[1 /* Body */],
));
let mut editor = SyntaxEditor::new(
Buffer::new(&FONT_SYSTEM, FONT_SIZES[1 /* Body */]),
&SYNTAX_SYSTEM,
"base16-eighties.dark"
).unwrap();
update_attrs(&mut editor, attrs);
let mut window = Window {
@ -154,7 +158,7 @@ impl Application for Window {
if let Some(path) = &self.path_opt {
let editor = self.editor.lock().unwrap();
let mut text = String::new();
for line in editor.buffer.lines.iter() {
for line in editor.buffer().lines.iter() {
text.push_str(line.text());
text.push('\n');
}
@ -202,7 +206,7 @@ impl Application for Window {
},
Message::MetricsChanged(metrics) => {
let mut editor = self.editor.lock().unwrap();
editor.buffer.set_metrics(metrics);
editor.buffer_mut().set_metrics(metrics);
},
Message::ThemeChanged(theme) => {
self.theme = match theme {
@ -238,7 +242,7 @@ impl Application for Window {
let editor = self.editor.lock().unwrap();
pick_list(
FONT_SIZES,
Some(editor.buffer.metrics()),
Some(editor.buffer().metrics()),
Message::MetricsChanged
)
};
@ -262,7 +266,7 @@ impl Application for Window {
.align_items(Alignment::Center)
.spacing(8)
,
text_box(&self.editor)
syntax_text_box(&self.editor)
]
.spacing(8)
.padding(16)
@ -273,8 +277,8 @@ impl Application for Window {
}
}
fn update_attrs<'a>(editor: &mut Editor<'a>, attrs: Attrs<'a>) {
editor.buffer.lines.iter_mut().for_each(|line| {
fn update_attrs<'a>(editor: &mut SyntaxEditor<'a>, attrs: Attrs<'a>) {
editor.buffer_mut().lines.iter_mut().for_each(|line| {
line.set_attrs_list(AttrsList::new(attrs));
});
}

View file

@ -0,0 +1,296 @@
// SPDX-License-Identifier: MIT OR Apache-2.0
use cosmic::{
iced_native::{
{Color, Element, Length, Point, Rectangle, Shell, Size},
clipboard::Clipboard,
event::{Event, Status},
image,
keyboard::{Event as KeyEvent, KeyCode},
layout::{self, Layout},
mouse::{self, Button, Event as MouseEvent, ScrollDelta},
renderer,
widget::{self, tree, Widget},
},
};
use cosmic_text::{
Action,
SyntaxEditor,
SwashCache,
};
use std::{
cmp,
sync::Mutex,
time::Instant,
};
use super::text;
pub struct SyntaxTextBox<'a> {
editor: &'a Mutex<SyntaxEditor<'static>>,
}
impl<'a> SyntaxTextBox<'a> {
pub fn new(editor: &'a Mutex<SyntaxEditor<'static>>) -> Self {
Self {
editor,
}
}
}
pub fn syntax_text_box<'a>(editor: &'a Mutex<SyntaxEditor<'static>>) -> SyntaxTextBox<'a> {
SyntaxTextBox::new(editor)
}
impl<'a, Message, Renderer> Widget<Message, Renderer> for SyntaxTextBox<'a>
where
Renderer: renderer::Renderer + image::Renderer<Handle = image::Handle>,
{
fn tag(&self) -> tree::Tag {
tree::Tag::of::<State>()
}
fn state(&self) -> tree::State {
tree::State::new(State::new())
}
fn width(&self) -> Length {
Length::Fill
}
fn height(&self) -> Length {
Length::Fill
}
fn layout(
&self,
_renderer: &Renderer,
limits: &layout::Limits,
) -> layout::Node {
let limits = limits.width(Length::Fill).height(Length::Fill);
//TODO: allow lazy shape
let mut editor = self.editor.lock().unwrap();
editor.buffer_mut().shape_until(i32::max_value());
let mut layout_lines = 0;
for line in editor.buffer().lines.iter() {
match line.layout_opt() {
Some(layout) => layout_lines += layout.len(),
None => (),
}
}
let height = layout_lines as f32 * editor.buffer().metrics().line_height as f32;
let size = Size::new(limits.max().width, height);
log::info!("size {:?}", size);
layout::Node::new(limits.resolve(size))
}
fn mouse_interaction(
&self,
_tree: &widget::Tree,
layout: Layout<'_>,
cursor_position: Point,
_viewport: &Rectangle,
_renderer: &Renderer,
) -> mouse::Interaction {
if layout.bounds().contains(cursor_position) {
mouse::Interaction::Text
} else {
mouse::Interaction::Idle
}
}
fn draw(
&self,
tree: &widget::Tree,
renderer: &mut Renderer,
_theme: &Renderer::Theme,
_style: &renderer::Style,
layout: Layout<'_>,
_cursor_position: Point,
viewport: &Rectangle,
) {
let state = tree.state.downcast_ref::<State>();
let mut editor = self.editor.lock().unwrap();
let view_w = cmp::min(viewport.width as i32, layout.bounds().width as i32);
let view_h = cmp::min(viewport.height as i32, layout.bounds().height as i32);
editor.buffer_mut().set_size(view_w, view_h);
editor.shape_as_needed();
let instant = Instant::now();
let mut pixels = vec![0; view_w as usize * view_h as usize * 4];
editor.draw(&mut state.cache.lock().unwrap(), |x, y, w, h, color| {
if w <= 0 || h <= 0 {
// Do not draw invalid sized rectangles
return;
}
if w > 1 || h > 1 {
// Draw rectangles with optimized quad renderer
renderer.fill_quad(
renderer::Quad {
bounds: Rectangle::new(
Point::new(layout.position().x + x as f32, layout.position().y + y as f32),
Size::new(w as f32, h as f32)
),
border_radius: 0.0,
border_width: 0.0,
border_color: Color::TRANSPARENT,
},
Color::from_rgba8(
color.r(),
color.g(),
color.b(),
(color.a() as f32) / 255.0
)
);
} else {
text::draw_pixel(&mut pixels, view_w, view_h, x, y, color);
}
});
let handle = image::Handle::from_pixels(view_w as u32, view_h as u32, pixels);
image::Renderer::draw(renderer, handle, Rectangle::new(
layout.position(),
Size::new(view_w as f32, view_h as f32)
));
let duration = instant.elapsed();
log::debug!("redraw {}, {}: {:?}", view_w, view_h, duration);
}
fn on_event(
&mut self,
tree: &mut widget::Tree,
event: Event,
layout: Layout<'_>,
cursor_position: Point,
_renderer: &Renderer,
_clipboard: &mut dyn Clipboard,
_shell: &mut Shell<'_, Message>,
) -> Status {
let state = tree.state.downcast_mut::<State>();
let mut editor = self.editor.lock().unwrap();
let mut status = Status::Ignored;
match event {
Event::Keyboard(KeyEvent::KeyPressed { key_code, modifiers }) => match key_code {
KeyCode::Left => {
editor.action(Action::Left);
status = Status::Captured;
},
KeyCode::Right => {
editor.action(Action::Right);
status = Status::Captured;
},
KeyCode::Up => {
editor.action(Action::Up);
status = Status::Captured;
},
KeyCode::Down => {
editor.action(Action::Down);
status = Status::Captured;
},
KeyCode::Home => {
editor.action(Action::Home);
status = Status::Captured;
},
KeyCode::End => {
editor.action(Action::End);
status = Status::Captured;
},
KeyCode::PageUp => {
editor.action(Action::PageUp);
status = Status::Captured;
},
KeyCode::PageDown => {
editor.action(Action::PageDown);
status = Status::Captured;
},
KeyCode::Enter => {
editor.action(Action::Enter);
status = Status::Captured;
},
KeyCode::Backspace => {
editor.action(Action::Backspace);
status = Status::Captured;
},
KeyCode::Delete => {
editor.action(Action::Delete);
status = Status::Captured;
},
_ => ()
},
Event::Keyboard(KeyEvent::CharacterReceived(character)) => {
editor.action(Action::Insert(character));
status = Status::Captured;
},
Event::Mouse(MouseEvent::ButtonPressed(Button::Left)) => {
if layout.bounds().contains(cursor_position) {
editor.action(Action::Click {
x: (cursor_position.x - layout.bounds().x) as i32,
y: (cursor_position.y - layout.bounds().y) as i32,
});
state.is_dragging = true;
status = Status::Captured;
}
},
Event::Mouse(MouseEvent::ButtonReleased(Button::Left)) => {
state.is_dragging = false;
status = Status::Captured;
},
Event::Mouse(MouseEvent::CursorMoved { .. }) => {
if state.is_dragging {
editor.action(Action::Drag {
x: (cursor_position.x - layout.bounds().x) as i32,
y: (cursor_position.y - layout.bounds().y) as i32,
});
status = Status::Captured;
}
},
Event::Mouse(MouseEvent::WheelScrolled { delta }) => match delta {
ScrollDelta::Lines { x, y } => {
editor.action(Action::Scroll {
lines: (-y * 6.0) as i32,
});
status = Status::Captured;
},
_ => (),
},
_ => ()
}
status
}
}
impl<'a, Message, Renderer> From<SyntaxTextBox<'a>> for Element<'a, Message, Renderer>
where
Renderer: renderer::Renderer + image::Renderer<Handle = image::Handle>,
{
fn from(text_box: SyntaxTextBox<'a>) -> Self {
Self::new(text_box)
}
}
pub struct State {
is_dragging: bool,
cache: Mutex<SwashCache<'static>>,
}
impl State {
/// Creates a new [`State`].
pub fn new() -> State {
State {
is_dragging: false,
cache: Mutex::new(SwashCache::new(&crate::FONT_SYSTEM)),
}
}
}

View file

@ -3,7 +3,7 @@
use cosmic_text::{
Action,
Attrs,
Color,
Buffer,
Family,
FontSystem,
Metrics,
@ -46,7 +46,7 @@ fn main() {
let font_system = FontSystem::new();
let syntax_system = SyntaxSystem::new(&font_system);
let syntax_system = SyntaxSystem::new();
let font_sizes = [
Metrics::new(10, 14).scale(display_scale), // Caption
@ -61,8 +61,8 @@ fn main() {
let line_x = 8 * display_scale;
let mut editor = SyntaxEditor::new(
Buffer::new(&font_system, font_sizes[font_size_i]),
&syntax_system,
font_sizes[font_size_i],
"base16-eighties.dark"
).unwrap();
@ -81,27 +81,6 @@ fn main() {
}
}
let mut bg_color = orbclient::Color::rgb(0x00, 0x00, 0x00);
let mut font_color = Color::rgb(0xFF, 0xFF, 0xFF);
if let Some(background) = editor.theme.settings.background {
bg_color = orbclient::Color::rgba(
background.r,
background.g,
background.b,
background.a,
);
}
if let Some(foreground) = editor.theme.settings.foreground {
font_color = Color::rgba(
foreground.r,
foreground.g,
foreground.b,
foreground.a,
);
}
let mut swash_cache = SwashCache::new(&font_system);
let mut ctrl_pressed = false;
@ -113,9 +92,10 @@ fn main() {
if editor.buffer_mut().redraw {
let instant = Instant::now();
window.set(bg_color);
let bg = editor.background_color();
window.set(orbclient::Color::rgb(bg.r(), bg.g(), bg.b()));
editor.draw(&mut swash_cache, font_color, |x, y, w, h, color| {
editor.draw(&mut swash_cache, |x, y, w, h, color| {
window.rect(line_x + x, y, w, h, orbclient::Color { data: color.0 })
});

View file

@ -145,8 +145,9 @@ impl fmt::Display for Metrics {
/// A buffer of text that is shaped and laid out
pub struct Buffer<'a> {
font_system: &'a FontSystem,
/// Lines (or paragraphs) of text in the buffer
/// The [FontSystem] used by this [Buffer]
pub font_system: &'a FontSystem,
/// [BufferLine]s (or paragraphs) of text in the buffer
pub lines: Vec<BufferLine>,
metrics: Metrics,
width: i32,
@ -365,14 +366,10 @@ impl<'a> Buffer<'a> {
/// Set the current buffer dimensions
pub fn set_size(&mut self, width: i32, height: i32) {
if width != self.width {
if width != self.width || height != self.height {
self.width = width;
self.relayout();
self.shape_until_scroll();
}
if height != self.height {
self.height = height;
self.relayout();
self.shape_until_scroll();
}
}

View file

@ -106,6 +106,16 @@ impl<'a> Editor<'a> {
}
}
/// Get the internal [Buffer]
pub fn buffer(&self) -> &Buffer<'a> {
&self.buffer
}
/// Get the internal [Buffer], mutably
pub fn buffer_mut(&mut self) -> &mut Buffer<'a> {
&mut self.buffer
}
/// Get the current cursor position
pub fn cursor(&self) -> Cursor {
self.cursor

View file

@ -31,23 +31,19 @@ use crate::{
Color,
Cursor,
Editor,
FontSystem,
Metrics,
Style,
Weight,
};
pub struct SyntaxSystem<'a> {
pub font_system: &'a FontSystem,
pub struct SyntaxSystem {
pub syntax_set: SyntaxSet,
pub theme_set: ThemeSet,
}
impl<'a> SyntaxSystem<'a> {
impl SyntaxSystem {
/// Create a new [SyntaxSystem]
pub fn new(font_system: &'a FontSystem) -> Self {
pub fn new() -> Self {
Self {
font_system,
//TODO: store newlines in buffer
syntax_set: SyntaxSet::load_defaults_nonewlines(),
theme_set: ThemeSet::load_defaults(),
@ -57,22 +53,22 @@ impl<'a> SyntaxSystem<'a> {
/// A wrapper of [Editor] with syntax highlighting provided by [SyntaxSystem]
pub struct SyntaxEditor<'a> {
//TODO: should this be pub?
editor: Editor<'a>,
syntax_system: &'a SyntaxSystem<'a>,
syntax_system: &'a SyntaxSystem,
syntax: &'a SyntaxReference,
//TODO: should this be pub?
pub theme: &'a Theme,
theme: &'a Theme,
highlighter: Highlighter<'a>,
syntax_cache: Vec<(ParseState, HighlightState)>,
}
impl<'a> SyntaxEditor<'a> {
/// Create a new [SyntaxEditor] with the provided [SyntaxSystem], [Metrics], and theme name.
/// Create a new [SyntaxEditor] with the provided [Buffer], [SyntaxSystem], and theme name.
///
/// A good default theme name is "base16-eighties.dark".
/// Returns None will be returned if theme not found
pub fn new(syntax_system: &'a SyntaxSystem<'a>, metrics: Metrics, theme_name: &str) -> Option<Self> {
let editor = Editor::new(Buffer::new(syntax_system.font_system, metrics));
///
/// Returns None if theme not found
pub fn new(buffer: Buffer<'a>, syntax_system: &'a SyntaxSystem, theme_name: &str) -> Option<Self> {
let editor = Editor::new(buffer);
let syntax = syntax_system.syntax_set.find_syntax_plain_text();
let theme = syntax_system.theme_set.themes.get(theme_name)?;
let highlighter = Highlighter::new(theme);
@ -108,6 +104,9 @@ impl<'a> SyntaxEditor<'a> {
}
};
// Clear syntax cache
self.syntax_cache.clear();
Ok(())
}
@ -173,7 +172,7 @@ impl<'a> SyntaxEditor<'a> {
line.set_wrap_simple(true);
//TODO: efficiently do syntax highlighting without having to shape whole buffer
line.shape(&self.syntax_system.font_system);
line.shape(self.editor.buffer.font_system);
let cache_item = (parse_state.clone(), highlight_state.clone());
if line_i < self.syntax_cache.len() {
@ -212,6 +211,34 @@ impl<'a> SyntaxEditor<'a> {
self.editor.cursor()
}
/// Get the default background color
pub fn background_color(&self) -> Color {
if let Some(background) = self.theme.settings.background {
Color::rgba(
background.r,
background.g,
background.b,
background.a,
)
} else {
Color::rgb(0, 0, 0)
}
}
/// Get the default foreground (text) color
pub fn foreground_color(&self) -> Color {
if let Some(foreground) = self.theme.settings.foreground {
Color::rgba(
foreground.r,
foreground.g,
foreground.b,
foreground.a,
)
} else {
Color::rgb(0xFF, 0xFF, 0xFF)
}
}
/// Copy selection
pub fn copy_selection(&mut self) -> Option<String> {
self.editor.copy_selection()
@ -229,9 +256,11 @@ impl<'a> SyntaxEditor<'a> {
/// Draw the editor
#[cfg(feature = "swash")]
pub fn draw<F>(&self, cache: &mut crate::SwashCache, color: Color, f: F)
pub fn draw<F>(&self, cache: &mut crate::SwashCache, mut f: F)
where F: FnMut(i32, i32, u32, u32, Color)
{
self.editor.draw(cache, color, f);
let size = self.buffer().size();
f(0, 0, size.0 as u32, size.1 as u32, self.background_color());
self.editor.draw(cache, self.foreground_color(), f);
}
}

0
terminal.sh Normal file → Executable file
View file

View file

@ -10,4 +10,5 @@ cargo build --release --no-default-features --features swash
cargo build --release --no-default-features --features syntect
cargo build --release --all-features
cargo build --release --all
target/release/terminal
env RUST_LOG=editor_test=info target/release/editor-test