Scoop API

scoop:scoop.ui:0.1.0

src/host/preferences.scoop

Selected production source · src/host/preferences.scoop

1package scoop.ui
3import scoop.window.InteractionPreferences
4import scoop.window.interactionPreferences
5import scoop.window.observeInteractionPreferences
7/** One native observation per root; effective changes reuse ordinary UI invalidation. */
8internal class RootPreferences(private val root: UiRoot, initial: UiPreferences): Closeable {
9 private var system = root.window.interactionPreferences
10 var options = initial
11 var value = initial.resolve(system)
12 val signal = StateSignal()
13 var revision = 0L
14 val observers = ArrayList<UiPreferenceObserver>()
15 private val pending = ArrayList<InteractionPreferences>()
16 private var notifying = false
17 private var native: Closeable? = None
19 init {
20 initial.check()
21 }
23 fun start() {
24 native =
25 Some(
26 root.window.observeInteractionPreferences {
27 next -> if (root.isOpen)
28 root.surface.dispatch {
29 system = next
30 publish()
31 }
32 }
33 )
34 }
36 fun replace(next: UiPreferences) {
37 options = next
38 publish()
39 }
41 fun observe(action: (InteractionPreferences) -> Unit): Closeable {
42 checkFocusMutation()
43 val observer = UiPreferenceObserver(root, this, action)
44 observers.add(observer)
45 return observer
46 }
48 private fun publish() {
49 val next = options.resolve(system)
50 if (next == value)
51 return
52 value = next
53 revision += 1L
54 signal.changed(UiInvalidation.Layout)
55 root.requestFrame()
56 pending.add(next)
57 if (notifying)
58 return
59 notifying = true
60 try {
61 while (root.isOpen && pending.size > 0L) {
62 val event = pending.removeAt(0L)
63 for (observer in observers.toArray()) {
64 if (!root.isOpen)
65 break
66 observer.deliver(event)
67 }
68 }
69 } finally {
70 notifying = false
71 pending.clear()
72 }
73 }
75 public override fun close() {
76 native?.close()
77 native = None
78 for (observer in observers)
79 observer.retire()
80 observers.clear()
81 pending.clear()
82 }
85internal class UiPreferenceObserver(
86 private val root: UiRoot,
87 private val owner: RootPreferences,
88 action: (InteractionPreferences) -> Unit
89): Closeable {
90 private var callback: ((InteractionPreferences) -> Unit)? = Some(action)
92 fun deliver(value: InteractionPreferences) {
93 callback?.invoke(value)
94 }
96 fun retire() {
97 callback = None
98 }
100 public override fun close() {
101 root.checkThread()
102 when (callback) {
103 case None -> return
104 case Some(_) -> Unit
105 }
106 retire()
107 for (index in 0L ..< owner.observers.size)
108 if (owner.observers[index] === this) {
109 owner.observers.removeAt(index)
110 return
111 }
112 }