scoop:scoop.window:0.1.0
src/native/lifetime.scoop
Selected production source · src/native/lifetime.scoop
1
package scoop.window.native3
import scoop.window.*5
/** An explicit native borrow that prevents active destruction until owner-side retirement. */6
public class NativeWindowLease internal constructor(private val owner: WindowOwner) : Closeable {7
private val closed: AtomicBoolean = AtomicBoolean(false)8
private var closing: (() -> Unit)? = None9
internal fun onClosing(callback: () -> Unit) {10
closing = Some(callback)11
owner.closingLeases.add(this)12
}13
internal fun requestClose() {14
val callback = closing ?: return15
closing = None16
owner.application.mailbox.postControl { if (!closed.load()) callback() }17
}18
/** Queries the typed native handles on the owner thread while this lease is active. */19
public val handle: NativeWindowHandle20
@Unsafe get() {21
owner.application.checkThread()22
if (closed.load()) throw IllegalStateException(Some("native window lease is closed"))23
return platformNativeHandle(owner.pointer!!)24
}25
/** Ends the borrow once, from any thread; actual release remains on the owner. */26
public override fun close() {27
if (closed.exchange(true)) return28
owner29
.application30
.mailbox31
.postControl {32
closing = None33
for (index in 0L..<owner.closingLeases.size)34
if (owner.closingLeases[index] === this) {35
owner.closingLeases.removeAt(index)36
break37
}38
owner.leases -= 1L39
}40
}41
}43
/** Acquires an owner-thread lease before creating a renderer surface. */44
@Unsafe45
public fun Window.acquireNativeWindow(): NativeWindowLease {46
owner.requireOpen()47
owner.leases += 1L48
return NativeWindowLease(owner)49
}