scoop:scoop.surface:0.1.0
src/shared/input/router.scoop
Selected production source · src/shared/input/router.scoop
1
package scoop.surface3
import scoop.graphics.*4
import scoop.platform.concurrent.currentThreadId5
import scoop.platform.time.MonotonicTimeSource6
import scoop.window.*8
internal enum ImeSession {9
Off, Opening(InputArea), On(InputArea), Closing(InputArea)10
}12
/** Shared routing state; the window adapter supplies only invalidation and IME operations. */13
internal 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 = false22
internal var windowRegions: WindowDecorations? = None23
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 = 029
private var draining = false30
internal var pending = false31
internal var pointer: PointerState? = None32
internal var inside = false33
internal var hover: Array<InputScope> = []34
internal var pressed: Array<InputScope>? = None35
internal var pointerClaim: InputScope? = None36
internal var scrollRoute: InputScrollRoute? = None37
internal val gestureRoutes = ArrayList<InputGestureRoute>()38
internal val contactRoutes = ArrayList<InputContactRoute>()39
internal val buttons = ArrayList<MouseButton>()40
internal var logicalFocus: InputArea? = None41
internal var activeFocus: InputArea? = None42
internal var activeFocusVisible = false43
internal var publishedTextCommands: TextCommandAvailability? = None44
internal var focusRevision = 0uL45
internal val boundaries = ArrayList<InputBoundary>()46
internal var pendingBoundaryChange = false47
internal var boundaryRevision = 0uL48
internal var ime = ImeSession.Off49
internal var imeCaret: ImeCaret? = None50
internal var imeConnection: TextInputConnection? = None51
internal var imeRequest = 0UL52
internal var textContinuation: InputTextContinuation? = None53
internal var caretFrameValid = false54
internal val activityObservers = ArrayList<InputActivityObserver>()55
internal val pointerObservers = ArrayList<WindowPointerObserver>()56
private var activityDirty = false58
init {59
owned.add(rootScope)60
refreshTextCommands()61
}63
fun createArea(64
focusable: Boolean,65
textInput: Boolean,66
parent: InputScope?,67
handler: (RoutedEventContext, InputEvent) -> Unit68
): InputArea {69
checkOpen()70
val result =71
InputArea(this, focusable || textInput, textInput, acceptParent(parent), handler)72
owned.add(result.scope)73
return result74
}75
fun createScope(76
parent: InputScope?,77
handler: (RoutedEventContext, InputEvent) -> Unit78
): InputScope {79
checkOpen()80
val result = InputScope(this, None, Some(acceptParent(parent)), handler)81
owned.add(result)82
return result83
}84
private fun acceptParent(parent: InputScope?): InputScope {85
val result = parent ?: rootScope86
requireInput(result.owner === this, "input parent belongs to another window")87
result.checkOpen()88
return result89
}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
return99
}100
val next = acceptParent(parent)101
var cursor: InputScope? = Some(next)102
while (true) {103
val current = cursor ?: break104
requireInput(current !== scope, "input parent would create a cycle")105
cursor = current.ancestor106
}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 error126
}127
scene = next128
caretFrameValid = true129
pending = true130
activityDirty = true131
drain()132
}133
fun changed() {134
checkThread()135
if (closed)136
return137
windowRegions?.refreshEligibility()138
pending = true139
dispatch { invalidate() }140
}141
fun geometryChanged() {142
imeCaret = None;143
caretFrameValid = false144
changed()145
}146
fun detached(scope: InputScope) {147
when (textContinuation) {148
case Some(val value) -> if (149
value.source.scope === scope || value.target.scope === scope150
)151
textContinuation = None152
case None -> {}153
}154
retiredScopes.add(scope)155
var index = 0L156
while (index < owned.size) {157
if (owned[index] === scope) {158
owned.removeAt(index);159
break160
}161
index += 1L162
}163
changed()164
}165
fun dispatchWindowInput(166
event: WindowEvent,167
pointer: PointerEvent? = None,168
platformInput: () -> Unit = {}169
) {170
checkThread()171
if (closed) return172
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 -> None179
}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 = value188
pending = true189
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 += 1219
activityDirty = true220
var failure: Throwable? = None221
try {222
block()223
} catch (error: Throwable) {224
failure = Some(error)225
}226
depth -= 1227
if (depth == 0)228
failure = cleanupFailure(failure) { drain() }229
throwFailure(failure)230
}231
private fun drain() {232
if (depth != 0 || draining)233
return234
draining = true235
var failure: Throwable? = None236
try {237
while (pending || activityDirty) {238
if (closed) {239
finishClose();240
break241
}242
if (pending) {243
pending = false244
val boundaryChange = pendingBoundaryChange245
pendingBoundaryChange = false246
reconcilePress(boundaryChange)247
if (closed)248
continue249
reconcileScroll()250
if (closed)251
continue252
reconcileGestures()253
if (closed)254
continue255
reconcileContacts()256
if (closed)257
continue258
reconcileFocus()259
if (closed)260
continue261
refreshHover(inputObservation())262
}263
if (!pending) {264
refreshTextCommands()265
activityDirty = false266
notifyActivity()267
}268
}269
} catch (error: Throwable) {270
failure = Some(error)271
}272
draining = false273
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 = activeFocus286
logicalFocus = None287
activeFocus = None288
activeFocusVisible = false289
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 = ime298
ime = ImeSession.Off299
imeCaret = None300
imeConnection = None301
textContinuation = None302
caretFrameValid = false303
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 = true313
)314
}315
for (observer in pointerObservers)316
observer.closed = true317
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
return338
dispatch {339
closed = true340
for (scope in owned) {341
scope.closed = true342
scope.retireDefaultActions()343
}344
for (observer in activityObservers)345
observer.closed = true346
activityObservers.clear()347
for (boundary in boundaries)348
boundary.closed = true349
boundaries.clear()350
pending = true351
}352
}353
}355
internal fun inputObservation(): InputTime = InputTime.Observed(MonotonicTimeSource.now())