diff src/name/blackcap/clipman/Misc.kt @ 27:8aa2dfac27eb

Big reorg; compiled but untested.
author David Barts <n5jrn@me.com>
date Wed, 29 Jan 2020 10:50:07 -0800
parents
children 0c6c18a733b7
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/name/blackcap/clipman/Misc.kt	Wed Jan 29 10:50:07 2020 -0800
@@ -0,0 +1,94 @@
+/*
+ * Miscellaneous utility stuff.
+ */
+package name.blackcap.clipman
+
+import java.awt.Dimension
+import java.awt.Toolkit
+import javax.swing.*
+import javax.swing.text.JTextComponent
+
+/**
+ * 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
+}
+