scoop:scoop.ui:0.1.0
src/lifecycle/scope.scoop
Selected production source · src/lifecycle/scope.scoop
1
package scoop.ui3
import scoop.graphics.*4
import scoop.graphics.text.FontCollection5
import scoop.surface.*6
import scoop.window.*7
import scoop.window.accessibility.*9
/** Owns the resources of one mount; applications do not close individual components. */10
public class ComponentScope internal constructor(private val node: MountedNode) {11
internal val root: UiRoot get() = node.root12
private var active = true13
internal var displayReads: DependencyCollector? = None14
private val resources = ScopeResources()15
internal val managed = resources.managed16
private val cleanup = resources.cleanup17
internal val events =18
ScopedNativeEvents(root.host, resources, { checkMounted() }, { action -> dispatch(action) })19
private var route: InputScope? = None20
private var childRoute: InputScope? = None21
private var layoutRoute: InputScope? = None22
private var animationGroup: AnimationGroup? = None24
internal fun createDragSource(25
area: InputArea,26
options: DragSourceOptions,27
prepare: (DragSourceStart) -> DragSourceData?,28
begin: (DragSourceData, (DragResult) -> Unit) -> DragSession29
): DragSource {30
checkMounted()31
checkDropMutation()32
requireBehaviorArea(area)33
val value = DragSource(root, this, area, options, prepare, begin)34
managed.add(value)35
return value36
}38
internal fun createDropArea(39
area: InputArea,40
handlers: DropAreaHandlers,41
enabled: Boolean,42
createTarget: (DropHandlers) -> DropTarget43
): DropArea {44
checkMounted()45
checkDropMutation()46
requireBehaviorArea(area)47
val controller =48
when (val current = root.drops) {49
case Some(val value) -> value50
case None -> {51
val value = RootDrops(root, createTarget)52
root.drops = Some(value)53
value54
}55
}56
val value = controller.create(this, area, handlers, enabled)57
managed.add(value)58
return value59
}61
internal fun createSemantics(62
role: SemanticRole,63
parent: SemanticsHandle?,64
createProvider: () -> AccessibilityProvider65
): SemanticsHandle {66
checkMounted()67
checkSemanticsMutation()68
checkSemanticParent(node, parent)69
val controller =70
when (val current = root.semantics) {71
case Some(val value) -> value72
case None -> {73
val provider = createProvider()74
try {75
val value = RootSemantics(root, provider)76
root.semantics = Some(value)77
value78
} catch (error: Throwable) {79
throw cleanupUi(Some(error)) { provider.close() }!!80
}81
}82
}83
val handle = controller.create(node, role, parent)84
managed.add(handle)85
return handle86
}87
internal fun semanticAncestor(): SemanticsHandle? = inheritedSemantics(node)89
internal fun forgetSemantics(handle: SemanticsHandle) {90
resources.forget(handle)91
}92
/** Selects the semantic parent for child mounts without changing this mount's siblings. */93
public fun routeSemanticsChildren(parent: SemanticsHandle?) {94
checkMounted()95
checkSemanticsMutation()96
when (parent) {97
case Some(val handle) -> {98
handle.checkOpen()99
requireUi(handle.owner === node, "semantic child route belongs to another mount")100
}101
case None -> {}102
}103
if (sameSemantics(node.semanticRoute, parent))104
return105
node.semanticRoute = parent106
root.semantics?.structureChanged()107
}109
/** The root owns its fallback collection; explicit application collections remain borrowed. */110
public val defaultFonts: FontCollection get() {111
checkMounted()112
displayReads?.read(root.fonts.signal)113
when (currentEvaluation()) {114
case Some(val evaluation) -> {115
evaluation.collector?.read(root.fonts.signal)116
evaluation.frameReads?.readDefaults(root.fonts)117
}118
case None -> {}119
}120
return root.fonts.value121
}123
/** Effective root preferences, tracked by render, update and cached frame readers. */124
public val interactionPreferences: InteractionPreferences get() {125
checkMounted()126
displayReads?.read(root.preferences.signal)127
when (currentEvaluation()) {128
case Some(val evaluation) -> {129
evaluation.collector?.read(root.preferences.signal)130
evaluation.frameReads?.readPreferences(root.preferences)131
}132
case None -> {}133
}134
return root.preferences.value135
}137
/** Observes later effective changes and retires the registration with this mount. */138
public fun observeInteractionPreferences(action: (InteractionPreferences) -> Unit): Closeable {139
checkMounted()140
val observer =141
root.preferences.observe {142
value -> if (isMounted)143
action(value)144
}145
managed.add(observer)146
return observer147
}149
/** The borrowed native owner; the mount does not acquire or transfer its lifetime. */150
public val layoutDirection: LayoutDirection get() {151
checkMounted();152
return node.layoutDirection153
}155
public val nativeWindow: Window get() {156
checkMounted()157
return root.window158
}160
public val application: ActiveApplication get() {161
checkMounted();162
return root.host.activeApplication163
}164
public val uiHost: UiHost get() {165
checkMounted();166
return root.host167
}168
public fun dispatch(action: () -> Unit): Boolean {169
if (!isMounted)170
return false171
return root.host.dispatchRoot(root) {172
if (isMounted)173
action()174
} &&175
isMounted176
}177
public fun observeWindow(window: Window, action: (WindowEvent) -> Unit): Closeable =178
events.window(window, action)179
public val input: InputScope get() {180
checkMounted()181
when (route) {182
case Some(val value) -> return value183
case None -> {}184
}185
val value =186
when (node.parent) {187
case Some(val parent) -> root.surface.createScope(Some(parent.scope.forChildren()))188
case None -> root.surface.input189
}190
route = Some(value)191
managed.add(value)192
return value193
}194
internal fun forChildren(): InputScope = childRoute ?: input195
internal val hasInputActivity: Boolean get() =196
when (route) {197
case Some(val value) -> !value.activity.isEmpty198
case None -> false199
}200
/** Routes logical descendants through an area owned by this mount. */201
public fun routeChildren(area: InputArea) {202
checkMounted()203
requireBehaviorArea(area)204
for (child in node.children)205
child.scope.reparentInput(area.scope)206
childRoute = Some(area.scope)207
}208
/** Keep the component's own enabled setting independent of layout visibility. */209
internal fun setLayoutInputHidden(hidden: Boolean) {210
val gate = when (layoutRoute) {211
case Some(val existing) -> existing213
case None -> {214
if (!hidden) return215
val own = input216
val created = root.surface.createScope(own.parent)217
own.parent = Some(created)218
managed.add(created)219
layoutRoute = Some(created)220
created221
}222
}223
gate.enabled = !hidden224
}225
private fun reparentInput(parent: InputScope) {226
val top = layoutRoute ?: (route ?: return)227
if (!top.isClosed) top.parent = Some(parent)228
}230
public val isMounted: Boolean get() {231
root.checkThread()232
return active && root.isOpen && root.surface.state == SurfaceWindowState.Open233
}234
/** Continues ordinary Tab navigation through parent groups from the current focus within this owner. */235
public fun moveFocus(reverse: Boolean = false): Boolean {236
checkMounted()237
checkFocusMutation()238
return root.focus.moveFrom(node, reverse)239
}240
internal fun checkMounted() {241
if (!isMounted)242
throw IllegalStateException(Some("component is no longer mounted"))243
}244
public fun <R: Closeable> resource(create: () -> R): R {245
checkMounted()246
val value = create()247
cleanup.add { value.close() }248
return value249
}250
public fun onDispose(action: () -> Unit) {251
checkMounted()252
cleanup.add(action)253
}254
/** Uses the native deadline while keeping callbacks inside this root's failure boundary. */255
public fun createDeadline(action: () -> Unit): WindowDeadline {256
checkMounted()257
val value =258
root.window.createDeadline {259
if (isMounted)260
root.surface.dispatch(action)261
}262
managed.add(value)263
return value264
}265
/** Observes the native window while preserving this root's callback ownership. */266
public fun observeWindowActivity(action: (WindowActivity) -> Unit): Closeable {267
checkMounted()268
val value =269
root.window.observeActivity {270
activity -> if (isMounted)271
root.surface.dispatch { action(activity) }272
}273
managed.add(value)274
return value275
}276
/** Local frame-request eligibility; ancestor and submitted placement gates still apply. */277
public var isFrameEnabled: Boolean278
get() {279
checkMounted()280
return node.localFrameEnabled281
}282
set(value) {283
checkMounted()284
checkOverlayMutation()285
node.setFrameEnabled(value)286
}287
public fun requestFrame() {288
checkMounted()289
node.request(UiInvalidation.Scene)290
}291
public fun requestLayout() {292
checkMounted()293
node.request(UiInvalidation.Layout)294
}295
public fun createArea(296
focusable: Boolean = false,297
textInput: Boolean = false,298
parent: InputArea? = None,299
handler: (RoutedEventContext, InputEvent) -> Unit = { _, _ -> Unit }300
): InputArea {301
checkMounted()302
val route =303
when (parent) {304
case Some(val value) -> {305
requireBehaviorArea(value);306
value.scope307
}308
case None -> input309
}310
val area = root.surface.createArea(focusable, textInput, Some(route), handler)311
managed.add(area)312
return area313
}314
public fun focusTarget(area: InputArea, options: FocusOptions = FocusOptions()): FocusTarget {315
checkMounted()316
checkFocusMutation()317
requireUi(!area.isClosed && area.focusable, "focus target requires an open focusable area")318
requireBehaviorArea(area)319
for (target in node.focusTargets)320
requireUi(target.area !== area, "area already has a focus target")321
val value = FocusTarget(node, area, options)322
node.focusTargets.add(value)323
managed.add(value)324
return value325
}326
public fun focusScope(options: FocusScopeOptions = FocusScopeOptions()): FocusScope {327
checkMounted()328
checkFocusMutation()329
when (node.focusScope) {330
case Some(_) -> throw IllegalStateException(Some("mount already has a focus scope"))331
case None -> {}332
}333
val value = FocusScope(node, options)334
node.focusScope = Some(value)335
managed.add(value)336
return value337
}338
public fun keyNavigation(options: NavigationOptions): KeyNavigation {339
checkMounted()340
checkFocusMutation()341
when (node.navigation) {342
case Some(_) -> throw IllegalStateException(Some("mount already has key navigation"))343
case None -> {}344
}345
val value = KeyNavigation(node, options)346
node.navigation = Some(value)347
managed.add(value)348
return value349
}350
public fun layoutAnchor(handle: LayoutAnchor): Closeable {351
checkMounted()352
checkOverlayMutation()353
val value = handle.bind(node)354
managed.add(value)355
return value356
}357
public fun scrollViewport(state: ScrollState): ScrollViewport {358
checkMounted()359
state.checkBinding()360
val value =361
ScrollViewport(362
node,363
state,364
animations().value(Point(0.0, 0.0)),365
animations().value(Point(0.0, 0.0))366
)367
scrollViewports.add(value)368
managed.add(value)369
return value370
}371
public fun scrollPan(372
area: InputArea,373
viewport: ScrollViewport,374
axes: ScrollAxes = ScrollAxes.Both,375
chain: ScrollChain = ScrollChain.Chain,376
options: TouchScrollOptions = TouchScrollOptions()377
): ScrollPan {378
checkMounted()379
requireBehaviorArea(area)380
requireUi(viewport.belongsTo(node), "scroll pan viewport must belong to this mount")381
return resource { ScrollPan(area, viewport, axes, chain, options) }382
}383
public fun lazyFocus(384
viewport: ScrollViewport,385
options: LazyFocusOptions = LazyFocusOptions()386
): LazyFocus {387
checkMounted()388
checkFocusMutation()389
requireUi(390
viewport.contains(node),391
"item focus viewport must belong to this mount or an ancestor"392
)393
when (node.lazyFocus) {394
case Some(_) -> throw IllegalStateException(Some("mount already has item focus"))395
case None -> {}396
}397
val items =398
node.lazyItems ?:399
throw IllegalArgumentException(Some("item focus requires a lazy element"))400
val value = LazyFocus(node, viewport, items, options)401
node.lazyFocus = Some(value)402
managed.add(value)403
return value404
}405
/** Binds this row's actual lazy column container to its ancestor table collection. */406
public fun bindGridColumns(table: SemanticsHandle, row: ViewKey) {407
checkMounted()408
checkSemanticsMutation()409
managed.add(SemanticGridColumns(table, row, node))410
}411
public fun animation(initial: Double): Animatable<Double> =412
animation(initial, AnimationConverters.DoubleValue)413
public fun animation(initial: Point): Animatable<Point> =414
animation(initial, AnimationConverters.PointValue)415
public fun animation(initial: Size): Animatable<Size> =416
animation(initial, AnimationConverters.SizeValue)417
public fun animation(initial: Color): Animatable<Color> =418
animation(initial, AnimationConverters.ColorValue)419
public fun <T> animation(initial: T, converter: AnimationConverter<T>): Animatable<T> {420
checkMounted()421
return animations().value(initial, converter)422
}423
private fun animations(): AnimationGroup {424
when (animationGroup) {425
case Some(val value) -> return value426
case None -> {}427
}428
val value = root.surface.animations.group(node.frameEnabled)429
animationGroup = Some(value)430
managed.add(value)431
return value432
}433
private val scrollViewports = ArrayList<ScrollViewport>()434
internal fun updateFrameParticipation() {435
if (!node.frameEnabled)436
for (viewport in scrollViewports)437
if (!viewport.isClosed)438
viewport.cancelAnimation()439
when (animationGroup) {440
case Some(val value) -> if (!value.isClosed)441
value.isFrameEnabled = node.frameEnabled442
case None -> {}443
}444
}445
internal fun deactivate() {446
active = false447
when (route) {448
case Some(val value) -> if (!value.isClosed)449
value.enabled = false450
case None -> {}451
}452
for (handle in node.semanticHandles.toArray())453
handle.close()454
}455
internal fun retireInteraction(): Throwable? {456
return resources.retireManaged()457
}458
internal fun release(): Throwable? {459
return resources.release()460
}461
}