view src/name/blackcap/clipman/Misc.kt @ 31:0c6c18a733b7

Compiles, new menu still a mess.
author David Barts <n5jrn@me.com>
date Thu, 30 Jan 2020 16:01:51 -0800
parents 8aa2dfac27eb
children 33fbe3a78d84
line wrap: on
line source

/*
 * Miscellaneous utility stuff.
 */
package name.blackcap.clipman

import java.awt.Dimension
import java.awt.Toolkit
import javax.swing.*
import javax.swing.text.JTextComponent

/**
 * Name of the character set (encoding) we preferentially use for many
 * things.
 */
val CHARSET_NAME = "UTF-8"

/**
 * Allows a val to have lateinit functionality. It is an error to attempt
 * to retrieve this object's value unless it has been set, and it is an
 * error to attempt to set the value of an already-set object.
 * @param &lt;T&gt; type of the associated value
 */
class LateInit<T> {
    private var _v: T? = null

    /**
     * The value associated with this object. The name of this property is
     * deliberately short.
     */
    var v: T
    get() {
        if (_v == null) {
            throw IllegalStateException("cannot retrieve un-initialized value")
        } else {
            return _v!!
        }
    }
    @Synchronized set(value) {
        if (_v != null) {
            throw IllegalStateException("cannot set already-initialized value")
        }
        _v = value
    }
}

/**
 * Run something in the Swing thread, asynchronously.
 * @param block lambda containing code to run
 */
fun inSwingThread(block: () -> Unit) {
    SwingUtilities.invokeLater(Runnable(block))
}

/**
 * Run something in the Swing thread, synchronously.
 * @param block lambda containing code to run
 */
fun inSynSwingThread(block: () -> Unit) {
    SwingUtilities.invokeAndWait(Runnable(block))
}

/**
 * Autosize a JTextComponent to a given width.
 * @param width the width
 */
fun JTextComponent.autoSize(width: Int): Unit {
    val SLOP = 10
    val dim = Dimension(width, width)
    preferredSize = dim
    size = dim
    val r = modelToView(document.length)
    preferredSize = Dimension(width, r.y + r.height + SLOP)
}

/**
 * Make a shortcut for a menu item, using the standard combining key
 * (control, command, etc.) for the system we're on.
 * @param key KeyEvent constant describing the key
 */
fun JMenuItem.makeShortcut(key: Int): Unit {
    val SC_KEY_MASK = Toolkit.getDefaultToolkit().menuShortcutKeyMask
    setAccelerator(KeyStroke.getKeyStroke(key, SC_KEY_MASK))
}

/**
 * Given a MenuElement object, get the item whose text matches the
 * specified text.
 * @param text to match
 * @return first matched element, null if no match found
 */
fun MenuElement.getItem(name: String) : JMenuItem? {
    subElements.forEach {
        val jMenuItem = it.component as? JMenuItem
        if (jMenuItem?.text == name) {
            return jMenuItem
        }
    }
    return null
}