use std::sync::Arc;
use std::time::Duration;
use canvist_headless::Doc;
use canvist_headless::Engine;
use canvist_headless::Format;
use canvist_headless::canvist_core::Command;
use canvist_headless::canvist_core::CommandResult;
use canvist_headless::canvist_core::Editor;
use canvist_headless::canvist_core::EditorState;
use canvist_headless::canvist_core::Env;
use canvist_headless::canvist_core::Update;
use canvist_headless::canvist_core::command;
use canvist_headless::canvist_core::commands;
use canvist_headless::canvist_extensions::StarterKitHandles;
use canvist_headless::canvist_model::Commit;
use canvist_headless::canvist_model::Selection;
use canvist_layout::Caret;
use canvist_layout::DisplayList;
use canvist_layout::DisplayOptions;
use canvist_layout::DocumentLayout;
use canvist_layout::LayoutOptions;
use canvist_layout::ParleyMeasurer;
use canvist_layout::Rect;
use crate::DesktopError;
use crate::DesktopResult;
use crate::EditorOptions;
use crate::Fonts;
use crate::accessibility::Accessibility;
use crate::lines::HostLines;
use crate::pointer::PointerState;
const REVEAL_MARGIN: f32 = 16.0;
const REVEAL_PASSES: usize = 4;
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Viewport {
pub width: f32,
pub height: f32,
pub scale: f32,
}
impl Default for Viewport {
fn default() -> Self {
Self {
width: 800.0,
height: 600.0,
scale: 1.0,
}
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct FrameInfo {
pub height: f32,
pub laid_out: usize,
pub measured: u64,
pub items: usize,
pub next_blink: Option<Duration>,
}
pub struct DesktopEditor<Handles = StarterKitHandles> {
pub(crate) engine: Engine<Handles>,
pub(crate) doc: Doc,
pub(crate) options: EditorOptions,
pub(crate) fonts: Fonts,
pub(crate) measurer: ParleyMeasurer,
pub(crate) layout: DocumentLayout,
synced: u64,
pub(crate) viewport: Viewport,
pub(crate) scroll: f32,
pub(crate) list: DisplayList,
reveal: bool,
pub(crate) dirty: bool,
pub(crate) focused: bool,
pub(crate) blink_from: Duration,
pub(crate) now: Duration,
pub(crate) pointer: PointerState,
pub(crate) a11y: Accessibility,
#[cfg(feature = "collab")]
pub(crate) joining: crate::collab::Joining,
}
impl<Handles> std::fmt::Debug for DesktopEditor<Handles> {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter
.debug_struct("DesktopEditor")
.field("doc", &self.doc)
.field("viewport", &self.viewport)
.field("scroll", &self.scroll)
.finish_non_exhaustive()
}
}
impl<Handles: Copy> DesktopEditor<Handles> {
pub fn new(engine: Engine<Handles>, options: EditorOptions) -> DesktopResult<Self> {
let engine = engine
.with_client(options.client)
.with_platform(options.platform);
let doc = engine.create()?;
Ok(Self::with_doc(engine, doc, options))
}
fn with_doc(engine: Engine<Handles>, doc: Doc, options: EditorOptions) -> Self {
let fonts = Fonts::new(options.fonts);
let viewport = Viewport::default();
let layout = DocumentLayout::new(
doc.document(),
options.theme.clone(),
layout_options(&options, viewport),
);
Self {
synced: doc.document().version(),
measurer: fonts.measurer(),
fonts,
engine,
doc,
options,
layout,
viewport,
scroll: 0.0,
list: DisplayList::default(),
reveal: false,
dirty: true,
focused: false,
blink_from: Duration::ZERO,
now: Duration::ZERO,
pointer: PointerState::default(),
a11y: Accessibility::default(),
#[cfg(feature = "collab")]
joining: crate::collab::Joining::default(),
}
}
#[must_use]
pub fn handles(&self) -> Handles {
self.engine.handles()
}
#[must_use]
pub fn engine(&self) -> &Engine<Handles> {
&self.engine
}
#[must_use]
pub fn doc(&self) -> &Doc {
&self.doc
}
#[must_use]
pub fn state(&self) -> &EditorState {
self.doc.state()
}
#[must_use]
pub fn options(&self) -> &EditorOptions {
&self.options
}
#[must_use]
pub fn fonts(&self) -> &Fonts {
&self.fonts
}
#[must_use]
pub fn layout(&self) -> &DocumentLayout {
&self.layout
}
pub fn load(&mut self, format: Format, input: &str) -> DesktopResult<()> {
let doc = self.engine.parse(format, input)?;
self.set_doc(doc)
}
pub fn set_doc(&mut self, doc: Doc) -> DesktopResult<()> {
if !Arc::ptr_eq(doc.document().schema(), self.engine.schema()) {
return Err(DesktopError::ForeignDocument);
}
self.layout = DocumentLayout::new(
doc.document(),
self.options.theme.clone(),
layout_options(&self.options, self.viewport),
);
self.synced = doc.document().version();
self.doc = doc;
self.scroll = 0.0;
self.pointer = PointerState::default();
self.dirty = true;
Ok(())
}
#[must_use]
pub fn export(&self, format: Format) -> String {
self.doc.export(format)
}
pub fn run(&mut self, command: &Command) -> DesktopResult<bool> {
self.edit(|editor, env| editor.run(command, env))
}
pub fn can(&mut self, command: &Command) -> DesktopResult<bool> {
Ok(self.doc.can(command)?)
}
pub fn undo(&mut self) -> DesktopResult<bool> {
self.edit(Editor::undo)
}
pub fn redo(&mut self) -> DesktopResult<bool> {
self.edit(Editor::redo)
}
pub fn select_all(&mut self) -> DesktopResult<bool> {
let select_all = command(commands::select_all);
self.run(&select_all)
}
pub fn select(&mut self, selection: Selection) -> DesktopResult<bool> {
self.edit(|editor, env| editor.select(selection, env))
}
pub fn register_font(&mut self, data: Vec<u8>) -> Vec<String> {
let data: Arc<[u8]> = data.into();
let families = self.measurer.register_font(data.to_vec());
self.fonts.add(data);
self.layout.forget_measurements();
self.dirty = true;
families
}
pub fn resize(&mut self, viewport: Viewport) {
if viewport == self.viewport {
return;
}
self.viewport = viewport;
let width = column_width(&self.options, viewport);
self.layout.set_width(self.doc.document(), width);
self.dirty = true;
}
#[must_use]
pub fn viewport(&self) -> Viewport {
self.viewport
}
#[must_use]
pub fn scroll_top(&self) -> f32 {
self.scroll
}
pub fn scroll_to(&mut self, top: f32) {
let top = top.clamp(0.0, self.max_scroll());
if top.to_bits() != self.scroll.to_bits() {
self.scroll = top;
self.dirty = true;
}
}
#[must_use]
pub fn needs_repaint(&self) -> bool {
self.dirty
}
pub fn frame(&mut self, now: Duration) -> DesktopResult<FrameInfo> {
self.now = self.now.max(now);
let mut info = self.ensure_viewport()?;
if std::mem::take(&mut self.reveal) {
self.reveal_caret(&mut info)?;
}
self.scroll = self.scroll.clamp(0.0, self.max_scroll());
let (top, bottom) = self.visible_range();
self.list = self.layout.display_list(&self.display_options(top, bottom));
self.list.items.retain(|item| {
let bounds = item.bounds();
bounds.y < bottom && bounds.y + bounds.height > top
});
self.dirty = false;
info.height = self.layout.height();
info.items = self.list.items.len();
info.next_blink = self.next_blink();
Ok(info)
}
#[must_use]
pub fn display_list(&self) -> &DisplayList {
&self.list
}
#[must_use]
pub fn caret(&self) -> Option<Caret> {
match self.doc.selection() {
Selection::Text { anchor, head } if anchor == head => {
let affinity = self.doc.state().affinity().into();
Some(Caret::with_affinity(head, affinity))
}
_ => None,
}
}
#[must_use]
pub fn caret_area(&self) -> Option<Rect> {
let head = match self.doc.selection() {
Selection::Text { head, .. } => Caret::new(head),
Selection::Blocks { .. } => return None,
};
let caret = self.caret().unwrap_or(head);
self.layout
.caret_rect(caret)
.map(|rect| self.to_view_rect(rect))
}
pub(crate) fn edit(
&mut self,
change: impl FnOnce(&mut Editor, &mut Env<'_>) -> CommandResult,
) -> DesktopResult<bool> {
Ok(self
.edit_update(change)?
.is_some_and(|update| update.doc_changed() || update.selection_changed()))
}
pub(crate) fn edit_update(
&mut self,
change: impl FnOnce(&mut Editor, &mut Env<'_>) -> CommandResult,
) -> DesktopResult<Option<Update>> {
let mut lines = HostLines::new(&mut self.layout, &mut self.measurer);
let update = self.doc.edit(self.now, &mut lines, change)?;
if let Some(update) = &update {
self.track(std::slice::from_ref(&update.commit));
self.reveal = true;
self.blink_from = self.now;
}
Ok(update)
}
pub(crate) fn track(&mut self, commits: &[Commit]) {
let doc = self.doc.document();
for commit in commits {
self.layout.apply(doc, commit);
}
if doc.version() != commits.last().map_or(self.synced, |commit| commit.version) {
self.layout.resync(doc);
}
self.synced = doc.version();
self.dirty = true;
}
fn display_options(&self, top: f32, bottom: f32) -> DisplayOptions {
let options = DisplayOptions::viewport(top, bottom);
let Some(caret) = self.caret() else {
return options.selection(self.doc.selection());
};
if self.focused && self.caret_on() {
options.caret(caret)
} else {
options
}
}
pub(crate) fn caret_on(&self) -> bool {
let period = self.options.caret_blink;
if period.is_zero() {
return true;
}
let elapsed = self.now.saturating_sub(self.blink_from);
(elapsed.as_nanos() / period.as_nanos()).is_multiple_of(2)
}
#[must_use]
pub fn next_blink(&self) -> Option<Duration> {
let period = self.options.caret_blink;
if !self.focused || period.is_zero() || self.caret().is_none() {
return None;
}
let elapsed = self.now.saturating_sub(self.blink_from).as_nanos();
let phases = elapsed / period.as_nanos() + 1;
let next = u64::try_from(phases * period.as_nanos()).unwrap_or(u64::MAX);
Some(self.blink_from + Duration::from_nanos(next))
}
fn ensure_viewport(&mut self) -> DesktopResult<FrameInfo> {
let (top, bottom) = self.visible_range();
let update = self
.layout
.ensure(self.doc.document(), &mut self.measurer, top, bottom)?;
self.scroll += update.shift;
Ok(FrameInfo {
laid_out: update.laid_out,
measured: update.measurer_calls,
..FrameInfo::default()
})
}
fn reveal_caret(&mut self, info: &mut FrameInfo) -> DesktopResult<()> {
for _ in 0..REVEAL_PASSES {
let Some(target) = self.head_rect().and_then(|rect| self.reveal_target(rect)) else {
return Ok(());
};
self.scroll = target.clamp(0.0, self.max_scroll());
let pass = self.ensure_viewport()?;
info.laid_out += pass.laid_out;
info.measured += pass.measured;
}
Ok(())
}
fn reveal_target(&self, rect: Rect) -> Option<f32> {
let padding = self.options.padding;
let top = rect.y + padding - REVEAL_MARGIN;
let bottom = rect.y + rect.height + padding + REVEAL_MARGIN;
if top < self.scroll {
return Some(top);
}
(bottom > self.scroll + self.viewport.height).then_some(bottom - self.viewport.height)
}
fn head_rect(&self) -> Option<Rect> {
let Selection::Text { head, .. } = self.doc.selection() else {
return None;
};
let caret = self.caret().unwrap_or(Caret::new(head));
self.layout
.caret_rect(caret)
.or_else(|| self.layout.block_rect(head.block))
}
pub(crate) fn visible_range(&self) -> (f32, f32) {
let top = self.scroll - self.options.padding;
(top, top + self.viewport.height)
}
fn max_scroll(&self) -> f32 {
let content = self.layout.height() + self.options.padding * 2.0;
(content - self.viewport.height).max(0.0)
}
pub(crate) fn column_left(&self) -> f32 {
let width = column_width(&self.options, self.viewport);
let spare = self.viewport.width - self.options.padding * 2.0 - width;
self.options.padding + (spare / 2.0).max(0.0)
}
pub(crate) fn to_view(&self, x: f32, y: f32) -> (f32, f32) {
(
x + self.column_left(),
y - self.scroll + self.options.padding,
)
}
pub(crate) fn to_document(&self, x: f32, y: f32) -> (f32, f32) {
(
x - self.column_left(),
y + self.scroll - self.options.padding,
)
}
pub(crate) fn to_view_rect(&self, rect: Rect) -> Rect {
let (x, y) = self.to_view(rect.x, rect.y);
Rect::new(x, y, rect.width, rect.height)
}
}
fn column_width(options: &EditorOptions, viewport: Viewport) -> f32 {
let available = viewport.width - options.padding * 2.0;
options
.max_width
.map_or(available, |max| available.min(max))
.max(1.0)
}
fn layout_options(options: &EditorOptions, viewport: Viewport) -> LayoutOptions {
LayoutOptions::new(column_width(options, viewport)).overscan(options.overscan)
}