aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/at/hannibal2/skyhanni/utils/ClipboardUtils.kt
blob: b1d8eb68b584f0b8447238073f36daf98a064da0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package at.hannibal2.skyhanni.utils

import at.hannibal2.skyhanni.SkyHanniMod
import at.hannibal2.skyhanni.test.command.ErrorManager
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.awt.Toolkit
import java.awt.datatransfer.Clipboard
import java.awt.datatransfer.DataFlavor
import java.awt.datatransfer.StringSelection
import java.awt.datatransfer.UnsupportedFlavorException
import kotlin.time.Duration.Companion.milliseconds

object ClipboardUtils {

    private var dispatcher = Dispatchers.IO
    private var lastClipboardAccessTime = SimpleTimeMark.farPast()

    private fun canAccessClipboard(): Boolean {
        val result = lastClipboardAccessTime.passedSince() > 10.milliseconds
        if (result) {
            lastClipboardAccessTime = SimpleTimeMark.now()
        }
        return result
    }

    private suspend fun getClipboard(): Clipboard? {
        val deferred = CompletableDeferred<Clipboard?>()
        if (canAccessClipboard()) {
            deferred.complete(Toolkit.getDefaultToolkit().systemClipboard)
        } else {
            LorenzUtils.runDelayed(5.milliseconds) {
                SkyHanniMod.coroutineScope.launch {
                    deferred.complete(getClipboard())
                }
            }
        }
        return deferred.await()
    }

    fun copyToClipboard(text: String, step: Int = 0) {
        SkyHanniMod.coroutineScope.launch {
            try {
                getClipboard()?.setContents(StringSelection(text), null)
            } catch (e: Exception) {
                if (step == 3) {
                    ErrorManager.logError(e, "Error while trying to access the clipboard.")
                } else {
                    copyToClipboard(text, step + 1)
                }
            }
        }
    }

    suspend fun readFromClipboard(step: Int = 0): String? {
        try {
            return try {
                withContext(dispatcher) {
                    getClipboard()?.getData(DataFlavor.stringFlavor)?.toString()
                }
            } catch (e: UnsupportedFlavorException) {
                null
            }
        } catch (e: Exception) {
            return if (step == 3) {
                ErrorManager.logError(e, "Error while trying to access the clipboard.")
                null
            } else {
                readFromClipboard(step + 1)
            }
        }
    }
}