Scoop API

scoop:scoop.surface:0.1.0

src/shared/host/window.scoop

Selected production source · src/shared/host/window.scoop

1package scoop.surface
3import scoop.graphics.Size
4import scoop.graphics.Point
5import scoop.platform.time.MonotonicTimeSource
6import scoop.platform.time.MonotonicInstant
7import scoop.window.*
9public enum SurfaceWindowState {
10 Open, Closing, Closed
13/** Shared owner of painting, frame demand and the renderer's explicit window lease. */
14public class SurfaceWindow internal constructor(
15 private val host: SurfaceHost,
16 public val nativeWindow: Window,
17 private val content: SurfaceContent,
18 private val renderer: WindowRenderer
19) : Closeable {
20 private var phase = SurfaceWindowState.Open
21 private var failure: Throwable? = None
22 private var depth = 0
23 private var configured: WindowMetrics? = None
24 private val scheduler = FrameScheduler()
25 private var animationDeadline: WindowDeadline? = None
26 private var scheduledAnimationTime: MonotonicInstant? = None
27 public val animations: AnimationTimeline = windowAnimations(nativeWindow)
28 internal val inputs = windowInputs(nativeWindow)
29 init {
30 host.bindShortcuts(inputs.rootScope)
31 animations.scheduleChanged = { refresh() }
32 }
33 public val input: InputScope
34 get() {
35 host.checkThread()
36 return inputs.rootScope
37 }
38 public val focusedArea: InputArea?
39 get() {
40 host.checkThread();
41 return inputs.logicalFocus
42 }
43 public val focusRevision: ULong
44 get() {
45 host.checkThread()
46 return inputs.focusRevision
47 }
48 /** Records a deferred or rejected focus intent without changing the current target. */
49 public fun reserveFocusRequest(): ULong = inputs.reserveFocusRequest()
50 public val focusBoundary: InputBoundary?
51 get() {
52 host.checkThread()
53 return inputs.currentFocusBoundary
54 }
55 public val inputBoundary: InputBoundary?
56 get() {
57 host.checkThread()
58 return inputs.currentBoundary
59 }
60 public val state: SurfaceWindowState
61 get() {
62 host.checkThread();
63 return phase
64 }
66 public fun createArea(
67 focusable: Boolean = false,
68 textInput: Boolean = false,
69 parent: InputScope? = None,
70 handler: (RoutedEventContext, InputEvent) -> Unit = { _, _ -> Unit }
71 ): InputArea = inputs.createArea(focusable, textInput, parent, handler)
72 public fun createScope(
73 parent: InputScope? = None,
74 handler: (RoutedEventContext, InputEvent) -> Unit = { _, _ -> Unit }
75 ): InputScope = inputs.createScope(parent, handler)
76 /** Queries the accepted foreground route without changing input or focus state. */
77 public fun hitInput(windowPoint: Point): Array<InputHit> = inputs.hitInput(windowPoint)
78 public fun clearFocus() {
79 inputs.clearFocus()
80 }
82 public fun requestFrame() {
83 host.checkThread()
84 if (phase != SurfaceWindowState.Open)
85 throw IllegalStateException(Some("Surface window is closing"))
86 scheduler.request()
87 refresh()
88 }
89 internal fun refresh() {
90 host.checkThread()
91 if (phase != SurfaceWindowState.Open) return
92 callback { refreshWindow() }
93 }
94 internal fun initialize() {
95 refreshWindow()
96 }
97 private fun refreshWindow() {
98 if (nativeWindow.state !=
99 WindowState.Open &&
100 nativeWindow.state !=
101 WindowState.PendingConfigure
102 ) {
103 close();
104 return
105 }
106 var drawable = false
107 when (nativeWindow.metrics) {
108 case Some(val metrics) -> {
109 if (configured != Some(metrics)) {
110 renderer.configure(metrics)
111 configured = Some(metrics)
112 scheduler.request()
113 inputs.windowRegions?.geometryChanged()
114 inputs.geometryChanged()
115 }
116 if (phase != SurfaceWindowState.Open) return
117 drawable = metrics.physicalSize.isDrawable &&
118 nativeWindow.isVisible &&
119 !nativeWindow.isOccluded
120 renderer.setFrameDemand((scheduler.dirty || animations.hasFrameWork) && drawable)
121 }
123 case None -> {
124 configured = None
125 renderer.setFrameDemand(false)
126 }
127 }
128 refreshAnimationDeadline(drawable)
129 }
130 private fun refreshAnimationDeadline(drawable: Boolean) {
131 val next = animations.nextDeadline(!drawable)
132 if (next == scheduledAnimationTime) return
133 scheduledAnimationTime = next
134 when (next) {
135 case None -> animationDeadline?.cancel()
137 case Some(val time) -> {
138 val deadline = animationDeadline ?:
139 nativeWindow
140 .createDeadline {
141 scheduledAnimationTime = None
142 callback {
143 animations.advanceTo(MonotonicTimeSource.now())
144 refresh()
145 }
146 }
147 animationDeadline = Some(deadline)
148 deadline.schedule(time)
149 }
150 }
151 }
152 internal fun event(event: WindowEvent) {
153 host.checkThread()
154 if (phase != SurfaceWindowState.Open) return
155 callback {
156 when (event) {
157 case Closing -> close()
158 case Destroyed -> close()
160 case RedrawRequested -> {
161 scheduler.request();
162 render()
163 }
165 case GeometryChanged(_) -> refresh()
167 case Occluded(_) -> {
168 scheduler.request();
169 refresh()
170 }
172 case ThemeChanged(_) -> requestFrame()
173 else -> otherWindowEvent(event)
174 }
175 }
176 }
177 private fun render() {
178 refresh()
179 if (phase != SurfaceWindowState.Open) return
180 val metrics = configured ?: return
181 if (!metrics.physicalSize.isDrawable || !nativeWindow.isVisible || nativeWindow.isOccluded)
182 return
183 when (renderer.acquire()) {
184 case Deferred -> {
185 scheduler.request();
186 refresh()
187 }
189 case Ready(val frame) -> {
190 val time = MonotonicTimeSource.now()
191 val size = Size(metrics.logicalSize.width, metrics.logicalSize.height)
192 val accepted = frame
193 .use { current ->
194 inputs
195 .beginFrame()
196 .use { placements ->
197 placements.decorations = inputs
198 .windowRegions
199 ?.beginFrame(metrics.scaleFactor)
200 scheduler.begin()
201 animations
202 .withFrame<Unit>(time) {
203 if (phase == SurfaceWindowState.Open) {
204 current
205 .draw { canvas ->
206 inputs
207 .dispatch {
208 content
209 .paint(
210 FrameContext(
211 this,
212 canvas,
213 size,
214 time,
215 placements,
216 metrics.scaleFactor,
217 metrics.safeAreaInsets
218 )
219 )
220 }
221 }
222 }
223 }
224 // A painter can resize or close its native window synchronously.
225 refresh()
226 val submitted = phase ==
227 SurfaceWindowState.Open &&
228 nativeWindow.state ==
229 WindowState.Open &&
230 nativeWindow.isVisible &&
231 !nativeWindow.isOccluded &&
232 current.submit()
233 if (submitted) {
234 placements.decorations?.publish()
235 inputs.publish(placements)
236 }
237 submitted
238 }
239 }
240 if (!accepted) scheduler.request()
241 if (phase == SurfaceWindowState.Open)
242 content
243 .onFrameComplete(
244 FrameCompletion(
245 time,
246 size,
247 if (accepted)
248 FrameSubmission.Accepted
249 else
250 FrameSubmission.Discarded
251 )
252 )
253 refresh()
254 }
255 }
256 }
257 private fun callback(block: () -> Unit) {
258 depth += 1
259 var error: Throwable? = None
260 try {
261 block()
262 } catch (caught: Throwable) {
263 error = Some(caught)
264 }
265 depth -= 1
266 when (error) {
267 case Some(val value) -> fail(value)
268 case None -> finishClosing()
269 }
270 }
271 /** Runs synchronous logical work under this window's callback and retirement boundary. */
272 public fun dispatch(block: () -> Unit): Boolean {
273 host.checkThread()
274 if (phase != SurfaceWindowState.Open) return false
275 callback(block)
276 return phase == SurfaceWindowState.Open
277 }
278 private fun fail(error: Throwable) {
279 failure = cleanupFailure(failure) { throw error }
280 stop()
281 finishClosing()
282 }
283 public override fun close() {
284 host.checkThread()
285 stop()
286 finishClosing()
287 }
288 private fun stop() {
289 if (phase != SurfaceWindowState.Open) return
290 phase = SurfaceWindowState.Closing
291 host.requestRetirement()
292 failure = cleanupFailure(failure) { renderer.setFrameDemand(false) }
293 failure = cleanupFailure(failure) { animationDeadline?.close() }
294 failure = cleanupFailure(failure) { inputs.windowRegions?.close() }
295 inputs.windowRegions = None
296 failure = cleanupFailure(failure) { inputs.close() }
297 failure = cleanupFailure(failure) { animations.close() }
298 }
299 internal fun finishClosing() {
300 if (phase == SurfaceWindowState.Closing && depth == 0 && !host.callbackActive) {
301 val error = retire()
302 when (error) {
303 case Some(val value) -> host.reportWindowError(nativeWindow.id, value)
304 case None -> {}
305 }
306 }
307 }
308 internal fun rollbackAttach() {
309 stop()
310 // A failed attach has not exposed this window or entered its content callbacks.
311 throwFailure(retire())
312 }
313 private fun retire(): Throwable? {
314 if (phase == SurfaceWindowState.Closed) return None
315 phase = SurfaceWindowState.Closed
316 failure = cleanupFailure(failure) { content.close() }
317 failure = cleanupFailure(failure) { renderer.close() }
318 val error = failure
319 failure = None
320 // Releasing a failed shared renderer remains a host-level error.
321 try {
322 host.detached(this)
323 } catch (shared: Throwable) {
324 throw cleanupFailure(error) { throw shared }!!
325 }
326 return error
327 }
330private fun windowAnimations(window: Window): AnimationTimeline = AnimationTimeline {
331 if (window.state == WindowState.Open) window.requestRedraw()
334private fun windowInputs(window: Window): InputRouter = InputRouter(
335 window.isFocused,
336 { if (window.state == WindowState.Open) window.requestRedraw() },
337 { allowed ->
338 if (window.state == WindowState.Open) {
339 window.setImeAllowed(allowed)
340 }
341 },
342 { caret -> if (window.state == WindowState.Open) publishWindowCaret(window, caret) else false },
343 { commands -> if (window.state == WindowState.Open) window.textCommandAvailability = commands }