scoop:scoop.ui:0.1.0
src/layout/scene.scoop
Selected production source · src/layout/scene.scoop
1
package scoop.ui3
import scoop.graphics.*4
import scoop.graphics.native.captureGeometry5
import scoop.surface.FrameContext6
import scoop.surface.FrameCompletion7
import scoop.surface.InputArea8
import scoop.platform.time.MonotonicInstant9
import scoop.ui.text.NativeTextSource11
internal class ScenePass {12
var presentedChildren = false13
var presentedItems: ItemScenes? = None14
var cacheable = true15
val paintKeys = ArrayList<PaintKey>()16
val scrolls = ArrayList<ScrollViewport>()17
val layers = ArrayList<CachedPaintLayer>()18
}20
/** Geometry, input and child presentation share one frame state, separate from pixel blocks. */21
public class SceneContext internal constructor(22
private val node: MountedNode,23
private val frame: FrameContext,24
private val layout: NodeLayout,25
private val overlay: OverlayLayout? = None,26
private val pass: ScenePass = ScenePass(),27
private val scrollPath: Array<ScrollReveal> = [],28
private val paintCache: PaintCachePolicy = PaintCachePolicy.None,29
private val epochs: Array<SceneEpoch> = [],30
private val recorder: SceneRecorder? = None31
) {32
private val extent = layout.metrics.size33
public val layoutDirection: LayoutDirection34
get() {35
checkActive();36
return node.layoutDirection37
}38
private var active = true39
private var borrowed = false40
public val size: Size41
get() {42
checkActive()43
return extent44
}45
public val time: MonotonicInstant46
get() {47
checkActive()48
observeFrameTime()49
return frame.time50
}51
public val overlayLayout: OverlayLayout?52
get() {53
checkActive()54
pass.cacheable = false55
return overlay56
}57
internal val retainsTextDrawing: Boolean58
get() {59
checkActive()60
return epochs.size > 0L || paintCache != PaintCachePolicy.None61
}62
/** Text contact targets follow this frame's enclosing viewport clips. */63
internal fun textHandleBounds(bounds: Rect): Rect? {64
checkActive()65
pass.cacheable = false66
@Unsafe67
{68
val geometry = captureGeometry(frame.canvas, bounds)69
try {70
val visible = geometry.visibleBounds ?: return None71
val local = localReveal(geometry, visible) ?: return None72
return intersectReveal(bounds, local)73
} finally {74
geometry.close()75
}76
}77
}78
/** Captures current transform and clip without creating an input target. */79
public fun anchor(handle: LayoutAnchor, rect: Rect) {80
checkActive()81
handle.capture(node, node.root.overlays.frame, frame.canvas, rect)82
recorder?.add(SceneCommand.Anchor(handle, rect))83
}84
/** Captures semantic geometry in the same transformed and clipped scene. */85
public fun semantics(handle: SemanticsHandle, bounds: Rect) {86
checkActive()87
checkSemanticOwner(node, handle)88
handle.controller.capture(handle, frame.canvas, bounds, scrollPath)89
recorder?.add(SceneCommand.Semantics(handle, bounds))90
}91
/** Captures a precise path; like path input placement, this scene is not cached. */92
public fun semantics(handle: SemanticsHandle, shape: Path) {93
checkActive()94
checkSemanticOwner(node, handle)95
pass.cacheable = false96
handle.controller.capture(handle, frame.canvas, shape, scrollPath)97
}98
internal fun textSemantics(99
binding: SemanticTextBinding,100
bounds: Rect,101
source: NativeTextSource102
) {103
checkActive()104
checkSemanticOwner(node, binding.handle)105
pass.cacheable = false106
binding.handle.controller.captureText(binding, frame.canvas, bounds, source, scrollPath)107
}108
/** Runs after this frame ends, while this node remains mounted and its root remains open. */109
public fun onFrameComplete(action: (FrameCompletion) -> Unit) {110
checkActive()111
pass.cacheable = false112
node.root.addCompletion(node, action)113
}114
internal fun checkOwner(owner: MountedNode) {115
checkActive()116
requireUi(node === owner, "scene registration belongs to a different mount")117
}118
private fun checkActive() {119
node.root.checkThread()120
if (!active) throw IllegalStateException(Some("scene context has ended"))121
if (borrowed) throw IllegalStateException(Some("scene context has an active child scope"))122
}123
/** Runs a pixel-only block with an independent Canvas lifetime and save stack. */124
public fun draw(block: (PaintContext) -> Unit) {125
checkActive()126
pass.cacheable = false127
borrowed = true128
try {129
frame130
.canvas131
.withState { canvas ->132
val context = PaintContext(node.root, canvas, extent, frame.time)133
try {134
block(context)135
} finally {136
context.end()137
}138
}139
} finally {140
borrowed = false141
}142
}143
/** Records a finite, isolated layer; revision covers every input affecting its pixels. */144
public fun drawLayer(145
key: PaintKey,146
bounds: Rect,147
revision: Long,148
samplingOutset: Double = 1.0,149
block: (PaintContext) -> Unit150
) {151
drawRecording(key, bounds, revision, samplingOutset, PaintComposition.Isolated, block)152
}153
internal fun drawRecording(154
key: PaintKey,155
bounds: Rect,156
revision: Long,157
samplingOutset: Double,158
composition: PaintComposition,159
block: (PaintContext) -> Unit160
) {161
checkActive()162
usePaintKey(key)163
borrowed = true164
try {165
val reads = FrameReads(node, frame.time)166
val layer = node167
.paintLayers168
.draw(169
frame.canvas,170
key,171
PaintLayerInput(extent, bounds, revision, samplingOutset, composition),172
paintCache,173
Some(frame.time),174
Some(reads)175
) { canvas ->176
val context = PaintContext(node.root, canvas, extent, frame.time)177
try {178
evaluateUi<Unit>(None, Some(reads)) { block(context) }179
} finally {180
context.end()181
}182
}183
when (layer) {184
case Some(val value) -> {185
when (currentEvaluation()) {186
case Some(val evaluation) -> evaluation.frameReads?.include(value.inputs)187
case None -> {}188
}189
pass.layers.add(value)190
recorder?.add(SceneCommand.Drawing(value))191
}193
case None -> pass.cacheable = false194
}195
} finally {196
borrowed = false197
}198
}199
private fun usePaintKey(key: PaintKey) {200
for (previous in pass.paintKeys)201
requireUi(previous !== key, "paint key was already used in this scene")202
pass.paintKeys.add(key)203
}204
/** Shares the one child presentation pass while isolating scene state. */205
public fun <T> withState(block: (SceneContext) -> T): T {206
checkActive()207
return withPath(scrollPath, paintCache, block)208
}209
/** Narrows an existing viewport's reveal region for this actual content subtree. */210
public fun <T> withScrollReveal(211
viewport: ScrollViewport,212
region: Rect,213
axes: ScrollAxes = ScrollAxes.Both,214
block: (SceneContext) -> T215
): T {216
checkActive()217
checkScrollRect(region)218
var found = -1L219
for (index in 0L..<scrollPath.size)220
if (scrollPath[index].viewport === viewport) found = index221
requireUi(found >= 0L, "reveal viewport is not in the actual scene path")222
val boundary = scrollPath[found]223
requireUi(224
viewport.matches(boundary.state, boundary.layout.binding),225
"reveal viewport is closed or rebound"226
)227
val replacement = boundary.constrain(region, axes)228
val selected = found229
val path = Array<ScrollReveal>(scrollPath.size) { index ->230
if (index == selected) replacement else scrollPath[index]231
}232
pass.cacheable = false233
return withPath(path, paintCache, block)234
}235
internal fun presentScroll(viewport: ScrollViewport) {236
checkActive()237
pass.cacheable = false238
for (previous in pass.scrolls)239
if (previous === viewport)240
throw IllegalStateException(Some("scroll viewport was already presented"))241
pass.scrolls.add(viewport)242
}243
internal fun scrollContent(244
viewport: ScrollViewport,245
layout: ScrollLayout,246
origin: Point,247
block: (SceneContext) -> Unit248
) {249
checkActive()250
val boundary = node.root.focus.captureScroll(viewport, layout, frame.canvas)251
val path = Array<ScrollReveal>(scrollPath.size + 1L) { index ->252
if (index < scrollPath.size) scrollPath[index] else boundary253
}254
withPath<Unit>(path, viewport.paintCache) { child ->255
val snapshot = layout.snapshot256
child.clipRect(Rect(0.0, 0.0, snapshot.viewport.width, snapshot.viewport.height))257
child258
.translate(259
origin.x - layout.presentationOffset.x + snapshot.padding.left,260
origin.y - layout.presentationOffset.y + snapshot.padding.top261
)262
block(child)263
}264
}265
private fun <T> withPath(266
path: Array<ScrollReveal>,267
policy: PaintCachePolicy,268
block: (SceneContext) -> T269
): T {270
borrowed = true271
try {272
return frame273
.withState { childFrame ->274
val commands = when (recorder) {275
case Some(_) -> Some(SceneRecorder())276
case None -> None277
}278
val child = SceneContext(279
node,280
childFrame,281
layout,282
overlay,283
pass,284
path,285
policy,286
epochs,287
commands288
)289
try {290
val result = block(child)291
when (commands) {292
case Some(val value) ->293
recorder?.add(SceneCommand.Scope(value.finish()))294
case None -> {}295
}296
result297
} catch (error: Throwable) {298
pass.cacheable = false299
throw error300
} finally {301
child.end()302
}303
}304
} finally {305
borrowed = false306
}307
}308
public fun concat(transform: Transform) {309
checkActive()310
frame.canvas.concat(transform)311
recorder?.add(SceneCommand.Concat(transform))312
}313
public fun translate(x: Double, y: Double) {314
concat(Transform.translation(x, y))315
}316
public fun scale(x: Double, y: Double) {317
concat(Transform.scale(x, y))318
}319
public fun rotate(radians: Double) {320
concat(Transform.rotation(radians))321
}322
public fun clipRect(rect: Rect) {323
checkActive()324
frame.canvas.clipRect(rect)325
recorder?.add(SceneCommand.Clip(rect))326
}327
public fun clipPath(path: Path) {328
checkActive()329
pass.cacheable = false330
frame.canvas.clipPath(path)331
}332
public fun save() {333
checkActive()334
frame.canvas.save()335
recorder?.add(SceneCommand.Save)336
}337
public fun saveLayer(338
opacity: Double = 1.0,339
filter: ImageFilter? = None,340
blendMode: BlendMode = BlendMode.SrcOver341
) {342
checkActive()343
frame.canvas.saveLayer(opacity, filter, blendMode)344
when (filter) {345
case Some(_) -> pass.cacheable = false346
case None -> recorder?.add(SceneCommand.SaveLayer(opacity, blendMode))347
}348
}349
/**350
* Groups this scene and its children with the current backdrop, including during opacity fades.351
* The optional filter processes the backdrop on entry, leaving subsequent foreground sharp.352
* This reads the current layer only; an outer saveLayer still isolates its contents.353
*/354
public fun saveBackdropLayer(355
opacity: Double = 1.0,356
backdrop: ImageFilter? = None,357
bounds: Rect? = None358
) {359
checkActive()360
frame.canvas.saveBackdropLayer(opacity, backdrop, bounds)361
when (backdrop) {362
case Some(_) -> pass.cacheable = false363
case None -> recorder?.add(SceneCommand.SaveBackdropLayer(opacity, bounds))364
}365
}366
public fun restore() {367
checkActive()368
frame.canvas.restore()369
recorder?.add(SceneCommand.Restore)370
}371
public fun place(area: InputArea, shape: Rect) {372
checkActive()373
frame.place(area, shape)374
node.root.focus.place(area, scrollPath)375
recorder?.add(SceneCommand.Place(area, shape))376
}377
public fun place(area: InputArea, shape: Path) {378
checkActive()379
pass.cacheable = false380
frame.place(area, shape)381
node.root.focus.place(area, scrollPath)382
}383
internal fun uncachedFrame(): FrameContext {384
checkActive()385
pass.cacheable = false386
return frame387
}388
public fun children() {389
presentChildren(None, None)390
}391
/** Presents a complete permutation without changing logical mount or input ownership. */392
public fun children(order: Array<Long>) {393
presentChildren(Some(order), None)394
}395
/** Presents one placed LazyElement item under this scope's transform and clip.396
* Every placed item must be presented once; cannot be mixed with children().397
* Looks up only the selected layout, without building or measuring any item.398
*/399
public fun item(key: ViewKey) {400
checkActive()401
if (pass.presentedChildren)402
throw IllegalStateException(Some("children were already presented"))403
val items = pass.presentedItems ?:404
when (layout.body) {405
case Lazy(_, val selected) -> ItemScenes(selected)406
else ->407
throw IllegalStateException(Some("item presentation requires a LazyElement"))408
}409
val index = items.take(key)410
pass.presentedItems = Some(items)411
pass.cacheable = false412
layout.presentChild(index, frame, overlay, scrollPath, paintCache, epochs)413
}414
internal fun presentChildren(order: Array<Long>?, epoch: SceneEpoch?) {415
checkActive()416
val partial = when (pass.presentedItems) {417
case Some(_) -> true418
case None -> false419
}420
if (pass.presentedChildren || partial)421
throw IllegalStateException(Some("children were already presented"))422
when (order) {423
case Some(val value) -> {424
requireUi(425
value.size == layout.children.size,426
"child order must include every child"427
)428
val visited = MutableArray<Boolean>(layout.children.size) { _ -> false }429
for (index in value) {430
requireUi(431
index >= 0L && index < layout.children.size,432
"child order index is out of bounds"433
)434
requireUi(!visited[index], "child order contains a duplicate index")435
visited[index] = true436
}437
}439
case None -> {}440
}441
pass.presentedChildren = true442
val childEpochs = when (epoch) {443
case Some(val value) ->444
Array<SceneEpoch>(epochs.size + 1L) { index ->445
if (index < epochs.size) epochs[index] else value446
}447
case None -> epochs448
}449
recorder?.add(SceneCommand.Children(order, childEpochs))450
try {451
layout.presentChildren(frame, overlay, scrollPath, paintCache, childEpochs, order)452
} catch (error: Throwable) {453
pass.cacheable = false454
throw error455
}456
}457
internal fun finish() {458
if (!pass.presentedChildren) {459
for (index in 0L..<layout.children.size)460
if (layout.children[index].origin !=461
None &&462
!(pass.presentedItems?.contains(index) ?: false)463
)464
throw IllegalStateException(Some("placed children must be presented"))465
for (index in 0L..<layout.children.size)466
if (layout.children[index].origin == None)467
layout.presentChild(index, frame, overlay, scrollPath, paintCache, epochs)468
}469
node.paintLayers.retain(pass.paintKeys)470
}471
internal fun end() {472
active = false473
}474
}