summaryrefslogtreecommitdiff
path: root/src/main/kotlin/moe/nea89/website/KConsole.kt
blob: 6c4f707caf0509232d915ab2fe62634d5023b6f9 (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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
package moe.nea89.website

import kotlinx.browser.document
import kotlinx.html.dom.append
import kotlinx.html.js.pre
import org.w3c.dom.HTMLElement
import org.w3c.dom.HTMLPreElement
import org.w3c.dom.events.KeyboardEvent
import kotlin.collections.set

class KConsole(
    private val root: HTMLElement,
    private val text: HTMLPreElement,
    private val fileSystem: KFileSystem?,
) {

    val fileAccessor = fileSystem?.let { FileAccessor(it) }

    companion object {
        val shlexRegex =
            """"([^"\\]+|\\.)+"|([^ "'\\]+|\\.)+|'([^'\\]+|\\.)+'""".toRegex()

        fun createFor(element: HTMLElement, fileSystem: KFileSystem? = null): KConsole {
            val text = element.append.pre()
            element.classList.add(Styles.consoleClass)
            val console = KConsole(element, text, fileSystem)
            document.body!!.onkeydown = console::keydown
            console.addLine("Starting up terminal.")
            console.rerender()
            return console
        }
    }

    enum class ConsoleState {
        SHELLPROMPT,
        IN_PROGRAM
    }

    var state = ConsoleState.SHELLPROMPT

    val lines = mutableListOf<String>()

    var input: String = ""

    fun addLines(newLines: List<String>) {
        lines.addAll(newLines)
    }

    fun addMultilineText(text: String) {
        addLines(text.split("\n"))
    }

    fun addLine(line: String) {
        lines.add(line)
    }

    fun scrollDown() {
        text.lastElementChild?.scrollIntoView()
    }

    fun rerender() {
        var view = lines.joinToString(separator = "\n")
        if (state == ConsoleState.SHELLPROMPT) {
            view += "\n${'$'} $input"
        }
        text.innerText = view
    }

    fun registerCommand(command: Command) {
        command.aliases.forEach {
            commands[it] = command
        }
        commands[command.name] = command
    }

    val commands = mutableMapOf<String, Command>()

    fun executeCommand(commandLine: String) {
        val parts = shlex(commandLine)
        if (parts.isNullOrEmpty()) {
            addLine("Syntax Error")
            return
        }
        val command = parts[0]
        println("Running command: $command")
        val arguments = parts.drop(1)
        val commandThing = commands[command]
        if (commandThing == null) {
            addLine("Unknown command")
            return
        }
        ShellExecutionContext.run(this, commandThing, command, arguments)
    }

    @OptIn(ExperimentalStdlibApi::class)
    fun shlex(command: String): List<String>? {
        var i = 0
        val parts = mutableListOf<String>()
        while (i < command.length) {
            val match = shlexRegex.matchAt(command, i)
            if (match == null) {
                println("Could not shlex: $command")
                return null
            }
            // TODO: Proper string unescaping
            parts.add(match.groupValues.drop(1).firstOrNull { it != "" } ?: "")
            i += match.value.length
            while (command[i] == ' ' && i < command.length)
                i++
        }
        return parts
    }

    fun keydown(event: KeyboardEvent) {
        if (event.altKey || event.ctrlKey || event.metaKey) return
        if (event.isComposing || event.keyCode == 229) return
        if (state != ConsoleState.SHELLPROMPT) return
        when (event.key) {
            "Enter" -> {
                val toExecute = input
                addLine("${'$'} $toExecute")
                input = ""
                executeCommand(toExecute)
            }
            "Backspace" -> input = input.substring(0, input.length - 1)
            else ->
                if (event.key.length == 1 || event.key.any { it !in 'a'..'z' && it !in 'A'..'Z' })
                    input += event.key
        }
        rerender()
        scrollDown()
    }
}