Scoop API

scoop:scoop.ui:0.1.0

src/text/primary_selection.scoop

Selected production source · src/text/primary_selection.scoop

1package scoop.ui.text
3import scoop.graphics.text.TextRange
4import scoop.window.*
6/** PRIMARY is independent of Copy/Paste; None follows the platform middle-button preference. */
7public struct TextPrimarySelectionOptions(val publish: Boolean = true, val paste: Boolean? = None)
9/** Owns only the current export, never the explicit copy/paste clipboard. */
10internal class PrimaryTextSelection(window: Window): Closeable {
11 private val primary = window.primarySelection
12 private var claim: PrimarySelectionClaim? = None
13 private var selected: Utf8Selection? = None
14 private var exported: String? = None
16 internal val available: Boolean get() = primary.isAvailable
18 internal fun update(selection: Utf8Selection, text: String?) {
19 if (text == None || !primary.isAvailable) {
20 close()
21 return
22 }
23 if (selected == Some(selection) && exported == text)
24 return
25 selected = Some(selection)
26 exported = text
27 val previous = claim
28 claim = None
29 try {
30 claim = primary.claimText(text!!)
31 } catch (_: WindowException) {
32 // A failed implicit export must not interrupt editing or rendering.
33 } catch (_: IllegalArgumentException) {
34 // Native plain-text selection protocols cannot carry an embedded NUL.
35 } finally {
36 release(previous)
37 }
38 }
40 internal fun read(options: TextPrimarySelectionOptions): String? {
41 if (!primary.isAvailable || !(options.paste ?: primary.defaultPasteEnabled))
42 return None
43 return primary.readText()
44 }
46 public override fun close() {
47 val previous = claim
48 claim = None
49 selected = None
50 exported = None
51 release(previous)
52 }
54 private fun release(value: PrimarySelectionClaim?) {
55 try {
56 value?.close()
57 } catch (_: WindowException) {
58 // Implicit ownership cleanup cannot make an otherwise valid edit fail.
59 }
60 }
63internal fun TextEditHost.refreshPrimarySelection() {
64 val range = current.selection.range
65 primarySelection.update(
66 current.selection,
67 if (
68 options.enabled &&
69 options.primarySelection.publish &&
70 copyAllowed &&
71 !options.protectedText &&
72 !options.projection.masked &&
73 range.start !=
74 range.end &&
75 primarySelection.available
76 )
77 Some(current.text.utf8Slice(range))
78 else
79 None
80 )
83internal fun SelectableTextHost.refreshPrimarySelection(available: Boolean) {
84 val range = selection.range
85 primarySelection.update(
86 selection,
87 if (
88 available &&
89 options.primarySelection.publish &&
90 options.copy &&
91 range.start !=
92 range.end &&
93 primarySelection.available
94 )
95 Some(content.toPlainText(TextRange(range.start, range.end)))
96 else
97 None
98 )