use std::time::Duration;
use canvist_core::Command;
use canvist_core::CommandResult;
use canvist_core::Editor;
use canvist_core::EditorState;
use canvist_core::Env;
use canvist_core::KeyPress;
use canvist_core::LineNavigator;
use canvist_core::Update;
use canvist_core::commands;
use canvist_core::parse_binding;
use canvist_core::value_to_json;
use canvist_model::Attrs;
#[cfg(feature = "journal")]
use canvist_model::Commit;
use canvist_model::Document;
use canvist_model::Point;
use canvist_model::Selection;
use canvist_model::Value;
use serde_json::Value as Json;
use crate::Format;
use crate::HeadlessError;
use crate::Position;
use crate::Snapshot;
use crate::format;
use crate::position;
pub struct Doc {
pub(crate) editor: Editor,
pub(crate) clock: Duration,
#[cfg(feature = "journal")]
journal: Option<Vec<Commit>>,
#[cfg(feature = "collab")]
pub(crate) shared: Option<canvist_collab::Binding>,
#[cfg(feature = "collab")]
pub(crate) grouping: canvist_core::UndoGrouping,
}
impl std::fmt::Debug for Doc {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter
.debug_struct("Doc")
.field("editor", &self.editor)
.finish_non_exhaustive()
}
}
impl Doc {
pub(crate) fn new(editor: Editor) -> Self {
Self {
editor,
clock: Duration::ZERO,
#[cfg(feature = "journal")]
journal: None,
#[cfg(feature = "collab")]
shared: None,
#[cfg(feature = "collab")]
grouping: canvist_core::UndoGrouping::default(),
}
}
#[must_use]
pub fn editor(&self) -> &Editor {
&self.editor
}
#[must_use]
pub fn state(&self) -> &EditorState {
self.editor.state()
}
#[must_use]
pub fn document(&self) -> &Document {
self.editor.state().doc()
}
#[must_use]
pub fn export(&self, format: Format) -> String {
format::write(self.document(), format)
}
#[must_use]
pub fn to_json(&self) -> Json {
self.document().to_json()
}
#[must_use]
pub fn snapshot(&self) -> Snapshot {
Snapshot::new(self.to_json(), self.selected_range())
}
#[must_use]
pub fn selection(&self) -> Selection {
self.editor.state().selection()
}
#[must_use]
pub fn selected_range(&self) -> Option<(Position, Position)> {
let Selection::Text { anchor, head } = self.selection() else {
return None;
};
Some((self.position(anchor)?, self.position(head)?))
}
pub fn point(&self, position: &Position) -> Result<Point, HeadlessError> {
position::resolve(self.document(), position)
}
#[must_use]
pub fn position(&self, point: Point) -> Option<Position> {
position::locate(self.document(), point)
}
pub fn select(&mut self, selection: Selection) -> Result<(), HeadlessError> {
let mut env = self.env();
let mut update = self.editor.select(selection, &mut env)?;
self.finish(&mut update).map(drop)
}
pub fn select_range(
&mut self,
anchor: &Position,
head: &Position,
) -> Result<(), HeadlessError> {
let anchor = self.point(anchor)?;
let head = self.point(head)?;
self.select(Selection::text(anchor, head))
}
pub fn select_all(&mut self) -> Result<(), HeadlessError> {
self.run(&canvist_core::command(commands::select_all))
.map(drop)
}
pub fn run(&mut self, command: &Command) -> Result<bool, HeadlessError> {
let mut env = self.env();
let mut update = self.editor.run(command, &mut env)?;
self.finish(&mut update)
}
pub fn can(&mut self, command: &Command) -> Result<bool, HeadlessError> {
let mut env = self.env();
Ok(self.editor.can(command, &mut env)?)
}
pub fn chain(&mut self, commands: &[Command]) -> Result<bool, HeadlessError> {
let mut env = self.env();
let chain = commands.iter().fold(self.editor.chain(), |chain, command| {
chain.then(command.clone())
});
let mut update = chain.run(&mut env)?;
self.finish(&mut update)
}
pub fn run_named(&mut self, name: &str, args: &Json) -> Result<bool, HeadlessError> {
let command = self.command_named(name, args)?;
#[cfg(feature = "collab")]
if let Some(redo) = self.shared_history_command(name) {
return Ok(self.history_step(redo)?.is_some());
}
self.run(&command)
}
pub fn command_named(&self, name: &str, args: &Json) -> Result<Command, HeadlessError> {
Ok(self.editor.command_named(name, &attrs(name, args)?)?)
}
pub fn can_named(&mut self, name: &str, args: &Json) -> Result<bool, HeadlessError> {
let command = self.command_named(name, args)?;
self.can(&command)
}
pub fn query(&self, name: &str, args: &Json) -> Result<Json, HeadlessError> {
let value = self.editor.query(name, &attrs(name, args)?)?;
Ok(value_to_json(&value))
}
pub fn insert_text(&mut self, text: &str) -> Result<bool, HeadlessError> {
if text.is_empty() {
return self.delete_selection();
}
let text = text.to_owned();
let command = canvist_core::command(move |state| commands::insert_text(state, &text));
self.run(&command)
}
pub fn delete_selection(&mut self) -> Result<bool, HeadlessError> {
self.run(&canvist_core::command(commands::delete_selection))
}
pub fn type_text(&mut self, text: &str) -> Result<bool, HeadlessError> {
let mut changed = false;
let mut buffer = [0; 4];
for character in text.chars() {
let mut env = self.env();
let mut update = self
.editor
.insert_text(character.encode_utf8(&mut buffer), &mut env)?;
changed |= self.finish(&mut update)?;
}
Ok(changed)
}
pub fn press(&mut self, key: &str) -> Result<bool, HeadlessError> {
let (key, modifiers) = parse_binding(key, self.editor.platform())?;
#[cfg(feature = "collab")]
if let Some(redo) = self.shared_history_key(KeyPress::new(&key, modifiers)) {
return Ok(self.history_step(redo)?.is_some());
}
let mut env = self.env();
let mut update = self
.editor
.handle_key(KeyPress::new(&key, modifiers), &mut env)?;
self.finish(&mut update)
}
pub fn paste(&mut self, format: Format, content: &str) -> Result<bool, HeadlessError> {
let mut env = self.env();
let mut update = match format {
Format::Text => self.editor.paste_text(content, &mut env)?,
format => {
let slice = format::read_slice(self.document().schema(), format, content)?;
self.editor.paste(slice, &mut env)?
}
};
self.finish(&mut update)
}
pub fn undo(&mut self) -> Result<bool, HeadlessError> {
Ok(self.history_step(false)?.is_some())
}
pub fn redo(&mut self) -> Result<bool, HeadlessError> {
Ok(self.history_step(true)?.is_some())
}
pub fn history_step(&mut self, redo: bool) -> Result<Option<Update>, HeadlessError> {
#[cfg(feature = "collab")]
if self.shared.is_some() {
return self.undo_shared(redo);
}
let mut env = self.env();
let mut update = if redo {
self.editor.redo(&mut env)?
} else {
self.editor.undo(&mut env)?
};
self.finish(&mut update)?;
Ok(update)
}
#[must_use]
pub fn can_undo(&self) -> bool {
#[cfg(feature = "collab")]
if let Some(binding) = &self.shared {
return binding.can_undo();
}
self.editor.can_undo()
}
#[must_use]
pub fn can_redo(&self) -> bool {
#[cfg(feature = "collab")]
if let Some(binding) = &self.shared {
return binding.can_redo();
}
self.editor.can_redo()
}
pub fn stop_dictation(&mut self) -> bool {
self.editor.stop_dictation()
}
pub fn edit(
&mut self,
now: Duration,
lines: &mut dyn LineNavigator,
change: impl FnOnce(&mut Editor, &mut Env<'_>) -> CommandResult,
) -> Result<Option<Update>, HeadlessError> {
self.clock = self.clock.max(now);
let mut env = Env::new(self.clock, lines);
let mut update = change(&mut self.editor, &mut env)?;
self.finish(&mut update)?;
Ok(update)
}
#[cfg(feature = "journal")]
pub fn record_commits(&mut self) {
self.journal.get_or_insert_with(Vec::new);
}
#[cfg(feature = "journal")]
pub fn take_commits(&mut self) -> Vec<Commit> {
self.journal
.as_mut()
.map(std::mem::take)
.unwrap_or_default()
}
#[cfg(feature = "journal")]
pub(crate) fn record(&mut self, update: &Update) {
if let Some(journal) = &mut self.journal
&& update.doc_changed()
{
journal.push(update.commit.clone());
}
}
#[cfg(not(feature = "journal"))]
#[allow(clippy::unused_self, reason = "the journal feature records")]
pub(crate) fn record(&mut self, _update: &Update) {}
pub(crate) fn env(&mut self) -> Env<'static> {
self.clock += Duration::from_secs(1);
Env::headless(self.clock)
}
#[cfg_attr(
not(feature = "collab"),
allow(
clippy::unnecessary_wraps,
reason = "only shared documents pass updates on"
)
)]
fn finish(&mut self, update: &mut Option<Update>) -> Result<bool, HeadlessError> {
let Some(update) = update else {
return Ok(false);
};
#[cfg(feature = "collab")]
self.mirror_local(update)?;
self.record(update);
Ok(true)
}
}
fn attrs(name: &str, args: &Json) -> Result<Attrs, HeadlessError> {
let invalid = |reason: &str| {
HeadlessError::InvalidArgs {
name: name.to_owned(),
reason: reason.to_owned(),
}
};
let fields = match args {
Json::Null => return Ok(Attrs::new()),
Json::Object(fields) => fields,
_ => return Err(invalid("arguments must be an object")),
};
fields
.iter()
.map(|(key, value)| {
value_of(value)
.map(|value| (key.as_str(), value))
.ok_or_else(|| {
invalid(&format!(
"`{key}` must be a string, number, boolean, null, array, or object"
))
})
})
.collect()
}
fn value_of(json: &Json) -> Option<Value> {
Some(match json {
Json::Null => Value::Null,
Json::Bool(value) => Value::Bool(*value),
Json::Number(number) => {
match number.as_i64() {
Some(int) => Value::from(int),
None => Value::from(number.as_f64()?),
}
}
Json::String(value) => Value::from(value.as_str()),
Json::Array(values) => {
Value::from(values.iter().map(value_of).collect::<Option<Vec<_>>>()?)
}
Json::Object(fields) => {
let attrs = fields
.iter()
.map(|(key, value)| Some((key.as_str(), value_of(value)?)))
.collect::<Option<Attrs>>()?;
Value::from(attrs)
}
})
}