Skip to content

Instantly share code, notes, and snippets.

@EmmanuelOga
Last active October 19, 2020 04:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save EmmanuelOga/01fbf083042f5df7321db2b56d4ec449 to your computer and use it in GitHub Desktop.
Save EmmanuelOga/01fbf083042f5df7321db2b56d4ec449 to your computer and use it in GitHub Desktop.
Lanterna Demo
import com.googlecode.lanterna.TerminalPosition
import com.googlecode.lanterna.TextColor
import com.googlecode.lanterna.input.KeyType
import com.googlecode.lanterna.screen.TerminalScreen
import com.googlecode.lanterna.terminal.DefaultTerminalFactory
import com.googlecode.lanterna.terminal.swing.AWTTerminalFontConfiguration.BoldMode
import com.googlecode.lanterna.terminal.swing.SwingTerminalFontConfiguration
import java.awt.Font
import java.nio.charset.Charset
import javax.swing.JFrame
fun main() {
val fc = SwingTerminalFontConfiguration(true, BoldMode.EVERYTHING, Font("Source Code Pro", Font.PLAIN, 32))
val screen = DefaultTerminalFactory(System.out, System.`in`, Charset.forName("UTF8"))
.setTerminalEmulatorFontConfiguration(fc)
.createSwingTerminal().apply {
defaultCloseOperation = JFrame.EXIT_ON_CLOSE
isVisible = true
clearScreen()
}.let { terminal ->
TerminalScreen(terminal).apply { startScreen() }
}
var x = 0
var y = 0
var c: Char? = null
var p1: TerminalPosition? = null
var p2: TerminalPosition? = null
while (true) {
screen.doResizeIfNecessary()
screen.newTextGraphics().apply {
foregroundColor = TextColor.ANSI.RED
backgroundColor = TextColor.ANSI.GREEN
putString(0, 0, "($x, $y), p1: $p1 p2: $p2 ")
}
if (c != null) {
screen.newTextGraphics().apply { putString(x, y, "$c") }
if (c != ' ') x++
c = null
}
if (p1 != null && p2 != null) {
screen.newTextGraphics().apply {
foregroundColor = TextColor.ANSI.RED
drawLine(p1, p2, '*')
}
p1 = null
p2 = null
}
screen.cursorPosition = TerminalPosition(x, y)
screen.refresh()
val input = screen.readInput()
when (input.keyType) {
KeyType.Escape -> break
KeyType.Character -> {
c = input.character
if (c == ' ') {
c = null
TerminalPosition(x, y).let { p ->
if (p1 != null) {
p2 = p
} else {
p1 = p
}
}
}
}
KeyType.ArrowUp -> if (y > 0) y--
KeyType.ArrowDown -> if (y + 1 < screen.terminalSize.rows) y++
KeyType.ArrowLeft -> if (x > 0) x--
KeyType.ArrowRight -> if (x + 1 < screen.terminalSize.columns) x++
KeyType.Backspace -> if (x > 0) {
x--
c = ' '
}
}
}
screen.stopScreen(true)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment