view src/main/kotlin/name/blackcap/passman/Clipboard.kt @ 9:72619175004e

Fix issues found in testing.
author David Barts <n5jrn@me.com>
date Sat, 01 Oct 2022 09:57:23 -0700
parents 3c792ad36b3d
children
line wrap: on
line source

package name.blackcap.passman

import java.awt.Toolkit
import java.awt.datatransfer.Clipboard
import java.awt.datatransfer.DataFlavor
import java.awt.datatransfer.Transferable
import java.awt.datatransfer.UnsupportedFlavorException

private val CLIPBOARD = Toolkit.getDefaultToolkit().systemClipboard

private class ClipboardData(val item: String): Transferable {
    private val FLAVORS = arrayOf<DataFlavor>(DataFlavor.stringFlavor)

    override fun getTransferDataFlavors(): Array<DataFlavor> = FLAVORS

    override fun isDataFlavorSupported(flavor: DataFlavor?): Boolean =
        FLAVORS.contains(flavor)

    override fun getTransferData(flavor: DataFlavor?): Any {
        if (!isDataFlavorSupported(flavor)) {
            throw UnsupportedFlavorException(flavor)
        }
        return item
    }

}

private class ClipboardOwner(): java.awt.datatransfer.ClipboardOwner {
    override fun lostOwnership(clipboard: Clipboard?, contents: Transferable?) {
        /* we don't care */
    }
}

/* XXX: This will make a string out of a password. Shikata ga nai. */
fun writeToClipboard(charArray: CharArray) {
    CLIPBOARD.setContents(ClipboardData(String(charArray)), ClipboardOwner())
}

fun writeToClipboard(string: String) {
    CLIPBOARD.setContents(ClipboardData(string), ClipboardOwner())
}