Scoop API

scoop:scoop.ui:0.1.0

src/text/editor/host.scoop

Selected production source · src/text/editor/host.scoop

1package scoop.ui.text
3import scoop.graphics.*
4import scoop.graphics.text.*
5import scoop.platform.concurrent.currentThreadId
6import scoop.surface.*
7import scoop.ui.*
8import scoop.window.*
9import scoop.window.accessibility.SemanticTextDocument
11/** One mounted plain-text view, using the existing input, layout and scroll owners. */
12public class TextEditHost public constructor(
13 internal val scope: ComponentScope,
14 initialState: TextEditorState,
15 initialAppearance: TextEditAppearance,
16 initialOptions: TextEditOptions = TextEditOptions(),
17 private val onInteractionChanged: (TextEditInteraction) -> Unit = { _ -> Unit }
18): Closeable {
19 private val thread = currentThreadId()
20 internal val window = scope.nativeWindow
21 internal var current = initialState
22 internal var appearance = initialAppearance
23 internal var options = initialOptions
24 internal var placeholder = ""
25 internal var edited: (TextEditorState) -> Unit = { _ -> Unit }
26 internal var submitted: (TextEditorState) -> Unit = { _ -> Unit }
27 private var committed: (TextEditorState) -> Unit = { _ -> Unit }
28 internal var closed = false
29 internal var performing = false
30 internal var notifying = false
31 internal var connection: TextInputConnection? = None
32 internal var sessionEnabled = false
33 internal var retiring = false
34 internal var preferredX: Double? = None
35 internal val visual = State<TextEditInteraction>(TextEditInteraction())
36 internal val body = ParagraphCache()
37 internal val glyphs = ArrayList<EditorGlyphCache>()
38 internal var currentLayout: TextEditLayout? = None
39 internal var geometryGeneration = 0L
40 internal val hint = ParagraphCache()
41 internal val bodyKey = PaintKey()
42 internal val bodyInk = TextInkVersion()
43 internal val hintKey = PaintKey()
44 internal var currentDisplay: TextDisplay? = None
45 internal var currentProjection = initialOptions.projection
46 internal var content: StyledText? = None
47 internal var hintContent: StyledText? = None
48 internal var staged: EditorFrame? = None
49 internal var accepted: EditorFrame? = None
50 internal val semantics = SemanticTextHost()
51 internal var semanticDocument: SemanticTextDocument? = None
52 internal var semanticLayout: EditorSemanticLayout? = None
53 internal var revealNeeded = false
54 internal var revealRevision = 0UL
55 internal var caretVisible = true
56 internal var drag: EditorDrag? = None
57 public val scroll = ScrollState()
58 internal val viewport = scope.scrollViewport(scroll)
59 public val area =
60 scope.createArea(
61 focusable = true,
62 textInput = initialOptions.enabled && !initialOptions.readOnly
63 ) { context, event -> editorHandle(this, context, event) }
64 public val focus = scope.focusTarget(area, FocusOptions(visibility = FocusVisibility.Always))
65 internal val keyboard = EditorKeyboard(this)
66 internal val primarySelection = PrimaryTextSelection(window)
67 internal val contextMenu =
68 TextContextMenu(
69 scope,
70 area,
71 { options.contextMenu },
72 { !closed && options.enabled && area.isFocusActive },
73 { command -> execute(command) },
74 true
75 )
76 internal val blink = scope.createDeadline { editorBlink(this) }
77 internal val dragTimer = scope.createDeadline { editorDragTick(this) }
78 internal val dropTarget = createEditorDropTarget(this)
79 internal val dataSource = createEditorDragSource(this)
80 internal val touchPan =
81 scope.scrollPan(
82 area,
83 viewport,
84 editorTouchAxes(initialOptions),
85 options = editorTouchScroll(initialOptions)
86 )
87 internal val touchPress = createEditorContactPress(this)
88 internal val touchHandles = createEditorSelectionHandles(this)
89 private val touchScrollIntent =
90 scroll.observeIntent {
91 value -> when (value) {
92 case LayoutCorrection(_) -> {}
93 case User(_) -> {
94 dataSource?.cancelCandidate()
95 keyboard.cancelPending()
96 touchPress.cancel();
97 revealNeeded = false
98 }
99 case Programmatic(_) -> touchPress.cancel()
100 }
101 }
102 internal var caretPreferences = scope.interactionPreferences
103 private var caretScale = window.metrics?.scaleFactor
104 private val preferenceObserver =
105 scope.observeInteractionPreferences { next -> editorPreferencesChanged(this, next) }
106 private val geometryObserver =
107 scope.observeWindow(window) {
108 event -> when (event) {
109 case GeometryChanged(val metrics) -> {
110 keyboard.changed(window.softwareKeyboard)
111 if (caretScale != Some(metrics.scaleFactor)) {
112 caretScale = Some(metrics.scaleFactor)
113 if (
114 !closed &&
115 appearance.caretWidth ==
116 None &&
117 caretPreferences.caretWidthPixels !=
118 None
119 )
120 scope.requestLayout()
121 }
122 }
123 case SoftwareKeyboardChanged(val state) -> keyboard.changed(state)
124 else -> {}
125 }
126 }
128 private val activityObserver =
129 scope.observeWindowActivity { value -> editorWindowActivity(this, value) }
131 init {
132 initialOptions.check()
133 initialAppearance.check()
134 checkDocument(initialState.committedText)
135 area.scope.defaultAction = { context, event -> editorHandle(this, context, event) }
136 area.scope.onEventFinished = { event -> editorFinish(this, event) }
137 area.scope.enabled = initialOptions.enabled
138 viewport.paintCache = initialOptions.paintCache
139 viewport.physics = initialOptions.scrollPhysics
140 viewport.reduceMotion = appearance.reduceMotion
141 refreshMenuCommands()
142 current.inputStarter?.bind(this)
143 }
145 public val isClosed: Boolean get() {
146 checkUiThread(thread);
147 return closed
148 }
149 public val state: TextEditorState get() {
150 checkOpen();
151 return current
152 }
153 /** Last published interaction remains readable while input and resources retire. */
154 public val interaction: TextEditInteraction get() {
155 checkUiThread(thread);
156 return visual.value
157 }
158 internal fun publishInteraction(value: TextEditInteraction) {
159 if (visual.value == value)
160 return
161 visual.value = value
162 onInteractionChanged(value)
163 }
164 /** Borrowed from the last accepted frame; measurements carry their own layouts. */
165 public val layout: TextEditLayout get() {
166 checkOpen();
167 return accepted?.layout ?:
168 throw IllegalStateException(Some("text editor has no accepted layout"))
169 }
170 public val display: TextDisplay get() {
171 checkOpen()
172 return accepted?.display ?:
173 throw IllegalStateException(Some("text editor has no accepted layout"))
174 }
175 public fun caret(position: TextPosition): Rect? {
176 checkOpen()
177 val frame =
178 accepted ?: throw IllegalStateException(Some("text editor has no accepted layout"))
179 return frame.caretStyle.caret(
180 frame.layout,
181 editorVisualPosition(frame.layout, frame.display.toDisplay(position))
182 )
183 }
184 public fun selectionBounds(range: Utf8Range): Array<TextBox> {
185 checkOpen()
186 return layout.selection(display.displayRange(range))
187 }
188 internal val copyAllowed: Boolean get() =
189 when (options.copy) {
190 case Default -> !options.protectedText && !options.projection.masked
191 case Allow -> true
192 case Deny -> false
193 }
194 /** The last accepted viewport and its clamped offsets. */
195 public val scrollSnapshot: ScrollSnapshot get() {
196 checkOpen()
197 return accepted?.snapshot ?:
198 throw IllegalStateException(Some("text editor has no accepted layout"))
199 }
201 internal fun checkOpen() {
202 checkUiThread(thread)
203 if (closed || !scope.isMounted)
204 throw IllegalStateException(Some("text edit host is no longer mounted"))
205 }
206 internal fun checkDocument(text: String) {
207 requireUi(
208 options.multiline || !editorHasLineBreak(text),
209 "single-line editor contains a hard line break"
210 )
211 }
213 public fun update(
214 state: TextEditorState,
215 appearance: TextEditAppearance,
216 options: TextEditOptions = TextEditOptions(),
217 focus: FocusOptions = FocusOptions(),
218 placeholder: String = "",
219 onEdited: (TextEditorState) -> Unit = { _ -> Unit },
220 onSubmit: (TextEditorState) -> Unit = { _ -> Unit },
221 onCommitted: (TextEditorState) -> Unit = { _ -> Unit }
222 ) {
223 checkOpen()
224 checkFocusMutation()
225 options.check()
226 appearance.check()
227 requireUi(
228 options.multiline || !editorHasLineBreak(state.committedText),
229 "single-line editor contains a hard line break"
230 )
231 if (area.isFocusActive && options.enabled)
232 state.checkHost(this)
233 this.focus.options =
234 if (focus.visibility == FocusVisibility.Automatic)
235 focus.copy { this.visibility = FocusVisibility.Always }
236 else
237 focus
238 val blinkChanged = this.options.caretBlink != options.caretBlink
239 val rebound = current !== state
240 val layoutChanged =
241 rebound ||
242 this.appearance.fonts !==
243 appearance.fonts ||
244 this.appearance.textStyle !==
245 appearance.textStyle ||
246 this.appearance.placeholderStyle !==
247 appearance.placeholderStyle ||
248 this.appearance.caretWidth !=
249 appearance.caretWidth ||
250 this.placeholder !=
251 placeholder ||
252 this.options.multiline !=
253 options.multiline ||
254 this.options.wrap !=
255 options.wrap ||
256 this.options.direction !=
257 options.direction ||
258 this.options.alignment !=
259 options.alignment ||
260 this.options.projection !==
261 options.projection
262 val restart =
263 rebound ||
264 this.options.readOnly !=
265 options.readOnly ||
266 this.options.enabled !=
267 options.enabled ||
268 this.options.multiline !=
269 options.multiline
270 if (layoutChanged || restart || this.options.contextMenu != options.contextMenu) {
271 touchPress.cancel()
272 touchPan.cancel()
273 touchHandles.hide()
274 }
275 if (restart) {
276 if (rebound)
277 current.inputStarter?.detach(this)
278 retireConnection()
279 editorStopDrag(this, false)
280 if (current.ownsHost(this))
281 perform({ current.cancelComposition() }, notify = false)
282 if (rebound)
283 current.detachHost(this)
284 }
285 if (rebound) {
286 contextMenu.cancel()
287 primarySelection.close()
288 }
289 if (rebound || this.options.protectedText != options.protectedText) {
290 retireSemanticDocument()
291 }
292 current = state
293 this.appearance = appearance
294 this.options = options
295 keyboard.update(rebound)
296 touchPress.update(
297 options.enabled && options.touch.enabled,
298 options.touch.threshold,
299 options.touch.longPressDelay,
300 options.touch.multiTap,
301 options.touch.multiTapInterval
302 )
303 touchPan.update(editorTouchAxes(options), ScrollChain.Chain, editorTouchScroll(options))
304 touchHandles.update(options.enabled, options.touch)
305 this.placeholder = placeholder
306 edited = onEdited
307 submitted = onSubmit
308 committed = onCommitted
309 if (blinkChanged) {
310 blink.cancel()
311 caretVisible = true
312 }
313 viewport.paintCache = options.paintCache
314 viewport.physics = options.scrollPhysics
315 viewport.reduceMotion = appearance.reduceMotion
316 area.scope.enabled = options.enabled
317 area.textInput = options.enabled && !options.readOnly
318 dropTarget?.update()
319 dataSource?.update()
320 refreshMenuCommands()
321 if (area.isFocusActive && options.enabled)
322 current.attachHost(this)
323 if (restart)
324 invalidate()
325 current.inputStarter?.bind(this)
326 editorInteraction(this, area.isFocusActive, visual.value.hovered && options.enabled)
327 if (layoutChanged)
328 scope.requestLayout()
329 else
330 scope.requestFrame()
331 }
333 public fun measure(
334 constraints: Constraints,
335 cells: TextEditCells? = None,
336 scrollPadding: (Size, Size) -> ScrollPadding = { _, _ -> ScrollPadding() }
337 ): TextEditMeasurement {
338 checkOpen()
339 when (cells) {
340 case Some(_) -> requireUi(
341 !options.multiline,
342 "cell layout requires a single-line editor"
343 )
344 case None -> {}
345 }
346 return editorMeasure(this, constraints, cells, scrollPadding)
347 }
348 public fun scene(context: SceneContext, measurement: TextEditMeasurement) {
349 checkOpen()
350 editorScene(this, context, measurement)
351 }
352 public fun execute(command: TextEditCommand): Boolean {
353 checkOpen()
354 checkFocusMutation()
355 if (!options.enabled || !area.isFocusActive || !area.scope.isInputAllowed)
356 return false
357 editorStopDrag(this, false)
358 return editorCommand(this, command, None)
359 }
361 /** Opens a bound native menu at a visible caret or selection from accepted layout. */
362 public fun showContextMenu(): Boolean {
363 checkOpen()
364 checkFocusMutation()
365 return editorContextMenu(this, None, None)
366 }
368 internal fun modelChanged() {
369 if (closed || performing)
370 return
371 dropTarget?.update()
372 dataSource?.update()
373 refreshMenuCommands()
374 invalidate()
375 editorStopDrag(this, false)
376 current.breakUndoGroup()
377 retireConnection()
378 }
379 internal fun invalidate(cancelContacts: Boolean = true) {
380 if (cancelContacts) {
381 touchPress.cancel()
382 touchPan.cancel()
383 touchHandles.hide()
384 }
385 preferredX = None
386 if (!area.isClosed)
387 area.setCaret(None, Some(current.revision))
388 focus.node.root.focus.cancel(focus)
389 revealNeeded =
390 !(touchHandles.contact?.claimed ?: false) &&
391 area.isFocusActive &&
392 !focus.node.root.focus.pendingElsewhere(focus)
393 revealRevision = focus.node.root.surface.focusRevision
394 caretVisible = true
395 blink.cancel()
396 if (!closed && scope.isMounted)
397 scope.requestLayout()
398 }
399 internal fun retireConnection() {
400 if (!area.isClosed)
401 retiring = area.restartTextInput()
402 }
403 internal fun publishNative(after: TextInputOrigin? = None) {
404 if (
405 closed ||
406 retiring ||
407 !sessionEnabled ||
408 !area.isFocusActive ||
409 options.readOnly ||
410 !options.enabled
411 )
412 return
413 when (connection) {
414 case Some(val value) -> if (
415 window.publishTextInputState(value, current.inputState, after)
416 )
417 keyboard.publish()
418 case None -> {}
419 }
420 }
421 internal fun perform(
422 action: () -> Boolean,
423 endComposition: Boolean = false,
424 notify: Boolean = true,
425 cancelContacts: Boolean = true
426 ): Boolean {
427 val before = current.text
428 val beforeCommitted = current.committedText
429 val composing = current.isComposing
430 performing = true
431 val changed =
432 try {
433 action()
434 } finally {
435 performing = false
436 }
437 if (changed)
438 invalidate(cancelContacts || before != current.text)
439 if (endComposition && composing)
440 retireConnection()
441 refreshMenuCommands()
442 publishNative()
443 if (notify)
444 notifyEdited(before, beforeCommitted)
445 else
446 dataSource?.update()
447 return changed
448 }
449 internal fun notifyEdited(before: String, beforeCommitted: String) {
450 if (notifying || closed)
451 return
452 dataSource?.update()
453 val state = current
454 val revision = state.revision
455 val after = state.committedText
456 val completed = !state.isComposing && beforeCommitted != after
457 notifying = true
458 try {
459 if (before != state.text)
460 edited(state)
461 if (completed && !closed && current === state && state.revision == revision)
462 committed(state)
463 } finally {
464 notifying = false
465 }
466 }
468 public override fun close() {
469 checkUiThread(thread)
470 checkFocusMutation()
471 if (closed)
472 return
473 closed = true
474 val owned = current.detachHost(this)
475 var failure = cleanupUi(None) { current.inputStarter?.detach(this) }
476 failure = cleanupUi(failure) { semantics.close() }
477 failure = cleanupUi(failure) { retireSemanticDocument() }
478 semanticLayout = None
479 failure = cleanupUi(failure) { contextMenu.close() }
480 failure = cleanupUi(failure) { primarySelection.close() }
481 failure = cleanupUi(failure) { keyboard.close() }
482 failure = cleanupUi(failure) { touchPress.close() }
483 failure = cleanupUi(failure) { touchPan.close() }
484 failure = cleanupUi(failure) { touchHandles.close() }
485 failure = cleanupUi(failure) { touchScrollIntent.close() }
486 failure = cleanupUi(failure) { preferenceObserver.close() }
487 failure = cleanupUi(failure) { geometryObserver.close() }
488 failure = cleanupUi(failure) { activityObserver.close() }
489 failure = cleanupUi(failure) { blink.close() }
490 failure = cleanupUi(failure) { dragTimer.close() }
491 failure = cleanupUi(failure) { dropTarget?.close() }
492 failure = cleanupUi(failure) { dataSource?.close() }
493 drag = None
494 if (owned)
495 failure = cleanupUi(failure) { current.cancelComposition() }
496 failure = cleanupUi(failure) { focus.close() }
497 failure = cleanupUi(failure) { area.close() }
498 failure = cleanupUi(failure) { viewport.close() }
499 failure = cleanupUi(failure) { staged?.close() }
500 staged = None
501 failure = cleanupUi(failure) { accepted?.close() }
502 accepted = None
503 failure = cleanupUi(failure) { currentLayout?.release() }
504 currentLayout = None
505 for (glyph in glyphs)
506 failure = cleanupUi(failure) { glyph.close() }
507 glyphs.clear()
508 failure = cleanupUi(failure) { body.close() }
509 failure = cleanupUi(failure) { hint.close() }
510 throwUi(failure)
511 }