Scoop API

scoop:scoop.window:0.1.0

src/owner/application_owner.scoop

Selected production source · src/owner/application_owner.scoop

1package scoop.window
3import scoop.platform.concurrent.ThreadId
4import scoop.platform.concurrent.currentThreadId
5import scoop.platform.time.MonotonicInstant
6import scoop.window.native.ApplicationAttachment
7import scoop.window.native.ApplicationHost
8import scoop.window.native.ApplicationWatch
9import scoop.window.native.NativeApplicationLease
10import scoop.window.native.dispatchWatch
12internal 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 = 1L
21 val fileDialogs = ArrayList<FileDialogOwner>()
22 var nextFileDialog = 1L
23 val menus = ArrayList<MenuOwner>()
24 val nativeResources = ArrayList<NativeApplicationLease>()
25 var nextMenu = 1L
26 var nextMenuItem = 1L
27 var nextMenuUse = 1L
28 var nextPopup = 1L
29 val pendingInputs = ArrayList<NativeInputDelivery>()
30 val nativeOperations = ArrayList<() -> Unit>()
31 var dragSource: DragSession? = None
32 var nativeOperationDepth = 0
33 val deadlines = ArrayList<WindowDeadline>()
34 var armedDeadline: MonotonicInstant? = None
35 var monitorRecords: ArrayList<MonitorRecord> = ArrayList<MonitorRecord>()
36 var nextMonitor: Long = 1L
37 val watches: ArrayList<ApplicationWatch> = ArrayList<ApplicationWatch>()
38 var interactionPreferences = InteractionPreferences()
39 val preferencesObservers = ArrayList<InteractionPreferencesObserver>()
40 var nextWatch: Long = 1L
41 val active = ActiveApplication(this)
42 var native: Ptr<Unit>? = None
43 var handler: ApplicationHandler? = None
44 var attachment: ApplicationAttachment? = None
45 var attached: Boolean = false
46 var attachmentComplete: Boolean = false
47 var attachmentCloseRequested: Boolean = false
48 var exiting: Boolean = false
49 var exitingDelivered: Boolean = false
50 var stopped: Boolean = false
51 var initialized: Boolean = false
52 var dispatchDepth: Int = 0
53 var nativeCallbackDepth: Int = 0
54 var pumping: Boolean = false
55 var flow: ControlFlow = ControlFlow.Wait
56 var failure: Throwable? = None
57 private var thread: ThreadId? = None
58 private var started: Boolean = false
59 private var nextWindow: Long = 1L
60 private var createdWindow: Boolean = false
62 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 @Unsafe
72 {
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 = true
87 thread = Some(currentThreadId())
88 this.handler = Some(handler)
89 @Unsafe
90 {
91 val callback =
92 foreignCallback<(Ptr<Unit>, Long, Int) -> Int>(
93 {
94 identity: Long, stage: Int ->
95 nativeCallback(identity, stage);
96 0
97 },
98 0,
99 ForeignCallbackMode.Reusable
100 )
101 try {
102 val pointer =
103 nativeApplicationCreate(
104 callback.function,
105 callback.context,
106 activationPolicy,
107 applicationId
108 )
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 = false
122 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 = None
147 };
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 += 1
161 try {
162 if (identity == 0L) {
163 pump(stage)
164 drainNativeOperations()
165 } else
166 dispatchWatch(identity, stage)
167 }
168 catch (error: Throwable) {
169 recordFailure(error);
170 beginExit();
171 drainShutdown()
172 } finally {
173 nativeCallbackDepth -= 1
174 }
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 += 1L
190 val flags =
191 flag(frameCode(attributes.frame) != 2) +
192 flag(attributes.resizable) *
193 2 +
194 flag(attributes.transparent) *
195 4
196 val size = attributes.size
197 @Unsafe
198 {
199 val pointer =
200 attributes.title.withUtf8Bytes(
201 fun(title: Ptr<UInt8>, count: Long): Ptr<Unit> {
202 @Unsafe
203 {
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 -> None
215 },
216 if (attributes.role == WindowRole.Tool)
217 1
218 else
219 0
220 )
221 }
222 }
223 )
224 val owner = WindowOwner(this, identity, pointer)
225 owner.owningWindow = parent
226 owner.role = attributes.role
227 try {
228 applyCreationProperties(owner, attributes)
229 owner.metrics = platformWindowMetrics(pointer)
230 if (owner.metrics == None)
231 owner.phase = WindowState.PendingConfigure
232 } catch (error: Throwable) {
233 nativeWindowDestroy(pointer)
234 throw error
235 }
236 windows.add(owner)
237 updateModalInput()
238 createdWindow = true
239 owner.requestedVisible = attributes.visible
240 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 0
250 }
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.Requested
260 )
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 None
271 }
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 -> flow
281 }
282 refreshDeadline()
283 if (flow == ControlFlow.Poll)
284 mailbox.wake()
285 }
287 fun beginExit() {
288 if (exiting)
289 return
290 exiting = true
291 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 = true
312 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 || pumping
321 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 -> error
332 }
333 )
334 }
336 fun didDestroyWindow() {
337 if (
338 !exiting &&
339 createdWindow &&
340 windows.size ==
341 0L &&
342 lastWindowPolicy ==
343 LastWindowPolicy.Exit
344 )
345 beginExit()
346 }