Scoop API

scoop:scoop.surface:0.1.0

src/shared/input/router.scoop

Selected production source · src/shared/input/router.scoop

1package scoop.surface
3import scoop.graphics.*
4import scoop.platform.concurrent.currentThreadId
5import scoop.platform.time.MonotonicTimeSource
6import scoop.window.*
8internal enum ImeSession {
9 Off, Opening(InputArea), On(InputArea), Closing(InputArea)
12/** Shared routing state; the window adapter supplies only invalidation and IME operations. */
13internal class InputRouter(
14 internal var osFocused: Boolean,
15 private val invalidate: () -> Unit,
16 internal val imeAllowed: (Boolean) -> Unit,
17 internal val imeCursor: (ImeCaret) -> Boolean,
18 internal val publishTextCommands: (TextCommandAvailability?) -> Unit = { _ -> }
19): Closeable {
20 private val thread = currentThreadId()
21 internal var closed = false
22 internal var windowRegions: WindowDecorations? = None
23 internal var scene = AreaScene([])
24 private val owned = ArrayList<InputScope>()
25 internal val rootScope = InputScope(this, None, None, { _, _ -> Unit })
26 private val retired = ArrayList<AreaScene>()
27 private val retiredScopes = ArrayList<InputScope>()
28 private var depth = 0
29 private var draining = false
30 internal var pending = false
31 internal var pointer: PointerState? = None
32 internal var inside = false
33 internal var hover: Array<InputScope> = []
34 internal var pressed: Array<InputScope>? = None
35 internal var pointerClaim: InputScope? = None
36 internal var scrollRoute: InputScrollRoute? = None
37 internal val gestureRoutes = ArrayList<InputGestureRoute>()
38 internal val contactRoutes = ArrayList<InputContactRoute>()
39 internal val buttons = ArrayList<MouseButton>()
40 internal var logicalFocus: InputArea? = None
41 internal var activeFocus: InputArea? = None
42 internal var activeFocusVisible = false
43 internal var publishedTextCommands: TextCommandAvailability? = None
44 internal var focusRevision = 0uL
45 internal val boundaries = ArrayList<InputBoundary>()
46 internal var pendingBoundaryChange = false
47 internal var boundaryRevision = 0uL
48 internal var ime = ImeSession.Off
49 internal var imeCaret: ImeCaret? = None
50 internal var imeConnection: TextInputConnection? = None
51 internal var imeRequest = 0UL
52 internal var textContinuation: InputTextContinuation? = None
53 internal var caretFrameValid = false
54 internal val activityObservers = ArrayList<InputActivityObserver>()
55 internal val pointerObservers = ArrayList<WindowPointerObserver>()
56 private var activityDirty = false
58 init {
59 owned.add(rootScope)
60 refreshTextCommands()
61 }
63 fun createArea(
64 focusable: Boolean,
65 textInput: Boolean,
66 parent: InputScope?,
67 handler: (RoutedEventContext, InputEvent) -> Unit
68 ): InputArea {
69 checkOpen()
70 val result =
71 InputArea(this, focusable || textInput, textInput, acceptParent(parent), handler)
72 owned.add(result.scope)
73 return result
74 }
75 fun createScope(
76 parent: InputScope?,
77 handler: (RoutedEventContext, InputEvent) -> Unit
78 ): InputScope {
79 checkOpen()
80 val result = InputScope(this, None, Some(acceptParent(parent)), handler)
81 owned.add(result)
82 return result
83 }
84 private fun acceptParent(parent: InputScope?): InputScope {
85 val result = parent ?: rootScope
86 requireInput(result.owner === this, "input parent belongs to another window")
87 result.checkOpen()
88 return result
89 }
90 fun reparent(scope: InputScope, parent: InputScope?) {
91 if (scope === rootScope) {
92 when (parent) {
93 case Some(_) -> throw IllegalArgumentException(
94 Some("window input root cannot be reparented")
95 )
96 case None -> {}
97 }
98 return
99 }
100 val next = acceptParent(parent)
101 var cursor: InputScope? = Some(next)
102 while (true) {
103 val current = cursor ?: break
104 requireInput(current !== scope, "input parent would create a cycle")
105 cursor = current.ancestor
106 }
107 if (!sameScope(scope.ancestor, Some(next))) {
108 scope.ancestor = Some(next)
109 changed()
110 }
111 }
112 fun beginFrame(): InputFrame {
113 checkOpen();
114 return InputFrame(this)
115 }
116 fun publish(frame: InputFrame) {
117 checkOpen()
118 requireInput(frame.owner === this, "input frame belongs to another window")
119 val next = frame.take()
120 try {
121 retired.add(scene)
122 }
123 catch (error: Throwable) {
124 throwFailure(cleanupFailure(Some(error)) { next.close() });
125 throw error
126 }
127 scene = next
128 caretFrameValid = true
129 pending = true
130 activityDirty = true
131 drain()
132 }
133 fun changed() {
134 checkThread()
135 if (closed)
136 return
137 windowRegions?.refreshEligibility()
138 pending = true
139 dispatch { invalidate() }
140 }
141 fun geometryChanged() {
142 imeCaret = None;
143 caretFrameValid = false
144 changed()
145 }
146 fun detached(scope: InputScope) {
147 when (textContinuation) {
148 case Some(val value) -> if (
149 value.source.scope === scope || value.target.scope === scope
150 )
151 textContinuation = None
152 case None -> {}
153 }
154 retiredScopes.add(scope)
155 var index = 0L
156 while (index < owned.size) {
157 if (owned[index] === scope) {
158 owned.removeAt(index);
159 break
160 }
161 index += 1L
162 }
163 changed()
164 }
165 fun dispatchWindowInput(
166 event: WindowEvent,
167 pointer: PointerEvent? = None,
168 platformInput: () -> Unit = {}
169 ) {
170 checkThread()
171 if (closed) return
172 val snapshot = pointerObservers.toArray()
173 val observation = when (pointer) {
174 case Some(val value) -> Some(PointerObservation.Pointer(value))
175 case None ->
176 when (event) {
177 case Focused(false) -> Some(PointerObservation.FocusLost)
178 else -> None
179 }
180 }
181 var failure = cleanupFailure(None) {
182 dispatch {
183 when (event) {
184 case Contact(val value) -> contactEvent(value)
186 case Focused(val value) -> {
187 osFocused = value
188 pending = true
189 if (!value)
190 cancelWindowInput(
191 InputCancelReason.Window(PointerCancelReason.FocusLost),
192 inputObservation()
193 )
194 }
196 case Keyboard(val value) -> routeFocused(InputEvent.Keyboard(value))
197 case TextCommand(val value) -> routeFocused(InputEvent.TextCommand(value))
198 case ModifiersChanged(val value) ->
199 notifyFocused(
200 InputEvent.ModifiersChanged(value)
201 )
202 case TextInput(val value) -> textEvent(value)
203 else -> platformInput()
204 }
205 }
206 }
207 if (!closed) {
208 when (observation) {
209 case Some(val value) ->
210 failure = cleanupFailure(failure) { deliverPointerObservation(snapshot, value) }
211 case None -> {}
212 }
213 }
214 throwFailure(failure)
215 }
216 internal fun dispatch(block: () -> Unit) {
217 checkThread()
218 depth += 1
219 activityDirty = true
220 var failure: Throwable? = None
221 try {
222 block()
223 } catch (error: Throwable) {
224 failure = Some(error)
225 }
226 depth -= 1
227 if (depth == 0)
228 failure = cleanupFailure(failure) { drain() }
229 throwFailure(failure)
230 }
231 private fun drain() {
232 if (depth != 0 || draining)
233 return
234 draining = true
235 var failure: Throwable? = None
236 try {
237 while (pending || activityDirty) {
238 if (closed) {
239 finishClose();
240 break
241 }
242 if (pending) {
243 pending = false
244 val boundaryChange = pendingBoundaryChange
245 pendingBoundaryChange = false
246 reconcilePress(boundaryChange)
247 if (closed)
248 continue
249 reconcileScroll()
250 if (closed)
251 continue
252 reconcileGestures()
253 if (closed)
254 continue
255 reconcileContacts()
256 if (closed)
257 continue
258 reconcileFocus()
259 if (closed)
260 continue
261 refreshHover(inputObservation())
262 }
263 if (!pending) {
264 refreshTextCommands()
265 activityDirty = false
266 notifyActivity()
267 }
268 }
269 } catch (error: Throwable) {
270 failure = Some(error)
271 }
272 draining = false
273 for (old in retired)
274 failure = cleanupFailure(failure) { old.close() }
275 retired.clear()
276 for (scope in retiredScopes)
277 scope.retireEventHandlers()
278 retiredScopes.clear()
279 throwFailure(failure)
280 }
281 private fun finishClose() {
282 val time = inputObservation()
283 var failure = cleanupFailure(None) { cancelWindowInput(InputCancelReason.Closed, time) }
284 failure = cleanupFailure(failure) { replaceHover([], time) }
285 val previous = activeFocus
286 logicalFocus = None
287 activeFocus = None
288 activeFocusVisible = false
289 failure = cleanupFailure(failure) { changeTextCommands(None) }
290 when (previous) {
291 case Some(val area) -> failure =
292 cleanupFailure(failure) {
293 notify(area.scope, InputEvent.FocusChanged(false), terminal = true)
294 };
295 case None -> {}
296 }
297 val session = ime
298 ime = ImeSession.Off
299 imeCaret = None
300 imeConnection = None
301 textContinuation = None
302 caretFrameValid = false
303 when (session) {
304 case Off -> {};
305 else -> failure = cleanupFailure(failure) { imeAllowed(false) }
306 }
307 failure =
308 cleanupFailure(failure) {
309 deliverPointerObservation(
310 pointerObservers.toArray(),
311 PointerObservation.Closed,
312 terminal = true
313 )
314 }
315 for (observer in pointerObservers)
316 observer.closed = true
317 pointerObservers.clear()
318 failure = cleanupFailure(failure) { scene.close() }
319 scene = AreaScene([])
320 for (scope in owned)
321 scope.retireEventHandlers()
322 owned.clear()
323 throwFailure(failure)
324 }
325 internal fun checkThread() {
326 if (thread != currentThreadId())
327 throw IllegalStateException(Some("input requires its owner thread"))
328 }
329 internal fun checkOpen() {
330 checkThread()
331 if (closed)
332 throw IllegalStateException(Some("input router is closed"))
333 }
334 public override fun close() {
335 checkThread()
336 if (closed)
337 return
338 dispatch {
339 closed = true
340 for (scope in owned) {
341 scope.closed = true
342 scope.retireDefaultActions()
343 }
344 for (observer in activityObservers)
345 observer.closed = true
346 activityObservers.clear()
347 for (boundary in boundaries)
348 boundary.closed = true
349 boundaries.clear()
350 pending = true
351 }
352 }
355internal fun inputObservation(): InputTime = InputTime.Observed(MonotonicTimeSource.now())