Scoop API

scoop:scoop.ui:0.1.0

src/layout/scene.scoop

Selected production source · src/layout/scene.scoop

1package scoop.ui
3import scoop.graphics.*
4import scoop.graphics.native.captureGeometry
5import scoop.surface.FrameContext
6import scoop.surface.FrameCompletion
7import scoop.surface.InputArea
8import scoop.platform.time.MonotonicInstant
9import scoop.ui.text.NativeTextSource
11internal class ScenePass {
12 var presentedChildren = false
13 var presentedItems: ItemScenes? = None
14 var cacheable = true
15 val paintKeys = ArrayList<PaintKey>()
16 val scrolls = ArrayList<ScrollViewport>()
17 val layers = ArrayList<CachedPaintLayer>()
20/** Geometry, input and child presentation share one frame state, separate from pixel blocks. */
21public 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? = None
31) {
32 private val extent = layout.metrics.size
33 public val layoutDirection: LayoutDirection
34 get() {
35 checkActive();
36 return node.layoutDirection
37 }
38 private var active = true
39 private var borrowed = false
40 public val size: Size
41 get() {
42 checkActive()
43 return extent
44 }
45 public val time: MonotonicInstant
46 get() {
47 checkActive()
48 observeFrameTime()
49 return frame.time
50 }
51 public val overlayLayout: OverlayLayout?
52 get() {
53 checkActive()
54 pass.cacheable = false
55 return overlay
56 }
57 internal val retainsTextDrawing: Boolean
58 get() {
59 checkActive()
60 return epochs.size > 0L || paintCache != PaintCachePolicy.None
61 }
62 /** Text contact targets follow this frame's enclosing viewport clips. */
63 internal fun textHandleBounds(bounds: Rect): Rect? {
64 checkActive()
65 pass.cacheable = false
66 @Unsafe
67 {
68 val geometry = captureGeometry(frame.canvas, bounds)
69 try {
70 val visible = geometry.visibleBounds ?: return None
71 val local = localReveal(geometry, visible) ?: return None
72 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 = false
96 handle.controller.capture(handle, frame.canvas, shape, scrollPath)
97 }
98 internal fun textSemantics(
99 binding: SemanticTextBinding,
100 bounds: Rect,
101 source: NativeTextSource
102 ) {
103 checkActive()
104 checkSemanticOwner(node, binding.handle)
105 pass.cacheable = false
106 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 = false
112 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 = false
127 borrowed = true
128 try {
129 frame
130 .canvas
131 .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 = false
141 }
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) -> Unit
150 ) {
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) -> Unit
160 ) {
161 checkActive()
162 usePaintKey(key)
163 borrowed = true
164 try {
165 val reads = FrameReads(node, frame.time)
166 val layer = node
167 .paintLayers
168 .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 = false
194 }
195 } finally {
196 borrowed = false
197 }
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) -> T
215 ): T {
216 checkActive()
217 checkScrollRect(region)
218 var found = -1L
219 for (index in 0L..<scrollPath.size)
220 if (scrollPath[index].viewport === viewport) found = index
221 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 = found
229 val path = Array<ScrollReveal>(scrollPath.size) { index ->
230 if (index == selected) replacement else scrollPath[index]
231 }
232 pass.cacheable = false
233 return withPath(path, paintCache, block)
234 }
235 internal fun presentScroll(viewport: ScrollViewport) {
236 checkActive()
237 pass.cacheable = false
238 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) -> Unit
248 ) {
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 boundary
253 }
254 withPath<Unit>(path, viewport.paintCache) { child ->
255 val snapshot = layout.snapshot
256 child.clipRect(Rect(0.0, 0.0, snapshot.viewport.width, snapshot.viewport.height))
257 child
258 .translate(
259 origin.x - layout.presentationOffset.x + snapshot.padding.left,
260 origin.y - layout.presentationOffset.y + snapshot.padding.top
261 )
262 block(child)
263 }
264 }
265 private fun <T> withPath(
266 path: Array<ScrollReveal>,
267 policy: PaintCachePolicy,
268 block: (SceneContext) -> T
269 ): T {
270 borrowed = true
271 try {
272 return frame
273 .withState { childFrame ->
274 val commands = when (recorder) {
275 case Some(_) -> Some(SceneRecorder())
276 case None -> None
277 }
278 val child = SceneContext(
279 node,
280 childFrame,
281 layout,
282 overlay,
283 pass,
284 path,
285 policy,
286 epochs,
287 commands
288 )
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 result
297 } catch (error: Throwable) {
298 pass.cacheable = false
299 throw error
300 } finally {
301 child.end()
302 }
303 }
304 } finally {
305 borrowed = false
306 }
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 = false
330 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.SrcOver
341 ) {
342 checkActive()
343 frame.canvas.saveLayer(opacity, filter, blendMode)
344 when (filter) {
345 case Some(_) -> pass.cacheable = false
346 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? = None
358 ) {
359 checkActive()
360 frame.canvas.saveBackdropLayer(opacity, backdrop, bounds)
361 when (backdrop) {
362 case Some(_) -> pass.cacheable = false
363 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 = false
380 frame.place(area, shape)
381 node.root.focus.place(area, scrollPath)
382 }
383 internal fun uncachedFrame(): FrameContext {
384 checkActive()
385 pass.cacheable = false
386 return frame
387 }
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 = false
412 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(_) -> true
418 case None -> false
419 }
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] = true
436 }
437 }
439 case None -> {}
440 }
441 pass.presentedChildren = true
442 val childEpochs = when (epoch) {
443 case Some(val value) ->
444 Array<SceneEpoch>(epochs.size + 1L) { index ->
445 if (index < epochs.size) epochs[index] else value
446 }
447 case None -> epochs
448 }
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 = false
454 throw error
455 }
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 = false
473 }