Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Editor invalidation, optimizations, and more #433

Draft
wants to merge 21 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,9 @@ image = { workspace = true }
im = { workspace = true }
wgpu = { workspace = true }

[dev-dependencies]
criterion = "0.5"

[features]
default = ["editor", "default-image-formats"]
# TODO: this is only winit and the editor serde, there are other dependencies that still depend on
Expand Down Expand Up @@ -99,3 +102,10 @@ tokio = ["dep:tokio"]
# rfd (file dialog) async runtime
rfd-async-std = ["dep:rfd", "rfd/async-std"]
rfd-tokio = ["dep:rfd", "rfd/tokio"]

[profile.bench]
debug = true

[[bench]]
name = "basic_editing"
harness = false
61 changes: 51 additions & 10 deletions editor-core/src/buffer/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,13 +63,54 @@ struct Revision {
cursor_after: Option<CursorMode>,
}

#[derive(Debug, Clone)]
#[derive(Debug, Clone, Copy)]
pub struct InvalLines {
pub start_line: usize,
pub inval_count: usize,
pub new_count: usize,
}
impl InvalLines {
pub fn new(start_line: usize, inval_count: usize, new_count: usize) -> Self {
Self {
start_line,
inval_count,
new_count,
}
}

pub fn single(start_line: usize) -> Self {
Self {
start_line,
inval_count: 1,
new_count: 1,
}
}

pub fn all(line_count: usize) -> Self {
Self {
start_line: 0,
inval_count: line_count,
new_count: line_count,
}
}
}

#[derive(Debug, Clone)]
pub struct InvalLinesR {
pub start_line: usize,
pub inval_count: usize,
pub new_count: usize,
pub old_text: Rope,
}
impl Into<InvalLines> for InvalLinesR {
fn into(self) -> InvalLines {
InvalLines {
start_line: self.start_line,
inval_count: self.inval_count,
new_count: self.new_count,
}
}
}

#[derive(Clone)]
pub struct Buffer {
Expand Down Expand Up @@ -214,7 +255,7 @@ impl Buffer {
self.set_pristine();
}

pub fn reload(&mut self, content: Rope, set_pristine: bool) -> (Rope, RopeDelta, InvalLines) {
pub fn reload(&mut self, content: Rope, set_pristine: bool) -> (Rope, RopeDelta, InvalLinesR) {
// Determine the line ending of the new text
let line_ending = LineEndingDetermination::determine(&content);
self.line_ending = line_ending.unwrap_or(self.line_ending);
Expand Down Expand Up @@ -262,7 +303,7 @@ impl Buffer {
&mut self,
edits: I,
edit_type: EditType,
) -> (Rope, RopeDelta, InvalLines)
) -> (Rope, RopeDelta, InvalLinesR)
where
I: IntoIterator<Item = E>,
E: Borrow<(S, &'a str)>,
Expand Down Expand Up @@ -299,7 +340,7 @@ impl Buffer {
self.add_delta(delta)
}

pub fn normalize_line_endings(&mut self) -> Option<(Rope, RopeDelta, InvalLines)> {
pub fn normalize_line_endings(&mut self) -> Option<(Rope, RopeDelta, InvalLinesR)> {
let Some(delta) = self.line_ending.normalize_delta(&self.text) else {
// There were no changes needed
return None;
Expand All @@ -310,7 +351,7 @@ impl Buffer {

// TODO: don't clone the delta and return it, if the caller needs it then they can clone it
/// Note: the delta's line-endings should be normalized.
fn add_delta(&mut self, delta: RopeDelta) -> (Rope, RopeDelta, InvalLines) {
fn add_delta(&mut self, delta: RopeDelta) -> (Rope, RopeDelta, InvalLinesR) {
let text = self.text.clone();

let undo_group = self.calculate_undo_group();
Expand All @@ -337,7 +378,7 @@ impl Buffer {
new_text: Rope,
new_tombstones: Rope,
new_deletes_from_union: Subset,
) -> InvalLines {
) -> InvalLinesR {
self.rev_counter += 1;

let (iv, newlen) = delta.summary();
Expand All @@ -354,7 +395,7 @@ impl Buffer {
let old_hard_count = old_logical_end_line - logical_start_line;
let new_hard_count = new_logical_end_line - logical_start_line;

InvalLines {
InvalLinesR {
start_line: logical_start_line,
inval_count: old_hard_count,
new_count: new_hard_count,
Expand Down Expand Up @@ -588,7 +629,7 @@ impl Buffer {
) -> (
Rope,
RopeDelta,
InvalLines,
InvalLinesR,
Option<CursorMode>,
Option<CursorMode>,
) {
Expand Down Expand Up @@ -622,7 +663,7 @@ impl Buffer {
(text, delta, inval_lines, cursor_before, cursor_after)
}

pub fn do_undo(&mut self) -> Option<(Rope, RopeDelta, InvalLines, Option<CursorMode>)> {
pub fn do_undo(&mut self) -> Option<(Rope, RopeDelta, InvalLinesR, Option<CursorMode>)> {
if self.cur_undo <= 1 {
return None;
}
Expand All @@ -636,7 +677,7 @@ impl Buffer {
Some((text, delta, inval_lines, cursor_before))
}

pub fn do_redo(&mut self) -> Option<(Rope, RopeDelta, InvalLines, Option<CursorMode>)> {
pub fn do_redo(&mut self) -> Option<(Rope, RopeDelta, InvalLinesR, Option<CursorMode>)> {
if self.cur_undo >= self.live_undos.len() {
return None;
}
Expand Down
132 changes: 112 additions & 20 deletions editor-core/src/buffer/rope_text.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::{borrow::Cow, ops::Range};
use std::{borrow::Cow, cell::Cell, ops::Range};

use lapce_xi_rope::{interval::IntervalBounds, rope::ChunkIter, Cursor, Rope};

Expand Down Expand Up @@ -79,10 +79,14 @@ pub trait RopeText {
/// assert_eq!(text.offset_of_line_col(1, 4), 11); // "d"
/// ````
fn offset_of_line_col(&self, line: usize, col: usize) -> usize {
let offset = self.offset_of_line(line);
let last_offset = self.offset_of_line(line + 1);
self.offset_of_offset_col(offset, last_offset, col)
}

fn offset_of_offset_col(&self, mut offset: usize, last_offset: usize, col: usize) -> usize {
let mut pos = 0;
let mut offset = self.offset_of_line(line);
let text = self.slice_to_cow(offset..self.offset_of_line(line + 1));
let mut iter = text.chars().peekable();
let mut iter = self.chars(offset..last_offset).peekable();
while let Some(c) = iter.next() {
// Stop at the end of the line
if c == '\n' || (c == '\r' && iter.peek() == Some(&'\n')) {
Expand All @@ -99,6 +103,35 @@ pub trait RopeText {
offset
}

/// (start_line_offset, line_end_offset(caret), line+1 offset)
/// Which we can provide as we need the first and last to compute the second.
fn line_offsets(&self, line: usize, caret: bool) -> (usize, usize, usize) {
// let line_start = self.offset_of_line(line);
// let line_end = self.line_end_offset(line, true);
// (line_start, line_end)

let start_offset = self.offset_of_line(line);
let end_offset = self.offset_of_line(line + 1);

let mut offset = end_offset;

let start = end_offset.saturating_sub(2).max(start_offset);
let mut chars = self.chars(start..end_offset);
let fst = chars.next();
let snd = chars.next();

if fst == Some('\r') && snd == Some('\n') {
offset -= 2;
} else if (fst == Some('\n') && snd == None) || snd == Some('\n') {
offset -= 1;
}

if !caret && start_offset != offset {
offset = self.prev_grapheme_offset(offset, 1, 0);
}
(start_offset, offset, end_offset)
}

fn line_end_col(&self, line: usize, caret: bool) -> usize {
let line_start = self.offset_of_line(line);
let offset = self.line_end_offset(line, caret);
Expand All @@ -121,19 +154,44 @@ pub trait RopeText {
/// assert_eq!(text.line_end_offset(2, false), 11); // "world|"
/// ```
fn line_end_offset(&self, line: usize, caret: bool) -> usize {
let mut offset = self.offset_of_line(line + 1);
let mut line_content: &str = &self.line_content(line);
if line_content.ends_with("\r\n") {
offset -= 2;
line_content = &line_content[..line_content.len() - 2];
} else if line_content.ends_with('\n') {
offset -= 1;
line_content = &line_content[..line_content.len() - 1];
self.line_offsets(line, caret).1
}

/// Whether the line is completely empty
/// This counts both 'empty' and 'only has newline'
/// ```rust
/// # use floem_editor_core::xi_rope::Rope;
/// # use floem_editor_core::buffer::rope_text::{RopeText, RopeTextRef};
/// let text = Rope::from("hello\nworld toast and jam\n\nhi");
/// let text = RopeTextRef::new(&text);
/// assert_eq!(text.is_line_empty(0), false);
/// assert_eq!(text.is_line_empty(1), false);
/// assert_eq!(text.is_line_empty(2), true);
/// assert_eq!(text.is_line_empty(3), false);
///
/// let text = Rope::from("");
/// let text = RopeTextRef::new(&text);
/// assert_eq!(text.is_line_empty(0), true);
/// ```
fn is_line_empty(&self, line: usize) -> bool {
let start_offset = self.offset_of_line(line);
let end_offset = self.offset_of_line(line + 1);

if start_offset == end_offset {
return true;
}
if !caret && !line_content.is_empty() {
offset = self.prev_grapheme_offset(offset, 1, 0);

let mut chars = self.chars(start_offset..end_offset);
let fst = chars.next();
let snd = chars.next();

if fst == Some('\r') && snd == Some('\n') {
true
} else if (fst == Some('\n') && snd == None) || snd == Some('\n') {
true
} else {
false
}
offset
}

/// Returns the content of the given line.
Expand Down Expand Up @@ -228,6 +286,11 @@ pub trait RopeText {
.slice_to_cow(range.start.min(self.len())..range.end.min(self.len()))
}

fn chars(&self, range: Range<usize>) -> impl Iterator<Item = char> + '_ {
let iter = self.text().iter_chunks(range);
iter.flat_map(str::chars)
}

// TODO(minor): Once you can have an `impl Trait` return type in a trait, this could use that.
/// Iterate over (utf8_offset, char) values in the given range
#[allow(clippy::type_complexity)]
Expand Down Expand Up @@ -366,38 +429,67 @@ pub trait RopeText {
}
}

// We cache the last line. This is cheap to calculate, but is used many times.
#[derive(Clone)]
pub struct RopeTextVal {
pub text: Rope,
text: Rope,
last_line: Cell<Option<usize>>,
}
impl RopeTextVal {
pub fn new(text: Rope) -> Self {
Self { text }
Self {
text,
last_line: Cell::new(None),
}
}
}
impl RopeText for RopeTextVal {
fn text(&self) -> &Rope {
&self.text
}

fn last_line(&self) -> usize {
if let Some(last_line) = self.last_line.get() {
last_line
} else {
let last_line = self.line_of_offset(self.len());
self.last_line.set(Some(last_line));
last_line
}
}
}
impl From<Rope> for RopeTextVal {
fn from(text: Rope) -> Self {
Self::new(text)
}
}
#[derive(Copy, Clone)]
#[derive(Clone)]
pub struct RopeTextRef<'a> {
pub text: &'a Rope,
text: &'a Rope,
last_line: Cell<Option<usize>>,
}
impl<'a> RopeTextRef<'a> {
pub fn new(text: &'a Rope) -> Self {
Self { text }
Self {
text,
last_line: Cell::new(None),
}
}
}
impl<'a> RopeText for RopeTextRef<'a> {
fn text(&self) -> &Rope {
self.text
}

fn last_line(&self) -> usize {
if let Some(last_line) = self.last_line.get() {
last_line
} else {
let last_line = self.line_of_offset(self.len());
self.last_line.set(Some(last_line));
last_line
}
}
}
impl<'a> From<&'a Rope> for RopeTextRef<'a> {
fn from(text: &'a Rope) -> Self {
Expand Down
Loading
Loading