Scoop API

scoop:scoop.ui:0.1.0

src/text/selectable/host.scoop

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

1package scoop.ui.text
3import scoop.collections.HashSet
4import scoop.graphics.*
5import scoop.graphics.text.*
6import scoop.platform.concurrent.currentThreadId
7import scoop.surface.*
8import scoop.ui.*
9import scoop.window.*
11/** Read-only directional selection over a real styled paragraph, without an editing document. */
12public class SelectableTextHost public constructor(
13 internal val scope: ComponentScope,
14 initialFonts: FontCollection,
15 initialContent: StyledText,
16 initialOptions: SelectableTextOptions = SelectableTextOptions()
17): Closeable {
18 private val thread = currentThreadId()
19 internal val paragraph = ParagraphHost()
20 internal var fonts = initialFonts
21 internal var content = initialContent
22 internal var semanticText: SelectableSemanticText? = None
23 internal val semantics = SemanticTextHost()
24 internal var semanticLayout: SelectableSemanticLayout? = None
25 internal var options = initialOptions
26 internal var closed = false
27 internal val selected = state(EditorSelection(TextPosition(0L), TextPosition(0L)))
28 internal var preferredX: Double? = None
29 internal var changed: (TextPosition, TextPosition) -> Unit = { _, _ -> Unit }
30 internal var actions: Array<SelectableAction> = []
31 internal var decorations: Array<TextRangeDecoration> = []
32 internal var accepted: SelectableFrame? = None
33 internal var staged: SelectableFrame? = None
34 internal var drag: SelectableDrag? = None
35 public val area =
36 scope.createArea(focusable = true) {
37 context,
38 event -> selectableHandle(this, context, event)
39 }
40 public val focus = scope.focusTarget(area)
41 internal val primarySelection = PrimaryTextSelection(scope.nativeWindow)
42 internal val dataSource = createSelectableDragSource(this)
43 internal val contextMenu =
44 TextContextMenu(
45 scope,
46 area,
47 { options.contextMenu },
48 { selectableMenuReady(this) },
49 { command -> execute(command) },
50 false
51 )
52 internal val touchPress = createSelectableContactPress(this)
53 internal val touchHandles = createSelectableSelectionHandles(this)
54 private val activity = area.scope.observeActivity { activityChanged() }
55 private val windowFocus =
56 scope.observeWindow(scope.nativeWindow) {
57 event -> when (event) {
58 case Focused(_) -> {
59 if (!closed && scope.isMounted && area.scope.activity.hasFocus)
60 activityChanged()
61 }
62 else -> {}
63 }
64 }
66 private fun activityChanged() {
67 if (closed || !scope.isMounted)
68 return
69 if (!scope.nativeWindow.isFocused || !area.scope.activity.hasFocus) {
70 dataSource?.cancelCandidate()
71 selectableStopDrag(this)
72 }
73 contextMenu.refresh()
74 scope.requestFrame()
75 }
77 init {
78 options.check()
79 requireUi(!fonts.isClosed, "selectable text fonts are closed")
80 area.scope.captureHandler = { context, event -> selectableHandle(this, context, event) }
81 area.scope.defaultAction = { context, event -> selectableHandle(this, context, event) }
82 area.scope.onEventFinished = { event -> selectableFinished(this, event) }
83 area.scope.enabled = options.enabled
84 dataSource?.update()
85 scope.routeChildren(area)
86 refreshMenuCommands()
87 }
89 public val isClosed: Boolean get() {
90 checkUiThread(thread);
91 return closed
92 }
93 public val anchor: TextPosition get() {
94 checkOpen();
95 return selected.value.anchor
96 }
97 public val cursor: TextPosition get() {
98 checkOpen();
99 return selected.value.cursor
100 }
101 public val selection: Utf8Selection get() {
102 checkOpen();
103 return Utf8Selection(anchor.byteOffset, cursor.byteOffset)
104 }
105 /** Borrowed from the last accepted frame. */
106 public val layout: TextLayout get() {
107 checkOpen();
108 return accepted?.layout ?:
109 throw IllegalStateException(Some("selectable text has no accepted layout"))
110 }
111 public fun selectionBounds(): Array<TextBox> {
112 checkOpen()
113 val frame = inputFrame() ?: return []
114 val range = selection.range
115 return frame.layout.selection(TextRange(range.start, range.end))
116 }
117 public fun actionInteraction(key: String): InteractionState? {
118 checkOpen()
119 for (action in actions)
120 if (action.input.key == key)
121 return Some(action.press.interaction)
122 return None
123 }
124 internal fun checkOpen() {
125 checkUiThread(thread)
126 if (closed || !scope.isMounted)
127 throw IllegalStateException(Some("selectable text host is no longer mounted"))
128 }
129 internal fun inputFrame(): SelectableFrame? {
130 val frame = accepted ?: return None
131 return if (frame.content.text == content.text)
132 Some(frame)
133 else
134 None
135 }
136 public fun update(
137 fonts: FontCollection,
138 content: StyledText,
139 options: SelectableTextOptions = SelectableTextOptions(),
140 focus: FocusOptions = FocusOptions(),
141 actions: Array<TextRangeAction> = [],
142 decorations: Array<TextRangeDecoration> = [],
143 onSelectionChanged: (TextPosition, TextPosition) -> Unit = { _, _ -> Unit }
144 ) {
145 checkOpen()
146 checkFocusMutation()
147 options.check()
148 requireUi(!fonts.isClosed, "selectable text fonts are closed")
149 val bytes = content.text.toByteArray()
150 val keys = HashSet<String>()
151 for (action in actions) {
152 requireUi(keys.add(action.key), "duplicate text range action key")
153 checkEditorRange(bytes, Utf8Range(action.range.start, action.range.end))
154 requireUi(action.range.start < action.range.end, "empty text range action")
155 }
156 for (decoration in decorations) {
157 checkEditorRange(bytes, Utf8Range(decoration.range.start, decoration.range.end))
158 for (color in [decoration.background, decoration.underline])
159 when (color) {
160 case Some(val value) -> checkSelectableColor(value)
161 case None -> {}
162 }
163 }
164 this.focus.options = focus
165 val textChanged = this.content.text != content.text
166 if (
167 textChanged || this.fonts !== fonts || this.options.contextMenu != options.contextMenu
168 ) {
169 touchPress.cancel()
170 touchHandles.hide()
171 }
172 if (
173 textChanged ||
174 (contextMenu.hasTarget && this.content.toPlainText() != content.toPlainText())
175 )
176 contextMenu.cancel()
177 if (textChanged)
178 primarySelection.close()
179 this.fonts = fonts
180 if (this.content !== content)
181 semanticText = None
182 this.content = content
183 this.options = options
184 touchPress.update(
185 options.enabled && options.touch.enabled,
186 options.touch.threshold,
187 options.touch.longPressDelay,
188 options.touch.multiTap,
189 options.touch.multiTapInterval
190 )
191 touchHandles.update(options.enabled, options.touch)
192 this.decorations = decorations
193 changed = onSelectionChanged
194 selectableActions(this, actions)
195 if (textChanged || !options.enabled) {
196 selectableStopDrag(this)
197 preferredX = None
198 }
199 if (textChanged) {
200 val current = selected.value
201 val boundaries = editorGraphemeBytes(content.text)
202 publishSelection(
203 EditorSelection(
204 selectableClamp(boundaries, current.anchor),
205 selectableClamp(boundaries, current.cursor)
206 )
207 )
208 }
209 if (!closed) {
210 refreshAdmission()
211 scope.requestLayout()
212 }
213 }
214 internal fun refreshAdmission() {
215 if (closed)
216 return
217 val available =
218 when (inputFrame()) {
219 case Some(_) -> options.enabled;
220 case None -> false
221 }
222 // Pending text blocks selection through inputFrame without retiring the existing focus.
223 area.scope.enabled = options.enabled
224 dataSource?.update()
225 refreshMenuCommands()
226 for (action in actions)
227 action.refresh(available, accepted)
228 }
229 public fun setSelection(anchor: TextPosition, cursor: TextPosition): Boolean {
230 checkOpen()
231 checkFocusMutation()
232 val bytes = content.text.toByteArray()
233 requireUi(
234 editorScalar(bytes, anchor.byteOffset) && editorScalar(bytes, cursor.byteOffset),
235 "invalid text selection"
236 )
237 preferredX = None
238 return publishSelection(EditorSelection(anchor, cursor))
239 }
240 internal fun publishSelection(value: EditorSelection, cancelContacts: Boolean = true): Boolean {
241 if (selected.value == value)
242 return false
243 if (cancelContacts) {
244 touchPress.cancel()
245 touchHandles.hide()
246 }
247 selected.value = value
248 refreshMenuCommands()
249 scope.requestFrame()
250 changed(value.anchor, value.cursor)
251 return true
252 }
253 public fun execute(command: TextEditCommand): Boolean {
254 checkOpen()
255 checkFocusMutation()
256 if (
257 !options.enabled ||
258 !scope.nativeWindow.isFocused ||
259 !area.scope.isInputAllowed ||
260 !area.scope.activity.hasFocus
261 )
262 return false
263 selectableStopDrag(this)
264 return selectableCommand(this, command)
265 }
266 /** Opens Copy and Select All at the current accepted selection or insertion position. */
267 public fun showContextMenu(): Boolean {
268 checkOpen()
269 checkFocusMutation()
270 return selectableContextMenu(this, None, None)
271 }
272 public fun measure(
273 context: MeasureContext,
274 constraints: Constraints,
275 settings: ParagraphStyle? = None,
276 inlines: Array<InlineView> = []
277 ): ParagraphMeasurement {
278 checkOpen()
279 return paragraph.measure(context, constraints, fonts, content, settings, inlines)
280 }
281 public fun scene(context: SceneContext, measurement: ParagraphMeasurement) {
282 checkOpen()
283 selectableScene(this, context, measurement)
284 }
285 public override fun close() {
286 checkUiThread(thread)
287 checkFocusMutation()
288 if (closed)
289 return
290 closed = true
291 semanticText = None
292 selectableStopDrag(this)
293 var failure: Throwable? = None
294 failure = cleanupUi(failure) { semantics.close() }
295 semanticLayout = None
296 failure = cleanupUi(failure) { contextMenu.close() }
297 failure = cleanupUi(failure) { primarySelection.close() }
298 failure = cleanupUi(failure) { touchPress.close() }
299 failure = cleanupUi(failure) { touchHandles.close() }
300 failure = cleanupUi(failure) { dataSource?.close() }
301 failure = cleanupUi(failure) { windowFocus.close() }
302 failure = cleanupUi(failure) { activity.close() }
303 for (action in actions)
304 failure = cleanupUi(failure) { action.close() }
305 actions = []
306 failure = cleanupUi(failure) { focus.close() }
307 failure = cleanupUi(failure) { area.close() }
308 failure = cleanupUi(failure) { staged?.close() }
309 staged = None
310 failure = cleanupUi(failure) { accepted?.close() }
311 accepted = None
312 failure = cleanupUi(failure) { paragraph.close() }
313 throwUi(failure)
314 }
317private fun selectableClamp(boundaries: Array<Long>, position: TextPosition): TextPosition {
318 var previous = 0L
319 for (boundary in boundaries) {
320 if (boundary >= position.byteOffset)
321 return TextPosition(
322 if (boundary == position.byteOffset || position.affinity == TextAffinity.Downstream)
323 boundary
324 else
325 previous,
326 position.affinity
327 )
328 previous = boundary
329 }
330 return TextPosition(previous, position.affinity)