use continuity_buffer::{Buffer, BufferId, Revision, RopeSnapshot, UndoGroupId};
use continuity_text::{EditOp, Position, Range, Selection};
use crate::change::{ChangeBatch, EngineEvent, MutationKind};
use crate::reconcile_diff::compute_reconcile_splice;
use crate::selection_coalesce::coalesce_selections;
use crate::selection_edit::{plan, SelectionEdit};
use crate::undo::{CoalesceKind, UndoManager};
use crate::{DeltaHistory, EngineState, Error, RopeEditDeltaWithPoints};
pub trait IdGenerator {
fn next_buffer_id(&mut self) -> BufferId;
fn next_undo_group_id(&mut self) -> UndoGroupId;
}
#[derive(Debug, Default)]
pub struct SystemIdGenerator;
impl IdGenerator for SystemIdGenerator {
fn next_buffer_id(&mut self) -> BufferId {
BufferId::new()
}
fn next_undo_group_id(&mut self) -> UndoGroupId {
UndoGroupId::new()
}
}
#[derive(Clone)]
pub struct EngineSnapshot {
pub rope: RopeSnapshot,
pub selections: Vec<Selection>,
pub is_read_only: bool,
}
pub struct Engine {
state: EngineState,
undo: UndoManager,
delta_history: DeltaHistory,
events: Vec<EngineEvent>,
ids: Box<dyn IdGenerator>,
}
impl Engine {
#[must_use]
pub fn new() -> Self {
Self::with_id_generator(Box::<SystemIdGenerator>::default())
}
#[must_use]
pub fn with_id_generator(ids: Box<dyn IdGenerator>) -> Self {
Self {
state: EngineState::new(),
undo: UndoManager::default(),
delta_history: DeltaHistory::default(),
events: Vec::new(),
ids,
}
}
pub fn open_buffer(&mut self, text: &str) -> BufferId {
let id = self.ids.next_buffer_id();
self.adopt_buffer(Buffer::from_parts(id, text, Revision::INITIAL))
}
pub fn load_buffer(&mut self, id: BufferId, text: &str, revision: Revision) -> BufferId {
self.adopt_buffer(Buffer::from_parts(id, text, revision))
}
pub fn adopt_buffer(&mut self, buffer: Buffer) -> BufferId {
let id = self.state.insert(buffer);
self.events.push(EngineEvent::BufferOpened { id });
id
}
pub fn close_buffer(&mut self, id: BufferId) -> Option<Buffer> {
let buffer = self.state.remove(id)?;
self.undo.forget(id);
self.delta_history.forget(id);
self.events.push(EngineEvent::BufferClosed { id });
Some(buffer)
}
#[must_use]
pub fn snapshot(&self, id: BufferId) -> Option<EngineSnapshot> {
self.state.get(id).map(|buffer| EngineSnapshot {
rope: buffer.snapshot(),
selections: buffer.selections().to_vec(),
is_read_only: buffer.is_read_only(),
})
}
#[must_use]
pub fn text(&self, id: BufferId) -> Option<String> {
self.state.get(id).map(|buffer| buffer.rope().to_string())
}
#[must_use]
pub fn selections(&self, id: BufferId) -> Option<&[Selection]> {
self.state.get(id).map(Buffer::selections)
}
#[must_use]
pub fn revision(&self, id: BufferId) -> Option<Revision> {
self.state.get(id).map(Buffer::revision)
}
pub fn set_selections(
&mut self,
id: BufferId,
mut selections: Vec<Selection>,
) -> Result<(), Error> {
coalesce_selections(&mut selections);
let buffer = self.state.get_mut(id).ok_or(Error::UnknownBuffer)?;
buffer.set_selections(selections);
self.events.push(EngineEvent::SelectionsChanged { id });
Ok(())
}
pub fn apply_edit(
&mut self,
id: BufferId,
op: EditOp,
timestamp_ms: i64,
) -> Result<ChangeBatch, Error> {
let batch = self.undo.apply_single(
self.state.get_mut(id).ok_or(Error::UnknownBuffer)?,
&op,
"editor.apply_edit",
timestamp_ms,
self.ids.as_mut(),
)?;
self.record_batch(&batch);
Ok(batch)
}
pub fn apply_grouped_edit(
&mut self,
id: BufferId,
ops: &[EditOp],
selections_after: Vec<Selection>,
command: &str,
timestamp_ms: i64,
) -> Result<Option<ChangeBatch>, Error> {
let buffer = self.state.get_mut(id).ok_or(Error::UnknownBuffer)?;
let selections_before = buffer.selections().to_vec();
let selections_after = if selections_after.is_empty() {
selections_before.clone()
} else {
selections_after
};
let batch = self.undo.apply_group(
buffer,
ops,
&selections_before,
&selections_after,
command,
CoalesceKind::Discrete,
timestamp_ms,
MutationKind::GroupedEdit,
self.ids.as_mut(),
)?;
self.record_optional_batch(batch.as_ref());
Ok(batch)
}
pub fn apply_selection_edit(
&mut self,
id: BufferId,
edit: &SelectionEdit,
timestamp_ms: i64,
) -> Result<Option<ChangeBatch>, Error> {
let buffer = self.state.get_mut(id).ok_or(Error::UnknownBuffer)?;
let Some(edit_plan) = plan(buffer, edit)? else {
return Ok(None);
};
let batch = self.undo.apply_group(
buffer,
&edit_plan.ops,
&edit_plan.selections_before,
&edit_plan.selections_after,
command_name_for(edit),
coalesce_kind_for(edit),
timestamp_ms,
MutationKind::SelectionEdit,
self.ids.as_mut(),
)?;
self.record_optional_batch(batch.as_ref());
Ok(batch)
}
pub fn undo(&mut self, id: BufferId, timestamp_ms: i64) -> Result<Option<ChangeBatch>, Error> {
let batch = self.undo.undo(
self.state.get_mut(id).ok_or(Error::UnknownBuffer)?,
timestamp_ms,
)?;
self.record_optional_batch(batch.as_ref());
Ok(batch)
}
pub fn redo(&mut self, id: BufferId, timestamp_ms: i64) -> Result<Option<ChangeBatch>, Error> {
self.redo_inner(id, timestamp_ms, false)
}
pub fn redo_alternate(
&mut self,
id: BufferId,
timestamp_ms: i64,
) -> Result<Option<ChangeBatch>, Error> {
self.redo_inner(id, timestamp_ms, true)
}
pub fn replace_text_if_revision(
&mut self,
id: BufferId,
expected: Revision,
text: impl Into<String>,
timestamp_ms: i64,
) -> Result<ChangeBatch, Error> {
let buffer = self.state.get(id).ok_or(Error::UnknownBuffer)?;
let actual = buffer.revision();
if actual != expected {
return Err(Error::RevisionMismatch { expected, actual });
}
let end = Position::from_byte_offset(buffer.rope(), buffer.rope().len_bytes())?;
let op = EditOp::replace(Range::new(Position::ZERO, end), text);
self.apply_edit(id, op, timestamp_ms)
}
pub fn reconcile_text_if_revision(
&mut self,
id: BufferId,
expected: Revision,
text: impl Into<String>,
timestamp_ms: i64,
) -> Result<Option<ChangeBatch>, Error> {
let text = text.into();
let buffer = self.state.get(id).ok_or(Error::UnknownBuffer)?;
let actual = buffer.revision();
if actual != expected {
return Err(Error::RevisionMismatch { expected, actual });
}
if buffer.rope() == text.as_str() {
return Ok(None);
}
let splice = compute_reconcile_splice(buffer.rope(), &text);
let start = Position::from_byte_offset(buffer.rope(), splice.start)?;
let end = Position::from_byte_offset(buffer.rope(), splice.old_end)?;
let replacement = text[splice.start..splice.new_end].to_string();
let op = EditOp::replace(Range::new(start, end), replacement);
self.apply_edit(id, op, timestamp_ms).map(Some)
}
#[must_use]
pub fn deltas_since(
&self,
id: BufferId,
since_revision: u64,
) -> (Vec<continuity_text::RopeEditDelta>, bool) {
self.delta_history.since(id, since_revision)
}
#[must_use]
pub fn deltas_with_points_since(
&self,
id: BufferId,
since_revision: u64,
) -> (Vec<RopeEditDeltaWithPoints>, bool) {
self.delta_history.with_points_since(id, since_revision)
}
pub fn drain_events(&mut self) -> Vec<EngineEvent> {
std::mem::take(&mut self.events)
}
#[must_use]
pub fn state(&self) -> &EngineState {
&self.state
}
pub fn state_mut(&mut self) -> &mut EngineState {
&mut self.state
}
fn redo_inner(
&mut self,
id: BufferId,
timestamp_ms: i64,
alternate: bool,
) -> Result<Option<ChangeBatch>, Error> {
let batch = self.undo.redo(
self.state.get_mut(id).ok_or(Error::UnknownBuffer)?,
timestamp_ms,
alternate,
)?;
self.record_optional_batch(batch.as_ref());
Ok(batch)
}
fn record_optional_batch(&mut self, batch: Option<&ChangeBatch>) {
if let Some(batch) = batch {
self.record_batch(batch);
}
}
fn record_batch(&mut self, batch: &ChangeBatch) {
self.delta_history.push(
batch.buffer_id,
batch.revision_after.get(),
batch.deltas.clone(),
);
self.events.push(EngineEvent::Changed {
id: batch.buffer_id,
revision: batch.revision_after,
kind: batch.kind,
});
}
}
impl Default for Engine {
fn default() -> Self {
Self::new()
}
}
fn coalesce_kind_for(edit: &SelectionEdit) -> CoalesceKind {
match edit {
SelectionEdit::InsertText(text) if text.chars().count() == 1 && text != "\n" => {
CoalesceKind::Typing
}
SelectionEdit::DeleteBack | SelectionEdit::DeleteForward => CoalesceKind::Typing,
_ => CoalesceKind::Discrete,
}
}
fn command_name_for(edit: &SelectionEdit) -> &'static str {
match edit {
SelectionEdit::InsertText(_) => "editor.insert_text",
SelectionEdit::DeleteBack => "editor.delete_back",
SelectionEdit::DeleteForward => "editor.delete_forward",
_ => "editor.selection_edit",
}
}