scoop:scoop.ui:0.1.0
src/text/primary_selection.scoop
Selected production source · src/text/primary_selection.scoop
1
package scoop.ui.text3
import scoop.graphics.text.TextRange4
import scoop.window.*6
/** PRIMARY is independent of Copy/Paste; None follows the platform middle-button preference. */7
public struct TextPrimarySelectionOptions(val publish: Boolean = true, val paste: Boolean? = None)9
/** Owns only the current export, never the explicit copy/paste clipboard. */10
internal class PrimaryTextSelection(window: Window): Closeable {11
private val primary = window.primarySelection12
private var claim: PrimarySelectionClaim? = None13
private var selected: Utf8Selection? = None14
private var exported: String? = None16
internal val available: Boolean get() = primary.isAvailable18
internal fun update(selection: Utf8Selection, text: String?) {19
if (text == None || !primary.isAvailable) {20
close()21
return22
}23
if (selected == Some(selection) && exported == text)24
return25
selected = Some(selection)26
exported = text27
val previous = claim28
claim = None29
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 None43
return primary.readText()44
}46
public override fun close() {47
val previous = claim48
claim = None49
selected = None50
exported = None51
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
}61
}63
internal fun TextEditHost.refreshPrimarySelection() {64
val range = current.selection.range65
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.available76
)77
Some(current.text.utf8Slice(range))78
else79
None80
)81
}83
internal fun SelectableTextHost.refreshPrimarySelection(available: Boolean) {84
val range = selection.range85
primarySelection.update(86
selection,87
if (88
available &&89
options.primarySelection.publish &&90
options.copy &&91
range.start !=92
range.end &&93
primarySelection.available94
)95
Some(content.toPlainText(TextRange(range.start, range.end)))96
else97
None98
)99
}