canvist_desktop 0.2.2

The canvist rich-text editor for macOS, Windows, and Linux: a winit component painted with vello, with IME, clipboard, and AccessKit accessibility
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
//! The editor: a document, its layout, and the viewport onto it.

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;

/// How far inside the viewport's edges the caret is kept when it is
/// scrolled into view, in logical pixels.
const REVEAL_MARGIN: f32 = 16.0;
/// How many times revealing the caret re-measures: each pass replaces
/// estimated heights above it with measured ones, which can move it again.
const REVEAL_PASSES: usize = 4;

/// The size of the editor on screen.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Viewport {
	/// The width in logical pixels.
	pub width: f32,
	/// The height in logical pixels.
	pub height: f32,
	/// Physical pixels per logical pixel.
	pub scale: f32,
}

impl Default for Viewport {
	fn default() -> Self {
		Self {
			width: 800.0,
			height: 600.0,
			scale: 1.0,
		}
	}
}

/// What [`DesktopEditor::frame`] did.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct FrameInfo {
	/// The document's height in logical pixels, including estimates for
	/// blocks not laid out yet.
	pub height: f32,
	/// Blocks laid out this frame.
	pub laid_out: usize,
	/// Measurer calls this frame: 0 when every segment was cached.
	pub measured: u64,
	/// Display items to paint.
	pub items: usize,
	/// When the caret next blinks, if it is blinking: the host should draw
	/// a frame then.
	pub next_blink: Option<Duration>,
}

/// The canvist editor for desktop apps.
///
/// It owns a [`Doc`] from an [`Engine`], lays it out with `canvist_layout`
/// and parley, and paints it through any `canvist_paint` painter. Input
/// arrives as [`InputEvent`](crate::InputEvent)s, so it runs headless in
/// tests exactly as it runs in a window; the `winit` feature adds the
/// window host.
///
/// `Handles` are the engine's typed handles, so commands of extensions that
/// were not registered do not compile:
///
/// ```
/// use canvist_desktop::DesktopEditor;
/// use canvist_desktop::EditorOptions;
/// use canvist_desktop::FontSource;
/// use canvist_headless::Engine;
/// use canvist_headless::Format;
///
/// let mut editor = DesktopEditor::new(
/// 	Engine::starter_kit(),
/// 	EditorOptions::new().fonts(FontSource::Bundled),
/// )?;
/// let kit = editor.handles();
///
/// editor.load(Format::Markdown, "Hello")?;
/// editor.select_all()?;
/// editor.run(&kit.bold.toggle())?;
///
/// assert_eq!(editor.export(Format::Markdown), "**Hello**");
/// # Ok::<(), canvist_desktop::DesktopError>(())
/// ```
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,
	/// The document version the layout last saw.
	synced: u64,
	pub(crate) viewport: Viewport,
	/// The document coordinate at the top of the viewport, before padding.
	pub(crate) scroll: f32,
	/// What the last frame painted.
	pub(crate) list: DisplayList,
	/// Whether the next frame should scroll the caret into view.
	reveal: bool,
	/// Whether something changed since the last frame.
	pub(crate) dirty: bool,
	pub(crate) focused: bool,
	/// When the caret last restarted its blink: on focus and on every edit.
	pub(crate) blink_from: Duration,
	/// The time of the last input, for the caret blink.
	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> {
	/// An editor with an empty document from `engine`.
	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(),
		}
	}

	/// The engine's typed handles, for commands and queries.
	#[must_use]
	pub fn handles(&self) -> Handles {
		self.engine.handles()
	}

	/// The engine the document belongs to.
	#[must_use]
	pub fn engine(&self) -> &Engine<Handles> {
		&self.engine
	}

	/// The document.
	#[must_use]
	pub fn doc(&self) -> &Doc {
		&self.doc
	}

	/// The editor state: document, selection, and stored marks, for typed
	/// queries such as `kit.bold.is_active(editor.state())`.
	#[must_use]
	pub fn state(&self) -> &EditorState {
		self.doc.state()
	}

	/// The options the editor was created with.
	#[must_use]
	pub fn options(&self) -> &EditorOptions {
		&self.options
	}

	/// The fonts, to build a painter's shaper.
	#[must_use]
	pub fn fonts(&self) -> &Fonts {
		&self.fonts
	}

	/// The layout, for geometry queries such as `caret_rect`.
	#[must_use]
	pub fn layout(&self) -> &DocumentLayout {
		&self.layout
	}

	/// Replace the document with `input` read as `format`. The caret goes
	/// to the start and the view to the top.
	pub fn load(&mut self, format: Format, input: &str) -> DesktopResult<()> {
		let doc = self.engine.parse(format, input)?;
		self.set_doc(doc)
	}

	/// Replace the document with `doc`, which must come from this editor's
	/// [`DesktopEditor::engine`], such as a shared document joined from Yjs
	/// state.
	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(())
	}

	/// The document as `format`.
	#[must_use]
	pub fn export(&self, format: Format) -> String {
		self.doc.export(format)
	}

	/// Run `command`, from the engine's typed handles. Returns whether it
	/// applied.
	pub fn run(&mut self, command: &Command) -> DesktopResult<bool> {
		self.edit(|editor, env| editor.run(command, env))
	}

	/// Whether `command` would apply. Nothing changes.
	pub fn can(&mut self, command: &Command) -> DesktopResult<bool> {
		Ok(self.doc.can(command)?)
	}

	/// Undo the last change.
	pub fn undo(&mut self) -> DesktopResult<bool> {
		self.edit(Editor::undo)
	}

	/// Redo the last undone change.
	pub fn redo(&mut self) -> DesktopResult<bool> {
		self.edit(Editor::redo)
	}

	/// Select the whole document.
	pub fn select_all(&mut self) -> DesktopResult<bool> {
		let select_all = command(commands::select_all);
		self.run(&select_all)
	}

	/// Select `selection`.
	pub fn select(&mut self, selection: Selection) -> DesktopResult<bool> {
		self.edit(|editor, env| editor.select(selection, env))
	}

	/// Register a TrueType or OpenType font from its bytes, for themes that
	/// name it, and return the family names it added. Text laid out with a
	/// fallback face lays out again.
	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
	}

	/// Size the editor: `width` and `height` in logical pixels, at `scale`
	/// physical pixels per logical pixel.
	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;
	}

	/// The editor's size.
	#[must_use]
	pub fn viewport(&self) -> Viewport {
		self.viewport
	}

	/// The document coordinate at the top of the viewport.
	#[must_use]
	pub fn scroll_top(&self) -> f32 {
		self.scroll
	}

	/// Scroll so document coordinate `top` is at the top of the viewport,
	/// within the document's bounds.
	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;
		}
	}

	/// Whether something changed that the next frame should paint.
	#[must_use]
	pub fn needs_repaint(&self) -> bool {
		self.dirty
	}

	/// Lay out the viewport, scroll the caret into view after edits, and
	/// build the display list that [`DesktopEditor::paint`] draws.
	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));
		// Layout culls whole blocks; drop the lines of long blocks that are
		// off screen too, so painting costs what the screen shows.
		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)
	}

	/// The display list the last frame built, in document coordinates.
	#[must_use]
	pub fn display_list(&self) -> &DisplayList {
		&self.list
	}

	/// The caret, when the selection is collapsed.
	#[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,
		}
	}

	/// The caret's rectangle, or the selection head's, in the editor's
	/// logical coordinates: where IME candidate windows go.
	#[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))
	}

	/// Make a change through the editor with this layout's line navigator,
	/// then let layout account for it.
	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()))
	}

	/// [`DesktopEditor::edit`], returning the update it applied.
	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)
	}

	/// Tell layout about `commits`, applied to the document in order. When
	/// the document moved further than they account for (a collaboration
	/// binding can apply a follow-up of its own), layout re-reads it.
	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;
	}

	/// The display options for document range `top..bottom`: the caret while
	/// focused and in the visible half of its blink, or the selection.
	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
		}
	}

	/// Whether the blinking caret is in its visible half.
	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)
	}

	/// When the caret next turns on or off, on the clock input events are
	/// stamped with, or `None` while it is not blinking.
	#[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))
	}

	/// Lay out the visible range, keeping content on screen still when
	/// blocks above it replaced estimated heights with measured ones.
	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()
		})
	}

	/// Scroll just far enough that the caret (or the selection's head) is
	/// inside the viewport, measuring the blocks on the way.
	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(())
	}

	/// Where to scroll so `rect`, in document coordinates, is inside the
	/// viewport with a margin, or `None` when it already is.
	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)
	}

	/// The rectangle of the selection's head, from layout when its block is
	/// laid out and from the block's estimated rectangle otherwise.
	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))
	}

	/// The document range the viewport shows.
	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)
	}

	/// Where the document's left edge is in the editor.
	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)
	}

	/// A document point in the editor's logical coordinates.
	pub(crate) fn to_view(&self, x: f32, y: f32) -> (f32, f32) {
		(
			x + self.column_left(),
			y - self.scroll + self.options.padding,
		)
	}

	/// An editor point in document coordinates.
	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)
	}
}

/// The document column's width in `viewport`.
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)
}