scoop:scoop.ui:0.1.0
src/host/host.scoop
Selected production source · src/host/host.scoop
1
package scoop.ui3
import scoop.platform.concurrent.currentThreadId4
import scoop.graphics.text.FontCollection5
import scoop.surface.SurfaceHost6
import scoop.surface.SurfaceWindow7
import scoop.surface.HostShortcutScope8
import scoop.surface.ShortcutBinding9
import scoop.window.*11
internal interface UiUpdateRoot {12
val isOpen: Boolean13
var pendingEnqueued: Boolean14
fun dispatchUpdate()15
}17
/** Runs logical updates and Surface frames on the existing application owner. */18
public 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? = None27
private var active: ActiveApplication? = None28
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? = None32
private var queued = false33
private var processing = false34
private var depth = 035
private var nativeDepth = 036
internal val isDispatching: Boolean get() = depth > 0 || processing37
private var pendingRetirement = false38
private var closing = false39
private var hostShortcuts: HostShortcutScope? = None40
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(_) -> false73
}74
return closing && roots.size == 0L && applicationClosed && surfaces.isClosed75
}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) -> C87
): 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
else101
None102
}103
}105
internal fun reportApplicationError(error: Throwable) {106
if (closing)107
throw error108
try {109
onApplicationError(error)110
} catch (reported: Throwable) {111
val failure: Throwable? =112
if (reported === error)113
Some(error)114
else115
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 = None124
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 scope136
}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? = None149
var surface: SurfaceWindow? = None150
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
} else161
None162
} catch (error: Throwable) {163
when (surface) {164
// A published Surface only propagates a failed error handler or host failure.165
case Some(_) -> throw error166
case None -> {167
val failedRoot = root168
val failure = cleanupUi(Some(error)) { failedRoot?.close() }!!169
if (surfaces.isClosing)170
throw failure171
reportRootError(window.id, failure)172
}173
}174
None175
}176
}177
}178
private fun reportRootError(id: WindowId, error: Throwable) {179
if (closing)180
throw error181
try {182
onRootError(id, error)183
} catch (reported: Throwable) {184
val failure: Throwable? =185
if (reported === error)186
Some(error)187
else188
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 += 1205
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 -= 1217
}218
}219
}220
internal fun enqueue(root: UiUpdateRoot) {221
if (closing || !root.isOpen)222
return223
if (!root.pendingEnqueued) {224
root.pendingEnqueued = true225
pending.add(root)226
}227
if (!processing)228
schedule()229
}230
private fun schedule() {231
if (queued || closing || pending.size == 0L)232
return233
val mailbox =234
proxy ?: throw IllegalStateException(Some("UI updates require a running host"))235
queued = true236
if (!mailbox.post { _ -> callback { flush() } }) {237
queued = false238
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 = false247
if (closing)248
return249
processing = true250
val work = pending.toArray()251
pending.clear()252
for (root in work)253
root.pendingEnqueued = false254
try {255
for (root in work)256
if (root.isOpen)257
root.dispatchUpdate()258
} finally {259
processing = false260
}261
schedule()262
}263
private fun <T> callback(block: () -> T): T {264
depth += 1265
var result: T? = None266
var failure: Throwable? = None267
try {268
result = Some(block())269
}270
catch (error: Throwable) {271
failure = Some(error)272
}273
depth -= 1274
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
else287
pendingRetirement = true288
}289
private fun finishRetirement() {290
if (closing) {291
surfaces.close()292
pendingRetirement = false293
} else294
if (pendingRetirement) {295
pendingRetirement = false296
var failure: Throwable? = None297
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
break317
}318
root.pendingEnqueued = false319
}320
public override fun close() {321
checkThread()322
if (closing)323
return324
closing = true325
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 = None331
queued = false332
pending.clear()333
for (root in roots.toArray()) {334
root.pendingEnqueued = false335
failure = cleanupUi(failure) { root.stop() }336
}337
if (nativeDepth > 0 || depth == 0)338
failure = cleanupUi(failure) { surfaces.close() }339
else340
pendingRetirement = true341
throwUi(failure)342
}343
}345
private fun removeRoot(values: ArrayList<UiRoot>, root: UiRoot) {346
var index = 0L347
while (index < values.size) {348
if (values[index] === root) {349
values.removeAt(index)350
return351
}352
index += 1L353
}354
}