diff src/name/blackcap/clipman/PasteboardQueue.kt @ 0:be282c48010a

Incomplete; checking it in as a backup.
author David Barts <n5jrn@me.com>
date Tue, 14 Jan 2020 14:07:19 -0800
parents
children fb224c3aebdf
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/name/blackcap/clipman/PasteboardQueue.kt	Tue Jan 14 14:07:19 2020 -0800
@@ -0,0 +1,65 @@
+/*
+ * The queue of pasteboard items we manage. New stuff gets added to the
+ * tail, and old stuff truncated off the head.
+ */
+package name.blackcap.clipman
+
+import java.awt.Container
+import java.util.Collections
+import java.util.LinkedList
+import javax.swing.*
+
+/**
+ * A queue that tracks the data we display and the widgets used to
+ * display them. We never explicitly remove stuff from the queue,
+ * though items will get silently discarded to prevent the queue from
+ * exceeding the specified maximum size.
+ */
+class PasteboardQueue(val parent: Container, maxSize: Int) {
+    private val queue = LinkedList<QueueItem>()
+    private var _maxSize = maxSize
+
+    /**
+     * The maximum allowed size of this queue. Attempts to make the queue
+     * larger than this size, or specifying a size smaller than the current
+     * size, will result in the oldest item(s) being discarded. A size less
+     * than or equal to zero means an unlimited size.
+     */
+    var maxSize: Int
+        get() { return _maxSize }
+        @Synchronized set(value) {
+            _maxSize = value
+            truncate(false)
+        }
+
+    /**
+     * Add a JComponent to the end of the queue.
+     * @param item JComponent to add
+     */
+    @Synchronized fun add(item: QueueItem) {
+        inSwingThread { parent.add(item.component) }
+        queue.addLast(item)
+        truncate(true)
+    }
+
+    private fun truncate(forceValidate: Boolean) {
+        if (_maxSize > 0) {
+            var size = queue.size
+            var dirty = forceValidate
+            while (size > _maxSize) {
+                var extra = queue.removeFirst().component
+                inSwingThread { parent.remove(extra) }
+                dirty = true
+                size -= 1
+            }
+            if (dirty) {
+                inSwingThread { parent.validate() }
+            }
+        }
+    }
+}
+
+/**
+ * An item in the above queue.
+ */
+data class QueueItem(val component: JComponent, val contents: PasteboardItem)