Scoop API

scoop:scoop.ui:0.1.0

src/host/host.scoop

Selected production source · src/host/host.scoop

1package scoop.ui
3import scoop.platform.concurrent.currentThreadId
4import scoop.graphics.text.FontCollection
5import scoop.surface.SurfaceHost
6import scoop.surface.SurfaceWindow
7import scoop.surface.HostShortcutScope
8import scoop.surface.ShortcutBinding
9import scoop.window.*
11internal interface UiUpdateRoot {
12 val isOpen: Boolean
13 var pendingEnqueued: Boolean
14 fun dispatchUpdate()
17/** Runs logical updates and Surface frames on the existing application owner. */
18public class UiHost public constructor(
19 private val onRootError: (WindowId, Throwable) -> Unit = { _, error -> throw error },
20 private val onApplicationError: (Throwable) -> Unit = { error -> throw error },
21 private val handler: (UiHost, ActiveApplication, ApplicationEvent) -> Unit = { _, _, _ -> }
22): ApplicationHandler, Closeable {
23 private val thread = currentThreadId()
24 private val roots = ArrayList<UiRoot>()
25 private val pending = ArrayList<UiUpdateRoot>()
26 private var applicationRoot: UiApplicationRoot? = None
27 private var active: ActiveApplication? = None
28 internal val windowEvents = UiEventTable<WindowId, WindowEvent> { checkThread() }
29 internal val frameEvents = UiEventTable<WindowId, Unit> { checkThread() }
30 internal val integration = platformUiIntegration(this)
31 private var proxy: ApplicationProxy? = None
32 private var queued = false
33 private var processing = false
34 private var depth = 0
35 private var nativeDepth = 0
36 internal val isDispatching: Boolean get() = depth > 0 || processing
37 private var pendingRetirement = false
38 private var closing = false
39 private var hostShortcuts: HostShortcutScope? = None
40 private val surfaces =
41 SurfaceHost(
42 onWindowError =
43 {
44 id,
45 error -> try {
46 onRootError(id, error)
47 } catch (reported: Throwable) {
48 // Surface owns the original failure and combines a failing report with it.
49 throw cleanupUi(Some(reported)) { close() }!!
50 }
51 },
52 handler =
53 {
54 _, application, event ->
55 when (event) {
56 case Window(val id, val value) -> {
57 windowEvents.deliver(id, value)
58 if (uiFrameChanged(value)) frameEvents.deliver(id, Unit)
59 }
60 else -> {}
61 }
62 integration?.event(event)
63 handler(this, application, event)
64 }
65 )
67 public val isClosed: Boolean get() {
68 checkThread()
69 val applicationClosed =
70 when (applicationRoot) {
71 case None -> true;
72 case Some(_) -> false
73 }
74 return closing && roots.size == 0L && applicationClosed && surfaces.isClosed
75 }
76 internal fun checkThread() {
77 checkUiThread(thread)
78 }
79 internal val activeApplication: ActiveApplication get() {
80 checkThread()
81 return active ?: throw IllegalStateException(Some("UI host is not running"))
82 }
84 public fun <C: ApplicationComponent> attachApplication(
85 application: ActiveApplication,
86 create: (ApplicationScope) -> C
87 ): UiApplication? {
88 checkThread()
89 if (closing || !(activeApplication === application))
90 throw IllegalStateException(Some("application does not drive this open UI host"))
91 when (applicationRoot) {
92 case Some(_) -> throw IllegalStateException(Some("UI application is already attached"))
93 case None -> {}
94 }
95 return callback {
96 val root = UiApplicationRoot(this, application)
97 applicationRoot = Some(root)
98 if (root.dispatch { root.mount(create) })
99 Some(UiApplication(root))
100 else
101 None
102 }
103 }
105 internal fun reportApplicationError(error: Throwable) {
106 if (closing)
107 throw error
108 try {
109 onApplicationError(error)
110 } catch (reported: Throwable) {
111 val failure: Throwable? =
112 if (reported === error)
113 Some(error)
114 else
115 Some(ResourceUseException(error, reported))
116 throw cleanupUi(failure) { close() }!!
117 }
118 }
120 internal fun detachedApplication(root: UiApplicationRoot) {
121 when (applicationRoot) {
122 case Some(val current) -> if (current === root)
123 applicationRoot = None
124 case None -> {}
125 }
126 removePending(root)
127 }
129 public fun shortcutScope(bindings: Array<ShortcutBinding> = []): HostShortcutScope {
130 checkThread()
131 if (closing)
132 throw IllegalStateException(Some("UI host is closed"))
133 val scope = HostShortcutScope(surfaces, bindings)
134 hostShortcuts = Some(scope)
135 return scope
136 }
138 public fun <C: Component> attach(
139 window: Window,
140 create: (ComponentScope) -> C,
141 fonts: FontCollection? = None,
142 preferences: UiPreferences = uiPreferences()
143 ): UiWindow? {
144 checkThread()
145 if (closing)
146 throw IllegalStateException(Some("UI host is closed"))
147 return callback {
148 var root: UiRoot? = None
149 var surface: SurfaceWindow? = None
150 try {
151 preferences.check()
152 val created = UiRoot(this, window, component(create), fonts, preferences)
153 root = Some(created)
154 roots.add(created)
155 val attached = surfaces.attach(window, created)
156 surface = Some(attached)
157 if (attached.dispatch { created.mount(attached) }) {
158 integration?.attached(window)
159 Some(UiWindow(created))
160 } else
161 None
162 } catch (error: Throwable) {
163 when (surface) {
164 // A published Surface only propagates a failed error handler or host failure.
165 case Some(_) -> throw error
166 case None -> {
167 val failedRoot = root
168 val failure = cleanupUi(Some(error)) { failedRoot?.close() }!!
169 if (surfaces.isClosing)
170 throw failure
171 reportRootError(window.id, failure)
172 }
173 }
174 None
175 }
176 }
177 }
178 private fun reportRootError(id: WindowId, error: Throwable) {
179 if (closing)
180 throw error
181 try {
182 onRootError(id, error)
183 } catch (reported: Throwable) {
184 val failure: Throwable? =
185 if (reported === error)
186 Some(error)
187 else
188 Some(ResourceUseException(error, reported))
189 throw cleanupUi(failure) { close() }!!
190 }
191 }
192 public override fun onEvent(application: ActiveApplication, event: ApplicationEvent) {
193 checkThread()
194 when (active) {
195 case None -> active = Some(application)
196 case Some(val value) -> if (!(value === application))
197 throw IllegalStateException(Some("UI host belongs to another application"))
198 }
199 when (proxy) {
200 case None -> proxy = Some(application.proxy())
201 case Some(_) -> {}
202 }
203 callback {
204 nativeDepth += 1
205 try {
206 when (event) {
207 case Exiting -> integration?.close()
208 else -> {}
209 }
210 surfaces.onEvent(application, event)
211 when (event) {
212 case Exiting -> close()
213 else -> {}
214 }
215 } finally {
216 nativeDepth -= 1
217 }
218 }
219 }
220 internal fun enqueue(root: UiUpdateRoot) {
221 if (closing || !root.isOpen)
222 return
223 if (!root.pendingEnqueued) {
224 root.pendingEnqueued = true
225 pending.add(root)
226 }
227 if (!processing)
228 schedule()
229 }
230 private fun schedule() {
231 if (queued || closing || pending.size == 0L)
232 return
233 val mailbox =
234 proxy ?: throw IllegalStateException(Some("UI updates require a running host"))
235 queued = true
236 if (!mailbox.post { _ -> callback { flush() } }) {
237 queued = false
238 throw cleanupUi(Some(IllegalStateException(Some("UI update delivery failed")))) {
239 close()
240 }!!
241 }
242 }
243 internal fun dispatchRoot(root: UiRoot, action: () -> Unit): Boolean =
244 callback { root.surface.dispatch(action) }
245 private fun flush() {
246 queued = false
247 if (closing)
248 return
249 processing = true
250 val work = pending.toArray()
251 pending.clear()
252 for (root in work)
253 root.pendingEnqueued = false
254 try {
255 for (root in work)
256 if (root.isOpen)
257 root.dispatchUpdate()
258 } finally {
259 processing = false
260 }
261 schedule()
262 }
263 private fun <T> callback(block: () -> T): T {
264 depth += 1
265 var result: T? = None
266 var failure: Throwable? = None
267 try {
268 result = Some(block())
269 }
270 catch (error: Throwable) {
271 failure = Some(error)
272 }
273 depth -= 1
274 when (failure) {
275 case Some(_) -> failure = cleanupUi(failure) { close() }
276 case None -> {}
277 }
278 if (depth == 0)
279 failure = cleanupUi(failure) { finishRetirement() }
280 throwUi(failure)
281 return result!!
282 }
283 internal fun retire(root: UiRoot) {
284 if (nativeDepth > 0 || depth == 0)
285 root.closeSurface()
286 else
287 pendingRetirement = true
288 }
289 private fun finishRetirement() {
290 if (closing) {
291 surfaces.close()
292 pendingRetirement = false
293 } else
294 if (pendingRetirement) {
295 pendingRetirement = false
296 var failure: Throwable? = None
297 for (root in roots.toArray())
298 if (!root.isOpen)
299 failure = cleanupUi(failure) { root.closeSurface() }
300 when (failure) {
301 case Some(_) -> failure = cleanupUi(failure) { close() }
302 case None -> {}
303 }
304 throwUi(failure)
305 }
306 }
307 internal fun detached(root: UiRoot) {
308 removeRoot(roots, root)
309 removePending(root)
310 integration?.detached(root.window)
311 }
312 private fun removePending(root: UiUpdateRoot) {
313 for (index in 0L ..< pending.size)
314 if (pending[index] === root) {
315 pending.removeAt(index)
316 break
317 }
318 root.pendingEnqueued = false
319 }
320 public override fun close() {
321 checkThread()
322 if (closing)
323 return
324 closing = true
325 var failure = cleanupUi(None) { integration?.close() }
326 failure = cleanupUi(failure) { windowEvents.close() }
327 failure = cleanupUi(failure) { frameEvents.close() }
328 failure = cleanupUi(failure) { applicationRoot?.close() }
329 failure = cleanupUi(failure) { hostShortcuts?.close() }
330 hostShortcuts = None
331 queued = false
332 pending.clear()
333 for (root in roots.toArray()) {
334 root.pendingEnqueued = false
335 failure = cleanupUi(failure) { root.stop() }
336 }
337 if (nativeDepth > 0 || depth == 0)
338 failure = cleanupUi(failure) { surfaces.close() }
339 else
340 pendingRetirement = true
341 throwUi(failure)
342 }
345private fun removeRoot(values: ArrayList<UiRoot>, root: UiRoot) {
346 var index = 0L
347 while (index < values.size) {
348 if (values[index] === root) {
349 values.removeAt(index)
350 return
351 }
352 index += 1L
353 }