scoop:scoop.window:0.1.0
src/owner/application_owner.scoop
Selected production source · src/owner/application_owner.scoop
1
package scoop.window3
import scoop.platform.concurrent.ThreadId4
import scoop.platform.concurrent.currentThreadId5
import scoop.platform.time.MonotonicInstant6
import scoop.window.native.ApplicationAttachment7
import scoop.window.native.ApplicationHost8
import scoop.window.native.ApplicationWatch9
import scoop.window.native.NativeApplicationLease10
import scoop.window.native.dispatchWatch12
internal class ApplicationOwner(13
val lastWindowPolicy: LastWindowPolicy,14
private val activationPolicy: Int,15
val applicationId: String?16
) {17
val mailbox: ApplicationMailbox = ApplicationMailbox()18
val windows: ArrayList<WindowOwner> = ArrayList<WindowOwner>()19
val modals = ArrayList<ModalSession>()20
var nextModal = 1L21
val fileDialogs = ArrayList<FileDialogOwner>()22
var nextFileDialog = 1L23
val menus = ArrayList<MenuOwner>()24
val nativeResources = ArrayList<NativeApplicationLease>()25
var nextMenu = 1L26
var nextMenuItem = 1L27
var nextMenuUse = 1L28
var nextPopup = 1L29
val pendingInputs = ArrayList<NativeInputDelivery>()30
val nativeOperations = ArrayList<() -> Unit>()31
var dragSource: DragSession? = None32
var nativeOperationDepth = 033
val deadlines = ArrayList<WindowDeadline>()34
var armedDeadline: MonotonicInstant? = None35
var monitorRecords: ArrayList<MonitorRecord> = ArrayList<MonitorRecord>()36
var nextMonitor: Long = 1L37
val watches: ArrayList<ApplicationWatch> = ArrayList<ApplicationWatch>()38
var interactionPreferences = InteractionPreferences()39
val preferencesObservers = ArrayList<InteractionPreferencesObserver>()40
var nextWatch: Long = 1L41
val active = ActiveApplication(this)42
var native: Ptr<Unit>? = None43
var handler: ApplicationHandler? = None44
var attachment: ApplicationAttachment? = None45
var attached: Boolean = false46
var attachmentComplete: Boolean = false47
var attachmentCloseRequested: Boolean = false48
var exiting: Boolean = false49
var exitingDelivered: Boolean = false50
var stopped: Boolean = false51
var initialized: Boolean = false52
var dispatchDepth: Int = 053
var nativeCallbackDepth: Int = 054
var pumping: Boolean = false55
var flow: ControlFlow = ControlFlow.Wait56
var failure: Throwable? = None57
private var thread: ThreadId? = None58
private var started: Boolean = false59
private var nextWindow: Long = 1L60
private var createdWindow: Boolean = false62
fun isCurrentThread(): Boolean = thread == Some(currentThreadId())63
fun checkThread() {64
if (!isCurrentThread())65
throw IllegalStateException(66
Some("window operation requires the application owner thread")67
)68
}70
fun run(handler: ApplicationHandler, attach: ((ApplicationHost) -> ApplicationAttachment)?) {71
@Unsafe72
{73
if (nativeIsMainThread() == 0)74
throw IllegalStateException(75
Some("Application.run requires the process main thread")76
)77
}78
when (currentJobOrNone()) {79
case Some(_) -> throw IllegalStateException(80
Some("Application.run requires a caller outside a Job")81
)82
case None -> {}83
}84
if (started)85
throw IllegalStateException(Some("Application.run is single-use"))86
started = true87
thread = Some(currentThreadId())88
this.handler = Some(handler)89
@Unsafe90
{91
val callback =92
foreignCallback<(Ptr<Unit>, Long, Int) -> Int>(93
{94
identity: Long, stage: Int ->95
nativeCallback(identity, stage);96
097
},98
0,99
ForeignCallbackMode.Reusable100
)101
try {102
val pointer =103
nativeApplicationCreate(104
callback.function,105
callback.context,106
activationPolicy,107
applicationId108
)109
native = Some(pointer)110
interactionPreferences = copyInteractionPreferences(pointer)111
mailbox.bind(pointer)112
try {113
when (attach) {114
case Some(val install) -> {115
attached = true;116
attachment = Some(install(ApplicationHost(this)))117
}118
case None -> {}119
}120
} catch (error: Throwable) {121
attached = false122
recordFailure(error)123
beginExit()124
}125
mailbox.wake()126
while (!stopped) {127
val status = nativeApplicationRun(pointer)128
if (!stopped) {129
recordFailure(130
WindowException(131
"native application loop",132
WindowErrorKind.NativeFailure,133
nativeCode = Some(status.toLong())134
)135
)136
beginExit()137
pump(0)138
}139
}140
} finally {141
retirePreferences()142
mailbox.unbind()143
when (native) {144
case Some(val pointer) -> {145
nativeApplicationDestroy(pointer);146
native = None147
};148
case None -> {}149
}150
releaseForeignCallback(callback)151
}152
}153
when (failure) {154
case Some(val error) -> throw error;155
case None -> {}156
}157
}159
fun nativeCallback(identity: Long, stage: Int) {160
nativeCallbackDepth += 1161
try {162
if (identity == 0L) {163
pump(stage)164
drainNativeOperations()165
} else166
dispatchWatch(identity, stage)167
}168
catch (error: Throwable) {169
recordFailure(error);170
beginExit();171
drainShutdown()172
} finally {173
nativeCallbackDepth -= 1174
}175
}177
fun createWindow(attributes: WindowAttributes): Window {178
checkThread()179
if (exiting || native == None)180
throw WindowException("create window", WindowErrorKind.InvalidState)181
validateAttributes(attributes)182
val parent = relationOwner(attributes.relation)183
if (attributes.role == WindowRole.Tool && !managementCapabilities().toolWindow)184
throw WindowException("tool window role", WindowErrorKind.Unsupported)185
attributes.size.toPhysical(1.0)186
if (nextWindow == 9223372036854775807L)187
throw WindowException("window identity", WindowErrorKind.NativeFailure)188
val identity = WindowId(nextWindow)189
nextWindow += 1L190
val flags =191
flag(frameCode(attributes.frame) != 2) +192
flag(attributes.resizable) *193
2 +194
flag(attributes.transparent) *195
4196
val size = attributes.size197
@Unsafe198
{199
val pointer =200
attributes.title.withUtf8Bytes(201
fun(title: Ptr<UInt8>, count: Long): Ptr<Unit> {202
@Unsafe203
{204
return nativeWindowCreate(205
native!!,206
identity.value,207
title,208
count,209
size.width,210
size.height,211
flags,212
when (parent) {213
case Some(val value) -> value.pointer;214
case None -> None215
},216
if (attributes.role == WindowRole.Tool)217
1218
else219
0220
)221
}222
}223
)224
val owner = WindowOwner(this, identity, pointer)225
owner.owningWindow = parent226
owner.role = attributes.role227
try {228
applyCreationProperties(owner, attributes)229
owner.metrics = platformWindowMetrics(pointer)230
if (owner.metrics == None)231
owner.phase = WindowState.PendingConfigure232
} catch (error: Throwable) {233
nativeWindowDestroy(pointer)234
throw error235
}236
windows.add(owner)237
updateModalInput()238
createdWindow = true239
owner.requestedVisible = attributes.visible240
when (parent) {241
case Some(val value) -> {242
val snapshot = value.snapshot()243
owner.visibilitySuppressed =244
!value.requestedVisible ||245
value.visibilitySuppressed ||246
snapshot.visible ==247
0 ||248
snapshot.minimized !=249
0250
}251
case None -> {}252
}253
if (attributes.visible && !owner.visibilitySuppressed) {254
checkNativeStatus(nativeWindowVisible(pointer, 1), "visible")255
if (attributes.requestActivation && !owner.inputBlocked)256
nativeRequestStatus(257
nativeWindowFocus(pointer),258
"focus",259
RequestStatus.Requested260
)261
}262
return Window(owner)263
}264
}266
fun findWindow(identity: Long): WindowOwner? {267
for (window in windows)268
if (window.id.value == identity)269
return Some(window)270
return None271
}273
fun setControlFlow(flow: ControlFlow) {274
checkThread()275
if (exiting)276
throw WindowException("set control flow", WindowErrorKind.InvalidState)277
this.flow =278
when (flow) {279
case WaitUntil(val time) -> ControlFlow.WaitUntil(time.normalized())280
else -> flow281
}282
refreshDeadline()283
if (flow == ControlFlow.Poll)284
mailbox.wake()285
}287
fun beginExit() {288
if (exiting)289
return290
exiting = true291
retirePreferences()292
for (session in fileDialogs)293
session.cancel(FileDialogCancelReason.ApplicationExit)294
for (input in pendingInputs.toArray())295
input.close()296
mailbox.closeBusiness()297
refreshDeadline()298
for (menu in menus.toArray())299
menu.close(PopupCancelReason.ApplicationExit)300
for (resource in nativeResources.toArray())301
resource.requestClose()302
for (window in windows)303
window.close()304
mailbox.wake()305
}307
fun complete(error: Throwable?) {308
checkThread()309
if (!attached || attachmentComplete)310
throw IllegalStateException(Some("unexpected application attachment completion"))311
attachmentComplete = true312
when (error) {313
case Some(val value) -> recordFailure(value);314
case None -> {}315
}316
beginExit()317
mailbox.wake()318
}320
val accessibilityBusy: Boolean get() = dispatchDepth != 0 || nativeCallbackDepth != 0 || pumping321
fun failAccessibility(error: Throwable) {322
recordFailure(error)323
beginExit()324
}326
fun recordFailure(error: Throwable) {327
failure =328
Some(329
when (failure) {330
case Some(val previous) -> ResourceUseException(previous, error);331
case None -> error332
}333
)334
}336
fun didDestroyWindow() {337
if (338
!exiting &&339
createdWindow &&340
windows.size ==341
0L &&342
lastWindowPolicy ==343
LastWindowPolicy.Exit344
)345
beginExit()346
}347
}