Debian Codegraph @

ivette/src/dome/renderer/text/buffers.ts

raw
1 /* ************************************************************************ */
2 /* */
3 /* This file is part of Frama-C. */
4 /* */
5 /* Copyright (C) 2007-2022 */
6 /* CEA (Commissariat à l'énergie atomique et aux énergies */
7 /* alternatives) */
8 /* */
9 /* you can redistribute it and/or modify it under the terms of the GNU */
10 /* Lesser General Public License as published by the Free Software */
11 /* Foundation, version 2.1. */
12 /* */
13 /* It is distributed in the hope that it will be useful, */
14 /* but WITHOUT ANY WARRANTY; without even the implied warranty of */
15 /* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
16 /* GNU Lesser General Public License for more details. */
17 /* */
18 /* See the GNU Lesser General Public License version 2.1 */
19 /* for more details (enclosed in the file licenses/LGPLv2.1). */
20 /* */
21 /* ************************************************************************ */
22
23 /* eslint-disable @typescript-eslint/explicit-function-return-type */
24 /* eslint-disable @typescript-eslint/no-explicit-any */
25
26 // --------------------------------------------------------------------------
27 // --- Text Documents
28 // --------------------------------------------------------------------------
29
30 /**
31 @packageDocumentation
32 @module dome/text/buffers
33 */
34
35 import Emitter from 'events';
36 import CodeMirror from 'codemirror/lib/codemirror';
37 import { Debug } from 'dome';
38
39 const D = new Debug('Dome.text');
40
41 export type Range = { from: CodeMirror.Position; to: CodeMirror.Position };
42
43 export interface Decorator {
44 /** @return a className to apply on markers with the identifier. */
45 (id: string): string | undefined;
46 }
47
48 export interface TextMarkerProxy {
49 clear(): void;
50 changed(): void;
51 find(): Range | undefined;
52 }
53
54 /**
55 Text Marker options.
56
57 Inherits CodeMirror
58 [TextMerkerOptions](https://codemirror.net/doc/manual.html#api_marker).
59 */
60 export interface MarkerProps extends CodeMirror.TextMarkerOptions {
61 id?: string;
62 hover?: boolean;
63 className?: string;
64 }
65
66 export interface CSSMarker {
67 /** Hover class `'dome-xHover-nnn'` */
68 classNameId: string;
69 /** Marker id */
70 id: string | undefined;
71 /** Hovered marker */
72 hover: boolean;
73 /** Size in character */
74 length: number;
75 }
76
77 // --------------------------------------------------------------------------
78 // --- Batched Update
79 // --------------------------------------------------------------------------
80
81 const BATCH_OPS = 500;
82 const BATCH_DELAY = 5;
83 const BATCH_RMAX = 1000; // max tag range for sorting
84 const BATCH_MARGINS = 20; // visible lines above the viewport
85
86 interface MarkerOptions {
87 id?: string;
88 hover?: boolean;
89 className?: string;
90 options: CodeMirror.TextMarkerOptions;
91 }
92
93 interface StackedMarker extends MarkerOptions {
94 startIndex: number;
95 }
96
97 interface BufferedMarker extends MarkerOptions {
98 startIndex: number;
99 stopIndex: number;
100 }
101
102 type BufferedTag = BufferedMarker | undefined;
103
104 function rankTag(lmin: number, lmax: number, tg: BufferedTag) {
105 if (tg && (lmin <= tg.stopIndex || tg.startIndex <= lmax)) {
106 const size = tg.stopIndex - tg.startIndex;
107 return size < BATCH_RMAX ? size : BATCH_RMAX;
108 }
109 return BATCH_RMAX;
110 }
111
112 function byVisibleTag(lmin: number, lmax: number) {
113 return (a: BufferedTag, b: BufferedTag) => (
114 rankTag(lmin, lmax, a) - rankTag(lmin, lmax, b)
115 );
116 }
117
118 // --------------------------------------------------------------------------
119 // --- Buffer
120 // --------------------------------------------------------------------------
121
122 export type TextMarker = CodeMirror.TextMarker<CodeMirror.MarkerRange>;
123
124 export interface RichTextBufferProps {
125
126 /**
127 * CodeMirror [mode](https://codemirror.net/mode/index.html) specification.
128 */
129 mode?: any;
130
131 /** Maximum number of lines in the buffer. */
132 maxlines?: number;
133
134 }
135
136 /**
137 Rich Text Content and State.
138
139 A buffer encapsulate a CodeMirror document instance inside an standard
140 Node event emitter. CodeMirror signals are automatically linked back to
141 the event emitter (on a lazy basis).
142
143 All buffer modifications are stacked and executed asynchronously inside
144 CodeMirror batched operations to increase performance.
145
146 The `maxlines` will control the maximum number of lines kept in the buffer.
147 By default, it is set to `10000`, but you can use `null`, `0` or any negative
148 value to disable this behavior. See also `this.setMaxlines()` method.
149
150 Additionnaly, a Buffer maintains an _edited_ state internally that can
151 be manually updated, and that is automatically set to `true` when the
152 underlying CodeMirror document is changed. It is associated to an `'edited'`
153 event of the buffer, and can be used to manage the « Saved » / « Not-Saved »
154 state of an editor, for instance.
155
156 Typically, a sequence of changed events would fire a unique `'edited'` buffer
157 event, untill `setEdited(false)` is invoked. The `clear()` method also resets
158 the _edited_ state to `false`, but sill emit an `'edited'` event if the
159 buffer was not empty.
160
161 Buffers can also be updated programmatically by various methods. In addition
162 to specified CodeMirror modes, you can also attach text markers
163 programmatically with a push/pop API.
164
165 Text markers can be associated with an identifier, that can be used for
166 dynamic highlighting, called Decorations. Decorations are class names that
167 add styling attributes upon the current mode. Typically, consider only using
168 background colors, underlines and/or strike-through for decorations, since
169 font styles and colors are likely to be managed by CodeMirror modes, unless
170 you know exactly what your are doing.
171
172 The `setDecorator` method can be used to set or update
173 the highlighting function that computes the decoration of a text marker
174 from its identifier. When the decorations may have change, you shall either
175 set again the highlighting function with a call to `setDecorator()` or call
176 the `updateDecorations()` method. This also triggers the `'decorated'` event.
177
178 */
179
180 export class RichTextBuffer extends Emitter {
181
182 private document: CodeMirror.Doc;
183 private maxlines = 10000;
184 private editors: CodeMirror.Editor[] = [];
185 private cacheIndex = 0; // document index, negative if not computed
186 private bufferedText: string; // buffered text to append
187 private bufferedTags: BufferedTag[];
188 private stacked: StackedMarker[] = [];
189 private batched = false;
190
191 // Indexed by CSS property dome-xHover-nnnn
192 private cssmarkers = new Map<string, CSSMarker>();
193
194 // Indexed by marker user identifier
195 private textmarkers = new Map<string, TextMarker[]>();
196
197 private decorator?: Decorator;
198 private edited = false;
199 private focused = false;
200 private markid = 0;
201
202 constructor(props: RichTextBufferProps = {}) {
203 super();
204 const { mode, maxlines } = props;
205 this.document = new CodeMirror.Doc('', mode);
206 this.cacheIndex = -1;
207 this.bufferedTags = [];
208 this.bufferedText = '';
209 this.setMaxlines(maxlines);
210 this.setEdited = this.setEdited.bind(this);
211 this.setFocused = this.setFocused.bind(this);
212 this.clear = this.clear.bind(this);
213 this.append = this.append.bind(this);
214 this.setValue = this.setValue.bind(this);
215 this.getValue = this.getValue.bind(this);
216 this.updateDecorations = this.updateDecorations.bind(this);
217 this.onChange = this.onChange.bind(this);
218 this.doBatch = this.doBatch.bind(this);
219 this.log = this.log.bind(this);
220 }
221
222 /**
223 Internal CodeMirror
224 [document](https://codemirror.net/doc/manual.html#api_doc) instance.
225 */
226 getDoc(): CodeMirror.Doc { return this.document; }
227
228 // --------------------------------------------------------------------------
229 // --- Buffer Manipulation
230 // --------------------------------------------------------------------------
231
232 /** Clear buffer contents and resets _edited_ state. */
233 clear() { this.setValue(''); }
234
235 /**
236 Writes in the buffer. All parameters are converted to string and joined
237 with spaces. The generated change event has origin `'buffer'` and it does
238 not modifies the _edited_ internal state.
239 */
240 append(...values: any[]) {
241 if (values.length > 0) {
242 const text = values.join(' ');
243 this.bufferedText += text;
244 this.armBatch();
245 }
246 }
247
248 /**
249 Starts a new line in the buffer. If the current buffer content does not
250 finish at the beginning of a fresh line, inserts a newline character.
251 */
252 flushline() {
253 const doc = this.document;
254 const buf = this.bufferedText;
255 if (buf === '') {
256 const start = doc.posFromIndex(Infinity);
257 if (start.ch > 0) doc.replaceRange('\n', start, undefined, 'buffer');
258 this.cacheIndex = -1;
259 } else if (buf[buf.length - 1] !== '\n') this.bufferedText += '\n';
260 }
261
262 /**
263 Appends with newline and auto-scrolling. This is a short-cut to
264 `flushline()` followed by `append(...value,'\n')` and `scroll()`.
265 */
266 log(...values: any[]) {
267 this.flushline();
268 this.append(...values, '\n');
269 this.scroll();
270 }
271
272 /**
273 Replace all textual content with the given string.
274 Also remove all markers.
275 */
276 setValue(txt = '') {
277 this.document.setValue(txt);
278 this.cssmarkers.clear();
279 this.textmarkers.clear();
280 this.stacked = [];
281 this.bufferedTags = [];
282 this.bufferedText = '';
283 this.cacheIndex = 0;
284 this.edited = false;
285 this.focused = false;
286 this.markid = 0;
287 }
288
289 /** Return the textual contents of the buffer. */
290 getValue() { return this.document.getValue(); }
291
292 // --------------------------------------------------------------------------
293 // --- Text Markers
294 // --------------------------------------------------------------------------
295
296 /**
297 Opens a text marker.
298
299 Opens a text marker at the current (end) position in the buffer.
300
301 The text marker is stacked and would be actually created on the matching
302 [[closeTextMarker]] call. It will be applied to the full range of text
303 inserted between its associated [[openTextMarker]] and [[closeTextMarker]]
304 calls.
305
306 The returned text marker is actually a _proxy_ to the text marker that will
307 be eventually created by [[closeTextMarker]]. Its methods are automatically
308 forwarded to the actual `CodeMirror.TextMarker` instance, once created.
309 Hence, you can safely invoke these methods on either the _proxy_ or the
310 _final_ text marker at your convenience.
311 */
312 openTextMarker(props: MarkerProps) {
313 const { id, hover, className, ...options } = props;
314 const startIndex = this.getLastIndex() + this.bufferedText.length;
315 this.stacked.push({ startIndex, id, hover, className, options });
316 }
317
318 /**
319 Closes the last opened marker.
320
321 Returns the (actual) [text marker]
322 (https://codemirror.net/doc/manual.html#api_marker) ; the proxy
323 returned by the corresponding call to [[openTextMarker]] is automatically
324 bound to the actual one.
325
326 */
327 closeTextMarker() {
328 const tag = this.stacked.pop();
329 if (tag) {
330 const stopIndex = this.getLastIndex() + this.bufferedText.length;
331 this.bufferedTags.push({ stopIndex, ...tag });
332 this.armBatch();
333 }
334 }
335
336 /** Lookup for the text markers associated with a marker identifier.
337 Remove the marked tags from the buffered tag array. */
338 findTextMarker(id: string): TextMarker[] {
339 this.doFlushText();
340 this.bufferedTags.forEach((tg, idx) => {
341 if (tg?.id === id) {
342 this.doMark(tg);
343 this.bufferedTags[idx] = undefined;
344 }
345 });
346 return this.textmarkers.get(id) ?? [];
347 }
348
349 /** Lopokup for a hover class. */
350 findHover(className: string): CSSMarker | undefined {
351 return this.cssmarkers.get(className);
352 }
353
354 // --------------------------------------------------------------------------
355 // --- Highlighter
356 // --------------------------------------------------------------------------
357
358 /**
359 Define highlighter.
360
361 @param fn - highlighter, `fn(id)` shall return a className to apply
362 on text markers with the provided identifier.
363 */
364 setDecorator(fn: Decorator) {
365 this.decorator = fn;
366 this.emit('decorated');
367 }
368
369 /**
370 Current highlighter.
371 */
372 getDecorator() { return this.decorator; }
373
374 /**
375 Rehighlight document.
376
377 Emits the `'decorated'` event to make editors
378 updating the decorations of identified text markers.
379
380 This can be used when decoration shall be re-computed,
381 even if the decoration function was not modified.
382
383 The method is bound to `this`.
384 */
385 updateDecorations() { this.emit('decorated'); }
386
387 // --------------------------------------------------------------------------
388 // --- Edited State
389 // --------------------------------------------------------------------------
390
391 /**
392 Set edited state.
393
394 The method is automatically invoked by editor views when the user actually
395 edit the document. The state is _not_ modified when modifying the document
396 from buffer's own methods, _eg._ `append()` and `clear()`.
397
398 The method fires the `'edited'` event on modifications. This method is
399 bound to `this`, hence `this.setEdited` can be used as a valid callback
400 function.
401
402 @param state - the new edited state (defaults to `true`).
403 */
404 setEdited(state = true) {
405 if (state !== this.edited) {
406 this.edited = state;
407 this.emit('edited', state);
408 }
409 }
410
411 /**
412 Set focused state.
413
414 The method is automatically invoked by editor views when they gain or lose
415 focus or when the user actually interact with the view,
416 eg. mouse-scrolling, edition, cursor move, etc. The escape key `ESC`
417 explicitly relax the _focused_ state, although the editor view might
418 actually keep the _focus_.
419
420 When a buffer is _focused_, shrinking and auto-scrolling are temporarily
421 deactivated to avoid confusing user's experience.
422
423 The method fires `'focused'` events on modifications. This method is bound
424 to `this`, hence `this.setEdited` can be used as a valid callback function.
425
426 @param focus - the new focused state (defaults to `true`).
427 */
428 setFocused(state = true) {
429 if (state !== this.focused) {
430 this.focused = state;
431 this.emit('focused', state);
432 this.doShrink();
433 }
434 }
435
436 /** Returns the current _edited_ state. */
437 isEdited() { return this.edited; }
438
439 /** Returns the current _focused_ state. */
440 isFocused() { return this.focused; }
441
442 // --------------------------------------------------------------------------
443 // --- Document Scrolling
444 // --------------------------------------------------------------------------
445
446 /**
447 Set (or unset) the maximum number of lines.
448
449 By default, the maximum number of lines is set to `10,000` to avoid
450 unwanted memory leaks. Setting `null`, `0` of any negative value cancel the
451 management of maximum number of lines.
452
453 Although CodeMirror is powerfull enough to manage huge buffers, you should
454 turn this limit _off_ with care.
455 */
456 setMaxlines(maxlines = 10000) {
457 this.maxlines = maxlines > 0 ? 1 + maxlines : 0;
458 this.doShrink();
459 }
460
461 /**
462 Requires all connected views to scroll to the
463 specified line or identified marker.
464
465 @param position -
466 defaults to the end of buffer (when not focused).
467 */
468 scroll(position?: string | number): void {
469 if (position === undefined) {
470 if (!this.focused) {
471 this.doFlushText();
472 this.emit('scroll', this.document.lastLine());
473 }
474 } else if (typeof position === 'number') {
475 this.doFlushText();
476 this.emit('scroll', position);
477 } else if (typeof position === 'string') {
478 let line = Infinity;
479 this.findTextMarker(position).forEach((tm) => {
480 const rg = tm.find();
481 if (rg && rg.from) {
482 const ln = rg.from.line;
483 if (ln < line) line = ln;
484 }
485 });
486 if (line !== Infinity)
487 this.emit('scroll', line);
488 }
489 }
490
491 /**
492 Requires all connected views to select the specified line and to place it
493 at the top of their displays.
494
495 @param line - the line number to select
496 */
497 setCursorOnTop(line: number): void {
498 this.forEach((cm) => {
499 cm.setCursor(cm.lastLine());
500 cm.setCursor(line - 1);
501 });
502 }
503
504 // --------------------------------------------------------------------------
505 // --- Document Linking
506 // --------------------------------------------------------------------------
507
508 private onChange(
509 _editor: CodeMirror.Editor,
510 change: CodeMirror.EditorChange,
511 ) {
512 if (change.origin !== 'buffer') {
513 this.setEdited(true);
514 this.cacheIndex = -1;
515 }
516 this.emit('change');
517 }
518
519 /**
520 Binds this buffer to a CodeMirror instance.
521
522 Uses CodeMirror linked documents to allow several CodeMirror instances to
523 be linked to the same buffer. Can be released with [[unlink]].
524
525 @param cm - code mirror instance to link this document in.
526 */
527 link(cm: CodeMirror.Editor) {
528 const newDoc = this.document.linkedDoc(
529 { sharedHist: true, mode: undefined },
530 );
531 cm.swapDoc(newDoc);
532 cm.on('change', this.onChange);
533 this.editors.push(cm);
534 }
535
536 /**
537 Release a linked CodeMirror document previously linked with [[link]].
538 @param cm - the code mirror instance to unlink
539 */
540 unlink(cm: CodeMirror.Editor) {
541 const oldDoc = cm.getDoc();
542 this.document.unlinkDoc(oldDoc);
543 this.editors = this.editors.filter((cm0) => {
544 if (cm === cm0) {
545 cm.off('change', this.onChange);
546 return false;
547 }
548 return true;
549 });
550 }
551
552 /**
553 Iterates over each linked CodeMirror instances
554
555 The operation `fn` is performed on each code mirror
556 instance currently linked to this buffer.
557
558 Exceptions raised by `fn` are catched and dumped in the console.
559 */
560 forEach(fn: (editor: CodeMirror.Editor) => void) {
561 this.editors.forEach((cm) => {
562 try { fn(cm); } catch (e) { D.error(e); }
563 });
564 }
565
566 // --------------------------------------------------------------------------
567 // --- Update Operations
568 // --------------------------------------------------------------------------
569
570 /* Append Operation */
571 private doFlushText() {
572 const text = this.bufferedText;
573 if (text.length > 0) {
574 this.bufferedText = '';
575 const doc = this.document;
576 const start = doc.posFromIndex(Infinity);
577 doc.replaceRange(text, start, undefined, 'buffer');
578 this.cacheIndex = -1;
579 this.doShrink();
580 }
581 }
582
583 /* Shrink Operation */
584 private doShrink() {
585 const lines = this.document.lineCount();
586 if (lines > this.maxlines) {
587 const p = this.document.firstLine();
588 const q = p + lines - this.maxlines;
589 this.document.replaceRange(
590 '',
591 { line: p, ch: 0 },
592 { line: q, ch: 0 },
593 'buffer',
594 );
595 this.cacheIndex = -1;
596 }
597 }
598
599 /* Close Operation */
600 private doMark(tag: BufferedMarker) {
601 const { id, hover, className, startIndex, stopIndex } = tag;
602 let markerId;
603 if (id || hover) {
604 markerId = `dome-xHover-${this.markid++}`;
605 const cmark = {
606 id,
607 classNameId: markerId,
608 hover: hover ?? (id !== undefined),
609 length: stopIndex - startIndex,
610 };
611 this.cssmarkers.set(markerId, cmark);
612 }
613 const fullClassName = [
614 'dome-xMarked',
615 id && (`dome-xMark-${id}`),
616 markerId,
617 className,
618 ].filter((s) => !!s).join(' ');
619 const options = {
620 shared: true,
621 className: fullClassName,
622 ...tag.options,
623 };
624 const doc = this.document;
625 const start = doc.posFromIndex(startIndex);
626 const stop = doc.posFromIndex(stopIndex);
627 const marker = doc.markText(start, stop, options);
628 if (id) {
629 const markers = this.textmarkers;
630 const ms = markers.get(id);
631 if (ms === undefined)
632 markers.set(id, [marker]);
633 else
634 ms.push(marker);
635 }
636 }
637
638 private doFilterTags() {
639 const tgs = this.bufferedTags;
640 if (tgs.length > 0 && this.editors.length > 0) {
641 let lmin = Infinity;
642 let lmax = 0;
643 this.forEach((cm) => {
644 const { from: fr, to } = cm.getViewport();
645 if (to > lmax) lmax = to;
646 if (fr < lmin) lmin = fr;
647 });
648 if (lmin <= lmax) tgs.sort(byVisibleTag(lmin, lmax + BATCH_MARGINS));
649 }
650 return tgs.splice(0, BATCH_OPS);
651 }
652
653 private getLastIndex() {
654 if (this.cacheIndex < 0) {
655 const doc = this.document;
656 const line = doc.lastLine() + 1;
657 this.cacheIndex = doc.indexFromPos({ line, ch: 0 });
658 }
659 return this.cacheIndex;
660 }
661
662 // --------------------------------------------------------------------------
663 // --- Batched Operations
664 // --------------------------------------------------------------------------
665
666 private armBatch() {
667 if (!this.batched) {
668 this.batched = true;
669 setTimeout(this.doBatch, BATCH_DELAY);
670 }
671 }
672
673 /* Batch Operation */
674 private doBatch() {
675 this.batched = false;
676 if (!this.bufferedText.length && !this.bufferedTags.length) return;
677 try {
678 // Start Operations
679 this.forEach((cm) => cm.startOperation());
680 // Flush Text
681 this.doFlushText();
682 // Mark Tags
683 this.doFilterTags().forEach((tg) => { if (tg) this.doMark(tg); });
684 // End Operations
685 this.forEach((cm) => cm.endOperation());
686 } finally {
687 if (this.bufferedTags.length > 0)
688 this.armBatch();
689 }
690 }
691
692 }
693
694 // --------------------------------------------------------------------------