chore: implement some IO utilities

This commit is contained in:
Alexander Klee 2024-05-15 20:08:51 +02:00
parent 9936fa3f78
commit 217979e9d7
2 changed files with 72 additions and 0 deletions

View File

@ -0,0 +1,21 @@
package io.gitlab.jfronny.sdom.ui
import com.intellij.openapi.fileTypes.FileType
import com.intellij.testFramework.LightVirtualFileBase
import com.intellij.util.LocalTimeCounter
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.InputStream
import java.io.OutputStream
class ByteVirtualFile(name: String, fileType: FileType?, modificationStamp: Long, private val content: ByteArray) : LightVirtualFileBase(name, fileType, modificationStamp) {
constructor() : this("")
constructor(name: String) : this(name, ByteArray(0))
constructor(name: String, content: ByteArray) : this(name, null, LocalTimeCounter.currentTime(), content)
constructor(name: String, fileType: FileType?, content: ByteArray) : this(name, fileType, LocalTimeCounter.currentTime(), content)
override fun getOutputStream(requestor: Any?, newModificationStamp: Long, newTimeStamp: Long): OutputStream = ByteArrayOutputStream()
override fun contentsToByteArray(): ByteArray = this.content.copyOf()
override fun getInputStream(): InputStream = ByteArrayInputStream(content)
override fun getLength(): Long = content.size.toLong()
}

View File

@ -0,0 +1,51 @@
package io.gitlab.jfronny.sdom.util
import java.awt.Desktop
import java.io.File
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
import java.util.regex.Pattern
import java.util.stream.Stream
object OSUtils {
var TYPE: Type? = System.getProperty("os.name", "generic").lowercase().let { os ->
if ((os.contains("mac")) || (os.contains("darwin"))) {
Type.MAC_OS
} else if (os.contains("win")) {
Type.WINDOWS
} else if (os.contains("nux")) {
Type.LINUX
} else {
null // probably fine :)
}
}
fun executablePathContains(executableName: String): Boolean {
return try {
Stream.of(
*System.getenv("PATH").split(Pattern.quote(File.pathSeparator).toRegex()).dropLastWhile { it.isEmpty() }
.toTypedArray())
.map { path: String -> path.replace("\"", "") }
.map { first: String -> Paths.get(first) }
.anyMatch { path: Path ->
(Files.exists(path.resolve(executableName))
&& Files.isExecutable(path.resolve(executableName)))
}
} catch (e: Exception) {
false
}
}
fun openFile(path: File) {
if (OSUtils.TYPE === OSUtils.Type.LINUX && OSUtils.executablePathContains("xdg-open")) {
Runtime.getRuntime().exec(arrayOf("xdg-open", path.absolutePath))
} else if (Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) {
Desktop.getDesktop().open(path)
}
}
enum class Type {
WINDOWS, MAC_OS, LINUX
}
}