aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/at/hannibal2/skyhanni/utils/ClipboardUtils.kt
blob: ddd072c2864df679e38953bbc7ff7d08aebb00a4 (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
package at.hannibal2.skyhanni.utils

import at.hannibal2.skyhanni.SkyHanniMod
import at.hannibal2.skyhanni.test.command.ErrorManager
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
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(retries: Int = 20): Clipboard? = if (canAccessClipboard()) {
        Toolkit.getDefaultToolkit().systemClipboard
    } else if (retries > 0) {
        delay(11)
        getClipboard(retries - 1)
    } else {
        ErrorManager.logErrorStateWithData("can not read clipboard",
            "clipboard can not be accessed after 20 retries")
        null
    }


    fun copyToClipboard(text: String, step: Int = 0) {
        SkyHanniMod.coroutineScope.launch {
            try {
                getClipboard()?.setContents(StringSelection(text), null)
            } catch (e: Exception) {
                if (step == 3) {
                    ErrorManager.logErrorWithData(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.logErrorWithData(e, "Error while trying to access the clipboard.")
                null
            } else {
                readFromClipboard(step + 1)
            }
        }
    }
}