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

import at.hannibal2.skyhanni.test.command.CopyErrorCommand
import net.minecraft.client.settings.KeyBinding
import org.lwjgl.input.Keyboard
import java.awt.Desktop
import java.awt.Toolkit
import java.awt.datatransfer.DataFlavor
import java.awt.datatransfer.StringSelection
import java.awt.datatransfer.UnsupportedFlavorException
import java.io.IOException
import java.net.URI

object OSUtils {

    @JvmStatic
    fun openBrowser(url: String) {
        if (Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) {
            try {
                Desktop.getDesktop().browse(URI(url))
            } catch (e: IOException) {
                e.printStackTrace()
                LorenzUtils.error("[SkyHanni] Error opening website: $url!")
            }
        } else {
            copyToClipboard(url)
            LorenzUtils.warning("[SkyHanni] Web browser is not supported! Copied url to clipboard.")
        }
    }

    fun copyToClipboard(text: String) {
        try {
            Toolkit.getDefaultToolkit().systemClipboard.setContents(StringSelection(text), null)
        } catch (e: Exception) {
            CopyErrorCommand.logError(e, "Error while trying to set clipboard content.")
        }
    }

    fun readFromClipboard(): String? {
        val systemClipboard = Toolkit.getDefaultToolkit().systemClipboard ?: return null
        try {
            val data = systemClipboard.getData(DataFlavor.stringFlavor) ?: return null
            return data.toString()
        } catch (e: UnsupportedFlavorException) {
            return null
        }
    }

    fun KeyBinding.isActive(): Boolean {
        if (!Keyboard.isCreated()) return false
        try {
            if (Keyboard.isKeyDown(this.keyCode)) return true
        } catch (e: IndexOutOfBoundsException) {
            println("KeyBinding isActive caused an IndexOutOfBoundsException with keyCode: $keyCode")
            e.printStackTrace()
            return false
        }
        return this.isKeyDown || this.isPressed
    }
}