Compare commits

...

14 Commits

Author SHA1 Message Date
binekrasik
16c81e5d07 revert: "add notice" 2026-05-23 14:55:36 +02:00
binekrasik
085cec8dc0 chore: add notice 2026-05-22 23:57:40 +02:00
binekrasik
071d4e3aa4 chore: addition to the previous commit 2026-05-22 23:55:26 +02:00
binekrasik
d76119918d chore: add info 2026-05-22 23:54:10 +02:00
binekrasik
3798a53395 chore: rewrite loadprg & fix some issues 2026-05-22 23:27:04 +02:00
binekrasik
4777552106 sync: wip changes 2026-05-22 14:48:00 +02:00
binekrasik
62038c2814 fix: build errors 2026-05-21 23:42:51 +02:00
binekrasik
646a9f6b7a chore: fix bugs & qol 2026-05-21 23:42:14 +02:00
binekrasik
255cc6a858 chore: cleanup imports 2026-05-21 19:15:33 +02:00
binekrasik
e0269c9b6a sync: wip changes 2026-05-21 13:47:27 +02:00
binekrasik
0577ee49cf chore: bump versions 2026-05-20 23:22:16 +02:00
binekrasik
729c8a5fd1 docs: update tested browsers 2026-05-20 23:21:19 +02:00
binekrasik
0649843821 chore: offload user input to InputManager 2026-05-20 22:46:59 +02:00
binekrasik
abe52acaa7 sync: sync wip changes 2026-05-20 13:10:34 +02:00
22 changed files with 1860 additions and 260 deletions

View File

@@ -34,7 +34,8 @@ Aplikace je zdarma hostovaná přes Vercel a je veřejně dostupná na adrese ht
## testování
Aplikace je testována v následujících prohlížečích:
- `Helium 0.12.1.1 (Chromium 148.0.7778.96) (64-bit)`
- `Helium 0.12.3.1 (Chromium 148.0.7778.167) (64-bit)`
- `Firefox 151.0 (64-bit)`
## licence

View File

@@ -1,7 +1,7 @@
{
"name": "webshell",
"private": true,
"version": "0.0.0",
"version": "0.2.1",
"type": "module",
"scripts": {
"dev": "vite",

View File

@@ -4,7 +4,8 @@ import { Wush } from './shell/wush/Wush'
import { Terminal } from './terminal/Terminal'
import { EventBroadcaster } from './utils/EventBroadcaster'
export const WEBSHELL_VERSION = "0.1.0"
export const WEBSHELL_VERSION = "0.2.1"
export const INFO_COMMENT: string | null = null
// initialize object store for webfs
let WebfsDatabase: IDBDatabase | null = null

View File

@@ -172,7 +172,7 @@ export class Item {
return this.path === '/' ? '/' : this.path.substring(this.path.lastIndexOf('/') + 1)
}
ReadData(): string | null {
GetData(): string | null {
return this.data
}
@@ -193,6 +193,49 @@ export class Item {
return items.filter((item): item is Item => item !== null)
}
/**
* Copies this item to the destination, replacing any existing destination.
*/
async Copy(destination: Item): Promise<void> {
if (destination.path === this.path) {
throw new Error(`Cannot copy item onto itself: ${this.path}`)
}
if (!(await this.Exists())) {
throw new Error(`Cannot copy item that has not been created: ${this.path}`)
}
await this.load()
if (await destination.Exists()) {
await destination.Delete()
}
const childrenToCopy = this.isDirectory ? await this.List() : []
destination.isDirectory = this.isDirectory
destination.executable = this.executable
destination.data = this.isDirectory ? null : this.data
destination.children = []
await destination.Create()
if (this.isDirectory) {
await Promise.all(childrenToCopy.map(async child => {
const childDestinationPath = Item.NormalizePath(
`${destination.GetPath()}/${child.GetName()}`
)
const destChild = child.IsDirectory()
? await Item.openDir(childDestinationPath)
: await Item.open(childDestinationPath)
await child.Copy(destChild)
}))
await destination.load()
}
}
async Delete(): Promise<void> {
if (!(await this.Exists())) return

View File

@@ -9,20 +9,23 @@ export class Cat extends Program {
return 1
}
const item = await Item.open(Item.NormalizePath(args[1].startsWith('/') ? args[1] : `${workdir.GetPath()}/${args[1]}`))
const path = Item.NormalizePath(args[1].startsWith('/') ? args[1] : `${workdir.GetPath()}/${args[1]}`)
let item: Item
if (!(await item.Exists())) {
stdout.emit(`cat: error: item ${item.GetPath()} doesn't exist.\n`)
try {
item = await Item.open(path)
} catch (err) {
stdout.emit(`cat: error: item ${path} is a directory\n`)
return 2
}
if (item.IsDirectory()) {
stdout.emit(`cat: error: can't read data from a directory; item ${item.GetPath()} is a directory.\n`)
if (!(await item.Exists())) {
stdout.emit(`cat: error: item ${item.GetPath()} doesn't exist.\n`)
return 3
}
stdout.emit(`${item.ReadData()}`)
stdout.emit('<- EOF\n')
stdout.emit(`${item.GetData()}`)
stdout.emit('\x1B[0;30m\x1B[47m EOF \x1B[0m\n')
return 0
}

59
src/program/Cp.ts Normal file
View File

@@ -0,0 +1,59 @@
import { Item } from '../fs/Item'
import type { SimpleStream } from '../utils/SimpleStream'
import { Program } from './Program'
export class Cp extends Program {
constructor() {
super()
}
async Exec(_: SimpleStream<string>, stdout: SimpleStream<string>, workdir: Item, args: string[]): Promise<number> {
if (args.length < 3) {
stdout.emit("cp: error: missing the first and/or second path arguments\n")
return 1
}
let item1: Item
let item2: Item
let destIsDir = false
// figure out if the items are files or directories
try {
item1 = await Item.openDir(Item.NormalizePath(args[1].startsWith('/') ? args[1] : `${workdir.GetPath()}/${args[1]}`))
} catch {
item1 = await Item.open(Item.NormalizePath(args[1].startsWith('/') ? args[1] : `${workdir.GetPath()}/${args[1]}`))
}
try {
item2 = await Item.open(Item.NormalizePath(args[2].startsWith('/') ? args[2] : `${workdir.GetPath()}/${args[2]}`))
} catch {
item2 = await Item.openDir(Item.NormalizePath(args[2].startsWith('/') ? args[2] : `${workdir.GetPath()}/${args[2]}`))
destIsDir = true
}
if (!await item1.Exists()) {
stdout.emit(`cp: error: source item ${item1.GetPath()} does not exist.\n`)
return 2
}
if (await item2.Exists() && !destIsDir) {
stdout.emit(`cp: error: destination item ${item2.GetPath()} already exists.\n`)
return 2
}
// either copy the item into a destination directory or create a new copy
if (destIsDir) {
const destChild = await Item.open(Item.NormalizePath(`${item2.GetPath()}/${item1.GetName()}`))
await item1.Copy(destChild)
stdout.emit(`-> copied ${item1.GetPath()} -> ${destChild.GetPath()}\n`)
} else {
await item2.Create()
await item1.Copy(item2)
stdout.emit(`-> copied ${item1.GetPath()} -> ${item2.GetPath()}\n`)
}
return 0
}
}

390
src/program/Edit.ts Normal file
View File

@@ -0,0 +1,390 @@
import { GetCurrentTerminal } from '../app'
import { Item } from '../fs/Item'
import type { SimpleStream } from '../utils/SimpleStream'
import { Program } from './Program'
type Viewport = {
cols: number
rows: number
headerRows: number
footerRows: number
contentHeight: number
}
type PromptState =
| { active: false }
| { active: true; label: string; value: string; handler: (value: string) => Promise<void> }
export class Edit extends Program {
constructor() {
super()
}
async Exec(stdin: SimpleStream<string>, stdout: SimpleStream<string>, workdir: Item, args: string[]): Promise<number> {
if (args.length < 2) {
stdout.emit('edit: error: missing path argument\n')
return 1
}
const terminal = GetCurrentTerminal()
const resolvePath = (path: string) => Item.NormalizePath(path.startsWith('/') ? path : `${workdir.GetPath()}/${path}`)
let filePath = resolvePath(args[1])
let file = await Item.open(filePath, '')
let fileExists = await file.Exists()
let lines = this.normalizeLines(file.GetData())
let dirty = false
let cursorLine = 0
let cursorCol = 0
let preferredCol = 0
let scrollLine = 0
let scrollCol = 0
let statusMessage = ''
let exitArmed = false
let promptState: PromptState = { active: false }
const getViewport = (): Viewport => {
const cols = Math.max(1, Math.floor(terminal.GetWidthCells()))
const rows = Math.max(1, Math.floor(terminal.GetHeightCells()))
const headerRows = rows >= 3 ? 1 : 0
const footerRows = rows >= 2 ? 1 : 0
const contentHeight = Math.max(1, rows - headerRows - footerRows)
return { cols, rows, headerRows, footerRows, contentHeight }
}
const formatLine = (text: string, width: number) => {
if (text.length > width)
return text.slice(0, width)
return text.padEnd(width, ' ')
}
const clampCursor = () => {
cursorLine = Math.max(0, Math.min(cursorLine, lines.length - 1))
const lineLength = lines[cursorLine].length
cursorCol = Math.max(0, Math.min(cursorCol, lineLength))
preferredCol = cursorCol
}
const ensureCursorVisible = (viewport: Viewport) => {
if (cursorLine < scrollLine)
scrollLine = cursorLine
if (cursorLine >= scrollLine + viewport.contentHeight)
scrollLine = cursorLine - viewport.contentHeight + 1
if (cursorCol < scrollCol)
scrollCol = cursorCol
if (cursorCol >= scrollCol + viewport.cols)
scrollCol = cursorCol - viewport.cols + 1
const maxScrollLine = Math.max(0, lines.length - viewport.contentHeight)
scrollLine = Math.min(scrollLine, maxScrollLine)
scrollCol = Math.max(0, scrollCol)
}
const setStatus = (message: string) => {
statusMessage = message
}
const openFile = async (path: string) => {
try {
const resolved = resolvePath(path)
const nextFile = await Item.open(resolved, '')
const exists = await nextFile.Exists()
const content = nextFile.GetData()
filePath = resolved
file = nextFile
fileExists = exists
lines = this.normalizeLines(content)
dirty = false
cursorLine = 0
cursorCol = 0
preferredCol = 0
scrollLine = 0
scrollCol = 0
setStatus(exists ? `Opened ${filePath}` : `New file ${filePath}`)
} catch (e) {
setStatus(`Open failed: ${e instanceof Error ? e.message : String(e)}`)
}
}
const saveFile = async () => {
const data = lines.join('\n')
try {
if (fileExists) {
await file.Write(data)
} else {
const created = await Item.open(filePath, data)
await created.Create()
file = created
fileExists = true
}
dirty = false
exitArmed = false
setStatus(`Saved ${filePath}`)
} catch (e) {
setStatus(`Save failed: ${e instanceof Error ? e.message : String(e)}`)
}
}
const startPrompt = (label: string, handler: (value: string) => Promise<void>) => {
promptState = { active: true, label, value: '', handler }
}
const render = () => {
const viewport = getViewport()
const footerRow = viewport.headerRows + viewport.contentHeight + (viewport.footerRows ? 1 : 0)
ensureCursorVisible(viewport)
let output = '\x1b[2J'
if (viewport.headerRows) {
const headerText = `EDIT - ${filePath}${dirty ? ' *' : ''}`
output += `\x1b[1;1H${formatLine(headerText, viewport.cols)}`
}
const contentStartRow = viewport.headerRows + 1
for (let i = 0; i < viewport.contentHeight; i++) {
const lineIndex = scrollLine + i
const lineText = lines[lineIndex] ?? ''
const visible = lineText.slice(scrollCol, scrollCol + viewport.cols)
output += `\x1b[${contentStartRow + i};1H${formatLine(visible, viewport.cols)}`
}
if (viewport.footerRows) {
const positionText = `Ln ${cursorLine + 1}, Col ${cursorCol + 1}`
const shortcuts = 'F2 Save F3 Open F10 Exit'
const footerText = promptState.active
? `${promptState.label}${promptState.value}`
: `${shortcuts} ${positionText}${statusMessage ? ` ${statusMessage}` : ''}`
output += `\x1b[${footerRow};1H${formatLine(footerText, viewport.cols)}`
}
if (promptState.active) {
const cursorRow = footerRow
const cursorColPos = Math.min(viewport.cols, promptState.label.length + promptState.value.length + 1)
output += `\x1b[${cursorRow};${cursorColPos}H`
} else {
const cursorRow = contentStartRow + (cursorLine - scrollLine)
const cursorColPos = 1 + (cursorCol - scrollCol)
output += `\x1b[${cursorRow};${cursorColPos}H`
}
stdout.emit(output)
}
render()
while (true) {
const key = await stdin.wait()
if (promptState.active) {
if (key === 'Escape') {
promptState = { active: false }
setStatus('Canceled')
render()
continue
}
if (key === 'Enter') {
const { handler } = promptState
const value = promptState.value.trim()
promptState = { active: false }
if (value.length > 0) {
await handler(value)
} else {
setStatus('Canceled')
}
render()
continue
}
if (key === 'Backspace') {
const nextValue: string = promptState.value.slice(0, -1)
promptState = {
active: true,
label: promptState.label,
value: nextValue,
handler: promptState.handler,
}
render()
continue
}
if (key.length === 1) {
const nextValue: string = promptState.value + key
promptState = {
active: true,
label: promptState.label,
value: nextValue,
handler: promptState.handler,
}
render()
}
continue
}
if (exitArmed && key !== 'F10')
exitArmed = false
switch (key) {
case 'F2':
await saveFile()
render()
continue
case 'F3':
startPrompt('Open: ', openFile)
render()
continue
case 'F10':
if (dirty && !exitArmed) {
exitArmed = true
setStatus('Unsaved changes. Press F10 again to exit.')
render()
continue
}
stdout.emit('\x1b[2J\x1b[H')
return 0
case 'ArrowLeft':
if (cursorCol > 0) {
cursorCol -= 1
} else if (cursorLine > 0) {
cursorLine -= 1
cursorCol = lines[cursorLine].length
}
preferredCol = cursorCol
render()
continue
case 'ArrowRight': {
const lineLength = lines[cursorLine].length
if (cursorCol < lineLength) {
cursorCol += 1
} else if (cursorLine < lines.length - 1) {
cursorLine += 1
cursorCol = 0
}
preferredCol = cursorCol
render()
continue
}
case 'ArrowUp':
cursorLine = Math.max(0, cursorLine - 1)
cursorCol = Math.min(preferredCol, lines[cursorLine].length)
render()
continue
case 'ArrowDown':
cursorLine = Math.min(lines.length - 1, cursorLine + 1)
cursorCol = Math.min(preferredCol, lines[cursorLine].length)
render()
continue
case 'Home':
cursorCol = 0
preferredCol = cursorCol
render()
continue
case 'End':
cursorCol = lines[cursorLine].length
preferredCol = cursorCol
render()
continue
case 'PageUp': {
const viewport = getViewport()
cursorLine = Math.max(0, cursorLine - viewport.contentHeight)
cursorCol = Math.min(preferredCol, lines[cursorLine].length)
render()
continue
}
case 'PageDown': {
const viewport = getViewport()
cursorLine = Math.min(lines.length - 1, cursorLine + viewport.contentHeight)
cursorCol = Math.min(preferredCol, lines[cursorLine].length)
render()
continue
}
case 'Backspace':
if (cursorCol > 0) {
const line = lines[cursorLine]
lines[cursorLine] = line.slice(0, cursorCol - 1) + line.slice(cursorCol)
cursorCol -= 1
preferredCol = cursorCol
dirty = true
} else if (cursorLine > 0) {
const current = lines[cursorLine]
cursorLine -= 1
cursorCol = lines[cursorLine].length
lines[cursorLine] += current
lines.splice(cursorLine + 1, 1)
preferredCol = cursorCol
dirty = true
}
render()
continue
case 'Delete': {
const line = lines[cursorLine]
if (cursorCol < line.length) {
lines[cursorLine] = line.slice(0, cursorCol) + line.slice(cursorCol + 1)
dirty = true
} else if (cursorLine < lines.length - 1) {
lines[cursorLine] = line + lines[cursorLine + 1]
lines.splice(cursorLine + 1, 1)
dirty = true
}
render()
continue
}
case 'Enter': {
const line = lines[cursorLine]
const before = line.slice(0, cursorCol)
const after = line.slice(cursorCol)
lines[cursorLine] = before
lines.splice(cursorLine + 1, 0, after)
cursorLine += 1
cursorCol = 0
preferredCol = 0
dirty = true
render()
continue
}
case 'Tab':
lines[cursorLine] = this.insertText(lines[cursorLine], cursorCol, ' ')
cursorCol += 4
preferredCol = cursorCol
dirty = true
render()
continue
}
if (key.length === 1) {
lines[cursorLine] = this.insertText(lines[cursorLine], cursorCol, key)
cursorCol += 1
preferredCol = cursorCol
dirty = true
render()
continue
}
clampCursor()
render()
}
}
private normalizeLines(content: string | null): string[] {
const normalized = (content ?? '').replace(/\r\n/g, '\n').replace(/\r/g, '\n')
const lines = normalized.split('\n')
return lines.length === 0 ? [''] : lines
}
private insertText(line: string, index: number, text: string): string {
return line.slice(0, index) + text + line.slice(index)
}
}

View File

@@ -3,17 +3,33 @@ import type { SimpleStream } from '../utils/SimpleStream'
import { Program } from './Program'
export class Eval extends Program {
async Exec(_: SimpleStream<string>, stdout: SimpleStream<string>, _workdir: Item, args: string[]): Promise<number> {
const javascript = args.slice(1).join(' ')
async Exec(stdin: SimpleStream<string>, stdout: SimpleStream<string>, _workdir: Item, args: string[]): Promise<number> {
const inlineArgs = args.slice(1)
const source = inlineArgs.length > 0
? inlineArgs.join(' ')
: await stdin.wait()
if (source.trim().length === 0) {
stdout.emit('eval: error: missing javascript input\n')
return 1
}
try {
// todo: pass workdir to the program
eval(javascript)
} catch (e) {
stdout.emit(`${String(e)}\n`)
this.RunJs(source, stdout)
} catch {
return 1
}
return 0
}
private RunJs(javascript: string, stdout: SimpleStream<string>) {
try {
// todo: pass workdir to the program
eval(javascript)
} catch (e) {
stdout.emit(`${String(e)}\n`)
throw e
}
}
}

View File

@@ -1,4 +1,4 @@
import { GetCurrentTerminal, WEBSHELL_VERSION } from '../app'
import { GetCurrentTerminal, WEBSHELL_VERSION, INFO_COMMENT } from '../app'
import type { Item } from '../fs/Item'
import { Terminal } from '../terminal/Terminal'
import type { SimpleStream } from '../utils/SimpleStream'
@@ -6,9 +6,24 @@ import { Program } from './Program'
export class Info extends Program {
async Exec(_: SimpleStream<string>, stdout: SimpleStream<string>, __: Item, ___: string[]): Promise<number> {
stdout.emit(`Webshell v${WEBSHELL_VERSION}\n`)
stdout.emit(`Terminal v${Terminal.Version}\n`)
stdout.emit(`Running ${GetCurrentTerminal().GetShell()?.Name} v${GetCurrentTerminal().GetShell()?.Version}\n`)
stdout.emit('\n')
stdout.emit(" --> binekrasik's Webshell / ->\n\n")
stdout.emit(" Webshell and its components are licensed under the Apache 2.0 license unless stated otherwise.\n")
stdout.emit(" Source available at https://git.martinpetr.dev/binekrasik/webshell.\n\n\n")
stdout.emit(" --> Versions / ->\n\n")
stdout.emit(` Webshell ${WEBSHELL_VERSION}\n`)
stdout.emit(` Terminal ${Terminal.Version}\n`)
stdout.emit(` Shell '${GetCurrentTerminal().GetShell()?.Name}' version ${GetCurrentTerminal().GetShell()?.Version}\n\n\n`)
// print a comment for the current release (if any)
if (INFO_COMMENT) {
stdout.emit(" --> Version comment / ->\n\n")
stdout.emit(` ${INFO_COMMENT}\n\n\n`)
}
stdout.emit(" - Copyright (C) 2026 binekrasik -\n\n")
return 0
}

View File

@@ -1,4 +1,4 @@
import type { Item } from '../fs/Item'
import { Item } from '../fs/Item'
import type { Shell } from '../shell/Shell'
import type { SimpleStream } from '../utils/SimpleStream'
import { Program } from './Program'
@@ -11,19 +11,59 @@ export class Loadprg extends Program {
this.shell = shell
}
async Exec(_: SimpleStream<string>, stdout: SimpleStream<string>, __: Item, args: string[]): Promise<number> {
const javascript = args.slice(2).join(' ')
async Exec(_: SimpleStream<string>, stdout: SimpleStream<string>, workdir: Item, args: string[]): Promise<number> {
const path = Item.NormalizePath(args[1].startsWith('/') ? args[1] : `${workdir.GetPath()}/${args[1]}`)
let file: Item
try {
const program = eval(javascript)
this.shell.LoadProgram(new program(), args[1])
} catch (e) {
stdout.emit(`${String(e)}\n`)
stdout.emit(`${String((e as Error).stack)}\n`)
return 1
file = await Item.open(path)
} catch (err) {
stdout.emit(`loadprg: error: item ${path} is a directory\n`)
return 2
}
if (!(await file.Exists())) {
stdout.emit(`loadprg: error: item ${file.GetPath()} doesn't exist.\n`)
return 3
}
let programName: string | null = null
// check if we have a name argument
// use the file name if the program name wasn't explicitly specified
const nameArgIndex = args.findIndex(value => value === "--name")
if (nameArgIndex !== -1 && args[nameArgIndex + 1]) {
programName = args[nameArgIndex + 1]
} else programName = file.GetName()
// read the file
const javascript = file.GetData()
if (!javascript) {
stdout.emit(`loadprg: error: could not read the program data\n`)
return 3
}
// load the program
type EntrypointFunction = InstanceType<typeof Program>['Exec']
let programEntrypoint: EntrypointFunction
try {
// due to some inconveniences and limitations,
// we only allow for loading the program main method
// instead of an entire program class.
programEntrypoint = new Function("stdin", "stdout", "workdir", "args", javascript) as EntrypointFunction
} catch (err) {
stdout.emit(`loadprg: error: could not load the program: ${err}\n`)
stdout.emit(`-> Stacktrace: ${(err as Error).stack}\n`)
return 4
}
// create a wrapper class for the program
const wrapper: Program = new (class ProgramWrapper extends Program { Exec = programEntrypoint })
this.shell.LoadProgram(wrapper, programName)
stdout.emit(`-> Loaded program from ${file.GetPath()} as ${programName}\n`)
return 0
}
}

View File

@@ -9,7 +9,6 @@ export class Ls extends Program {
async Exec(_: SimpleStream<string>, stdout: SimpleStream<string>, workdir: Item, args: string[]): Promise<number> {
// open the target directory, default to workdir
const item = args[1]
? await Item.openDir(Item.NormalizePath(
args[1].startsWith('/')
@@ -32,7 +31,7 @@ export class Ls extends Program {
stdout.emit(` [ drwx name ]\n`)
const items = await item.List()
items.forEach(entry => {
stdout.emit(` | ${`${(entry.IsDirectory() ? 'd' : '-')}${(entry.IsReadable() ? 'r' : '-')}${(entry.IsWritable() ? 'w' : '-')}${(entry.IsExecutable() ? 'x' : '-')}`.padEnd(8, ' ')} ${entry.GetName()}\n`)
stdout.emit(` | ${`${(entry.IsDirectory() ? 'd' : '-')}${(entry.IsReadable() ? 'r' : '-')}${(entry.IsWritable() ? 'w' : '-')}${(entry.IsExecutable() ? 'x' : '-')}`.padEnd(8, ' ')} ${entry.IsDirectory() ? '\x1B[0;30m\x1B[47m' : ''}${entry.GetName()}\x1B[0m\n`)
})
return 0

View File

@@ -21,7 +21,7 @@ export class Mkdir extends Program {
return 2
}
item.Create()
await item.Create()
return 0
}

61
src/program/Mv.ts Normal file
View File

@@ -0,0 +1,61 @@
import { Item } from '../fs/Item'
import type { SimpleStream } from '../utils/SimpleStream'
import { Program } from './Program'
export class Mv extends Program {
constructor() {
super()
}
async Exec(_: SimpleStream<string>, stdout: SimpleStream<string>, workdir: Item, args: string[]): Promise<number> {
if (args.length < 3) {
stdout.emit("mv: error: missing the first and/or second path arguments\n")
return 1
}
let item1: Item
let item2: Item
let destIsDir = false
// figure out if the items are files or directories
try {
item1 = await Item.openDir(Item.NormalizePath(args[1].startsWith('/') ? args[1] : `${workdir.GetPath()}/${args[1]}`))
} catch {
item1 = await Item.open(Item.NormalizePath(args[1].startsWith('/') ? args[1] : `${workdir.GetPath()}/${args[1]}`))
}
try {
item2 = await Item.open(Item.NormalizePath(args[2].startsWith('/') ? args[2] : `${workdir.GetPath()}/${args[2]}`))
} catch {
item2 = await Item.openDir(Item.NormalizePath(args[2].startsWith('/') ? args[2] : `${workdir.GetPath()}/${args[2]}`))
destIsDir = true
}
if (!await item1.Exists()) {
stdout.emit(`mv: error: source item ${item1.GetPath()} does not exist.\n`)
return 2
}
if (await item2.Exists() && !destIsDir) {
stdout.emit(`mv: error: destination item ${item2.GetPath()} already exists.\n`)
return 2
}
// either move the file into a destination directory or move it to a new path
if (destIsDir) {
const destChild = await Item.open(Item.NormalizePath(`${item2.GetPath()}/${item1.GetName()}`))
await item1.Copy(destChild)
stdout.emit(`-> moved ${item1.GetPath()} -> ${destChild.GetPath()}\n`)
} else {
await item2.Create()
await item1.Copy(item2)
stdout.emit(`-> moved ${item1.GetPath()} -> ${item2.GetPath()}\n`)
}
await item1.Delete()
return 0
}
}

View File

@@ -20,7 +20,7 @@ export class Touch extends Program {
return 1
}
item.Create()
await item.Create()
return 0
}

45
src/program/Tree.ts Normal file
View File

@@ -0,0 +1,45 @@
import { Item } from '../fs/Item'
import type { SimpleStream } from '../utils/SimpleStream'
import { Program } from './Program'
export class Tree extends Program {
constructor() {
super()
}
async Exec(_: SimpleStream<string>, stdout: SimpleStream<string>, workdir: Item, args: string[]): Promise<number> {
// open the target directory, default to workdir
const item = args[1]
? await Item.openDir(Item.NormalizePath(
args[1].startsWith('/')
? args[1]
: `${workdir.GetPath()}/${args[1]}`
))
: workdir
if (args[1] && !item.IsDirectory()) {
stdout.emit("tree: error: the provided path is not a directory\n")
return 1
}
if (!(await item.Exists())) {
stdout.emit(`tree: error: path ${item.GetPath()} doesn't exist\n`)
return 2
}
stdout.emit(`-> Tree of item: '${item.GetPath()}'\n`)
await this.printTree(stdout, item, 1)
return 0
}
private async printTree(stdout: SimpleStream<string>, item: Item, depth: number): Promise<void> {
const items = await item.List()
for (const item of items) {
stdout.emit(` ${' |'.repeat(depth)}--+ ${item.IsDirectory() ? '\x1B[0;30m\x1B[47m' : ''}${item.GetName()}\x1B[0m\n`)
if (item.IsDirectory())
await this.printTree(stdout, item, depth + 1)
}
}
}

View File

@@ -7,7 +7,7 @@ export abstract class Shell {
readonly abstract Version: string
readonly abstract Name: string
broadcaster: EventBroadcaster
terminal: Terminal
readonly terminal: Terminal
constructor(broadcaster: EventBroadcaster, terminal: Terminal) {
this.broadcaster = broadcaster
@@ -17,6 +17,5 @@ export abstract class Shell {
abstract LoadProgram(program: Program, name: string): void
abstract ExecuteProgram(name: string, args: string[]): void
abstract Init(): Promise<void>
abstract HandleKeyInput(key: string, isCharacter: boolean): void
abstract SetWorkingDirectory(directory: Item): Promise<void>
}

View File

@@ -0,0 +1,40 @@
/**
* Wush environment manager
* Manages environment variables, aliases etc.
*/
export class Environment {
private variables: Record<string, string> = {}
private aliases: Record<string, string> = {}
SetVariable(name: string, value: any | null): void {
if (value === null) {
// remove the variable if value is null
delete this.variables[name]
} else this.variables[name] = String(value)
}
GetVariable(name: string): string | null {
return this.variables[name] ?? null
}
SetAlias(name: string, value: string | null): void {
if (value === null) {
// remove the alias if value is null
delete this.aliases[name]
} else this.aliases[name] = value
}
GetAlias(name: string): string | null {
return this.aliases[name] ?? null
}
GetAliasesByValue(value: string): string[] | null {
const keys: string[] = []
for (const key in this.aliases)
if (this.aliases[key] === value)
keys.push(key)
return keys.length === 0 ? null : keys
}
}

View File

@@ -0,0 +1,242 @@
import type { EventBroadcaster } from "../../utils/EventBroadcaster"
import type { Wush } from "./Wush"
export type ModifierKey = 'shift' | 'ctrl' | 'alt' | 'rightAlt'
/**
* Wush input manager
* Manages input events and holds command history
*/
export class InputManager {
private modifierKeys: ModifierKey[] = []
private shell: Wush
private keyEventBroadcaster: EventBroadcaster
// history
history: string[] = []
historyIndex: number | null = null
historyDraft: string = ''
constructor(shell: Wush, keyEventBroadcaster: EventBroadcaster) {
this.shell = shell
this.keyEventBroadcaster = keyEventBroadcaster
}
//
// -> history management
//
private NavigateHistory(direction: -1 | 1) {
// don't continue if there's no history
if (this.history.length === 0)
return
// I honestly don't know how but it works.
// __**do not touch this under any circumstances**__
if (direction === -1) {
if (this.historyIndex === null) {
this.historyDraft = this.shell._buffer.join('')
this.historyIndex = this.history.length - 1
} else if (this.historyIndex > 0) {
this.historyIndex -= 1
} else return
this.shell._SetBuffer(this.history[this.historyIndex])
return
}
if (this.historyIndex === null)
return
if (this.historyIndex < this.history.length - 1) {
this.historyIndex += 1
this.shell._SetBuffer(this.history[this.historyIndex])
return
}
this.historyIndex = null
this.shell._SetBuffer(this.historyDraft)
}
private ExitHistoryNavigation() {
this.historyIndex = null
this.historyDraft = ''
}
//
// -> keyboard management
//
/**
* Checks if the modifier includes every key of the combo
* @param combo modifier combo to check for
* @returns boolean according to the check truthfullness
*/
static HasModifierCombo(modifiers: ModifierKey[], combo: ModifierKey[]) {
let result = true
// check if the modifier buffer has every key in the combo
combo.forEach(key => {
if (!modifiers.includes(key)) {
result = false
return
}
})
return result
}
/**
* Gets a ModifierKey using a key id from KeyboardEvent
* @param key key from KeyboardEvent
* @returns a ModifierKey string if the provided key is valid, null otherwise
*/
static GetModifierKeyFromKey(key: string): ModifierKey | null {
switch (key) {
case 'Control':
return 'ctrl'
case 'Shift':
return 'shift'
case 'Alt':
return 'alt'
case 'AltGraph':
return 'rightAlt'
default:
return null
}
}
/**
* Registers keyboard listeners
*/
RegisterEvents() {
// also check for unfocus events as the modifier keys may be pressed when the window loses focus
window.addEventListener('blur', () => {
this.modifierKeys = []
})
this.keyEventBroadcaster.on('keyup', (key: string, isCharacter: boolean) => {
// deregister a modifier key as pressed
if (!isCharacter) {
const mod = InputManager.GetModifierKeyFromKey(key)
if (mod && this.modifierKeys.includes(mod))
this.modifierKeys = this.modifierKeys.filter(k => k !== mod)
}
})
this.keyEventBroadcaster.on('keydown', (key: string, isCharacter: boolean) => {
// register a modifier key as pressed
if (!isCharacter && !this.modifierKeys.includes(InputManager.GetModifierKeyFromKey(key)!)) {
const mod = InputManager.GetModifierKeyFromKey(key)
if (mod) this.modifierKeys.push(mod)
}
this.HandleKeyInput(key, isCharacter)
})
}
HandleKeyInput(key: string, isCharacter: boolean) {
// handle special input
switch (key.toUpperCase()) {
case 'C':
if (InputManager.HasModifierCombo(this.modifierKeys, ['ctrl'])) {
document.execCommand('copy')
return
}
break
case 'R':
if (InputManager.HasModifierCombo(this.modifierKeys, ['ctrl'])) {
location.reload()
return
}
break
case 'F5':
if (InputManager.HasModifierCombo(this.modifierKeys, ['alt'])) {
location.reload()
return
}
break
}
// redirect input to a running program instead
if (this.shell.HasRunningProgram()) {
this.shell.WriteStdin(key)
return
}
// handle standard keys
if (!isCharacter) {
switch (key) {
case 'ArrowLeft':
if (this.shell._bufferPos > 0) {
this.shell._bufferPos -= 1
this.shell._SyncCursorToBuffer()
}
break
case 'ArrowRight':
if (this.shell._bufferPos < this.shell._buffer.length) {
this.shell._bufferPos += 1
this.shell._SyncCursorToBuffer()
}
break
case 'ArrowUp':
this.NavigateHistory(-1)
break
case 'ArrowDown':
this.NavigateHistory(1)
break
case 'Backspace':
// don't erase anything if there's nothing left in the buffer
if (this.shell._bufferPos === 0)
break
this.ExitHistoryNavigation()
this.shell.terminal.RemoveCell()
this.shell.RemoveCharFromBuffer(1, this.shell._bufferPos)
this.shell._SyncCursorToBuffer()
break
case 'Delete':
if (this.shell._bufferPos >= this.shell._buffer.length || this.shell._buffer.length <= 0)
break
this.ExitHistoryNavigation()
this.shell._bufferPos += 1
this.shell._SyncCursorToBuffer()
this.shell.terminal.RemoveCell()
this.shell.RemoveCharFromBuffer(1, this.shell._bufferPos)
this.shell._SyncCursorToBuffer()
break
case 'Enter':
// send the buffer to stdin if an exec is running
if (this.shell.GetExecExitCode() === -1) {
this.shell.WriteStdin(`${this.shell._buffer.join('')}\n`)
this.shell.FlushBuffer()
} else {
// "execute" the buffer
this.shell.terminal.MoveCursor(0, 1, { x: true, y: false })
const command = this.shell._buffer.join('')
if (command.length > 0)
this.history.push(command)
this.historyIndex = null
this.historyDraft = ''
this.shell.ExecuteLineBuffer()
}
break
}
} else {
this.ExitHistoryNavigation()
// push the character into the buffer
this.shell._InsertText(key)
}
}
}

View File

@@ -0,0 +1,13 @@
/**
* Wush input parser
* Provides necessary parsing functions
*/
export class InputParser {
// static Tokenize(input: string) {
// }
// static Parse(tokens: string[]) {
// }
}

View File

@@ -1,21 +0,0 @@
/**
* Wush environment manager
* Manages environment variables, aliases etc.
*/
export class ShellEnvironment {
private variables: Record<string, string> = {}
SetVariable(name: string, value: string | null): void {
// remove the variable if value is null
if (value === null) {
delete this.variables[name]
return
}
this.variables[name] = value
}
GetVariable(name: string): string | undefined {
return this.variables[name]
}
}

View File

@@ -25,21 +25,24 @@ import { Mkdir } from '../../program/Mkdir'
import { Cd } from '../../program/Cd'
import { Printf } from '../../program/Printf'
import { Pwd } from '../../program/Pwd'
// import { Pwd } from '../program/Pwd'
// import { Cd } from '../program/Cd'
import { Environment } from './Environment'
import { InputManager } from './InputManager'
import { Edit } from '../../program/Edit'
import { Mv } from '../../program/Mv'
import { Tree } from '../../program/Tree'
import { Cp } from '../../program/Cp'
export class Wush extends Shell {
public readonly Version = "0.1.0"
public readonly Version = "0.3.2"
public readonly Name = "wush"
// buffer
private buffer: string[] = []
private bufferPos: number = 0
private promptStart: CursorPosition = { col: 0, row: 0 }
_buffer: string[] = []
_bufferPos: number = 0
_promptStart: CursorPosition = { col: 0, row: 0 }
private history: string[] = []
private historyIndex: number | null = null
private historyDraft: string = ''
private inputManager: InputManager
private environment: Environment
// exec stuff
/**
@@ -47,9 +50,6 @@ export class Wush extends Shell {
*/
private execExitCode: number = 0
// todo: workers
// private workersAllowed: boolean = false
// streams
readonly stdin: SimpleStream<string>
readonly stdout: SimpleStream<string>
@@ -63,16 +63,21 @@ export class Wush extends Shell {
// create streams
this.stdin = new SimpleStream<string>()
this.stdout = new SimpleStream<string>()
this.inputManager = new InputManager(this, broadcaster)
this.environment = new Environment()
}
async Init() {
this.broadcaster.on('keydown', (key: string, isCharacter: boolean) =>
this.HandleKeyInput(key, isCharacter),
)
// initialize keyboard listener
this.inputManager.RegisterEvents()
// load workdir
this.workingDirectory = await Item.Root()
// register streams
this.stdout.on(data => this.WriteEscapedString(data))
// load core programs
this.programs['clear'] = new Clear()
this.programs['eval'] = new Eval()
@@ -91,11 +96,27 @@ export class Wush extends Shell {
this.programs['pwd'] = new Pwd()
this.programs['cd'] = new Cd(this)
this.programs['printf'] = new Printf()
this.programs['edit'] = new Edit()
this.programs['mv'] = new Mv()
this.programs['cp'] = new Cp()
this.programs['tree'] = new Tree()
this.stdout.on(data => this.WriteEscapedString(data))
// reset exit code
this.SetExitCode(0)
// initial prompt
this.Prompt()
}
SetExitCode(code: number): void {
this.execExitCode = code
this.environment.SetVariable("status", code)
}
HasRunningProgram(): boolean {
return this.execExitCode === -1
}
GetPrograms(): { [name: string]: Program } {
return this.programs
}
@@ -108,11 +129,15 @@ export class Wush extends Shell {
delete this.programs[name]
}
GetExecExitCode(): number {
return this.execExitCode
}
async ExecuteProgram(name: string, args: string[]): Promise<void> {
return new Promise<void>(resolve => {
this.programs[name].Exec(this.stdin, this.stdout, this.workingDirectory, args)
.then(code => {
this.execExitCode = code != -1 ? code : -2
this.SetExitCode(code != -1 ? code : -2)
resolve()
})
.catch((e) => {
@@ -124,7 +149,7 @@ export class Wush extends Shell {
// check if the exec actually exited with an exit code
// and if not, set it to -2 to indicate that it didn't exit with a valid code
if (this.execExitCode === -1)
this.execExitCode = -2
this.SetExitCode(-2)
// this.terminal.Write(`The program exited with exit code ${this.execExitCode}.`)
resolve()
@@ -134,11 +159,12 @@ export class Wush extends Shell {
Prompt() {
this.terminal.Write(`user in ${this.workingDirectory.GetPath()} -> `)
this.promptStart = this.terminal.GetCursorPosition()
this.buffer = []
this.bufferPos = 0
this.historyIndex = null
this.historyDraft = ''
this._promptStart = this.terminal.GetCursorPosition()
this._buffer = []
this._bufferPos = 0
this.inputManager.historyIndex = null
this.inputManager.historyDraft = ''
}
/**
@@ -158,9 +184,9 @@ export class Wush extends Shell {
}
WriteEscapedString(data: string) {
let i = 0
let buffer = ''
// write the buffer to screen
const flush = () => {
if (buffer.length === 0)
return
@@ -169,11 +195,15 @@ export class Wush extends Shell {
buffer = ''
}
// process the string
let i = 0
while (i < data.length) {
const char = data[i]
// check for escape sequences
if (char === '\x1b') {
flush()
const nextIndex = this.ProcessEscapeSequence(data, i)
if (nextIndex !== null) {
i = nextIndex
@@ -181,10 +211,13 @@ export class Wush extends Shell {
}
}
// check for control codes
if (char === '\f' || char === '\n') {
flush()
this.ProcessSimpleControlCode(char)
this.ProcessControlCode(char)
i++
continue
}
@@ -197,57 +230,140 @@ export class Wush extends Shell {
PushToBuffer(text: string) {
text.split('').forEach(char => {
this.buffer.splice(this.bufferPos, 0, char)
this.bufferPos++
this._buffer.splice(this._bufferPos, 0, char)
this._bufferPos++
})
// console.log(this.buffer)
}
RemoveCharFromBuffer(amount: number, index: number) {
this.buffer.splice(index - amount, amount)
this.bufferPos -= amount
// console.log(this.buffer)
this._buffer.splice(index - amount, amount)
this._bufferPos -= amount
}
MoveBufferPos(index: number, absolute: boolean = false) {
this.bufferPos = Math.max(absolute ? index : this.bufferPos + index, 0)
this._bufferPos = Math.max(absolute ? index : this._bufferPos + index, 0)
}
FlushBuffer() {
this.buffer = []
this.bufferPos = 0
this._buffer = []
this._bufferPos = 0
}
async ExecuteBuffer() {
type OperatorToken = '&&' | '||' | '|' | ';'
/**
* Takes the prompt buffer, parses it and executes the contents
*/
async ExecuteLineBuffer(data?: string) {
type OperatorToken = '&&' | '||' | '|' | ';' | '>' | '>>' | '<'
type Token = { type: 'word'; value: string } | { type: 'operator'; value: OperatorToken }
type ParsedCommand = {
args: string[]
stdin: null | SimpleStream<string>
stdout: null | SimpleStream<string>
stdinPath: string | null
stdoutPath: string | null
stdoutAppend: boolean
}
type ParsedPipeline = { commands: ParsedCommand[] }
type ParsedListItem = { pipeline: ParsedPipeline; operator: '&&' | '||' | ';' | null }
// environment variable helpers
/**
* @returns value of the variable, empty string otherwise
*/
const resolveVariable = (name: string): string => this.environment.GetVariable(name) ?? ''
const isValidVarNameChar = (char: string) => /[A-Za-z0-9_]/.test(char)
/**
* splits the buffer into smaller processable pieces (tokens)
*/
const tokenize = (text: string): { tokens: Token[]; error: string | null } => {
const tokens: Token[] = []
// state machine stuff
let current = ''
let wordStarted = false
let inSingleQuote = false
let inDoubleQuote = false
let escapeNext = false
/**
* adds a new plain string to the token buffer
*/
const pushWord = () => {
if (!wordStarted)
return
tokens.push({ type: 'word', value: current })
// reset the state
current = ''
wordStarted = false
}
// reads environment variable tokens
const readVariable = (index: number): {
value: string
nextIndex: number
error: string | null
expanded: boolean
} => {
if (index + 1 >= text.length)
return { value: '$', nextIndex: index, error: null, expanded: false }
const next = text[index + 1]
if (next === '{') {
let end = index + 2
while (end < text.length && text[end] !== '}')
end++
if (end >= text.length)
return { value: '', nextIndex: text.length - 1, error: 'unterminated variable expansion', expanded: true }
const name = text.slice(index + 2, end)
if (name.length === 0)
return { value: '', nextIndex: end, error: 'empty variable name', expanded: true }
return { value: resolveVariable(name), nextIndex: end, error: null, expanded: true }
}
if (isValidVarNameChar(next)) {
let end = index + 1
while (end + 1 < text.length && isValidVarNameChar(text[end + 1]))
end++
const name = text.slice(index + 1, end + 1)
return { value: resolveVariable(name), nextIndex: end, error: null, expanded: true }
}
return { value: '$', nextIndex: index, error: null, expanded: false }
}
const appendExpandedValue = (value: string, split: boolean, preserveEmpty: boolean) => {
if (value.length === 0) {
if (preserveEmpty)
wordStarted = true
return
}
if (!split) {
current += value
wordStarted = true
return
}
for (const char of value) {
if (char === ' ' || char === '\t') {
pushWord()
continue
}
current += char
wordStarted = true
}
}
// iterates over the provided text buffer
for (let i = 0; i < text.length; i++) {
const char = text[i]
@@ -258,6 +374,7 @@ export class Wush extends Shell {
continue
}
// process strict (single quote) strings
if (inSingleQuote) {
if (char === "'") {
inSingleQuote = false
@@ -270,6 +387,7 @@ export class Wush extends Shell {
continue
}
// process classic (double quote) strings
if (inDoubleQuote) {
if (char === '"') {
inDoubleQuote = false
@@ -281,6 +399,18 @@ export class Wush extends Shell {
current += text[i + 1]
i++
wordStarted = true
} else if (char === '$') {
const { value, nextIndex, error, expanded } = readVariable(i)
if (error)
return { tokens: [], error }
if (expanded) {
appendExpandedValue(value, false, true)
i = nextIndex
} else {
current += char
wordStarted = true
}
} else {
current += char
wordStarted = true
@@ -289,24 +419,45 @@ export class Wush extends Shell {
continue
}
// state checks
// escapes
if (char === '\\') {
escapeNext = true
wordStarted = true
continue
}
// single quote strings
if (char === "'") {
inSingleQuote = true
wordStarted = true
continue
}
// double quote strings
if (char === '"') {
inDoubleQuote = true
wordStarted = true
continue
}
if (char === '$') {
const { value, nextIndex, error, expanded } = readVariable(i)
if (error)
return { tokens: [], error }
if (expanded) {
appendExpandedValue(value, true, false)
i = nextIndex
} else {
current += char
wordStarted = true
}
continue
}
if (char === ' ' || char === '\t') {
pushWord()
continue
@@ -327,6 +478,23 @@ export class Wush extends Shell {
continue
}
if (char === '>') {
pushWord()
if (text[i + 1] === '>') {
tokens.push({ type: 'operator', value: '>>' })
i++
} else {
tokens.push({ type: 'operator', value: '>' })
}
continue
}
if (char === '<') {
pushWord()
tokens.push({ type: 'operator', value: '<' })
continue
}
if (char === '|') {
pushWord()
if (text[i + 1] === '|') {
@@ -365,11 +533,16 @@ export class Wush extends Shell {
return { tokens, error: null }
}
// parse the tokens into a list of parsed commands and pipelines
const parseTokens = (tokens: Token[]): { list: ParsedListItem[]; error: string | null } => {
const list: ParsedListItem[] = []
let currentArgs: string[] = []
let currentPipeline: ParsedCommand[] = []
let expectCommand = false
let expectRedirect: 'stdin' | 'stdout' | 'append' | null = null
let currentStdinPath: string | null = null
let currentStdoutPath: string | null = null
let currentStdoutAppend = false
const pushCommand = () => {
if (currentArgs.length === 0)
@@ -379,8 +552,14 @@ export class Wush extends Shell {
args: currentArgs,
stdin: null,
stdout: null,
stdinPath: currentStdinPath,
stdoutPath: currentStdoutPath,
stdoutAppend: currentStdoutAppend,
})
currentArgs = []
currentStdinPath = null
currentStdoutPath = null
currentStdoutAppend = false
return true
}
@@ -395,12 +574,43 @@ export class Wush extends Shell {
for (const token of tokens) {
if (token.type === 'word') {
if (expectRedirect) {
if (expectRedirect === 'stdin') {
currentStdinPath = token.value
} else {
currentStdoutPath = token.value
currentStdoutAppend = expectRedirect === 'append'
}
expectRedirect = null
expectCommand = false
continue
}
currentArgs.push(token.value)
expectCommand = false
continue
}
if (expectRedirect)
return { list: [], error: 'expected redirection target' }
if (token.value === '>' || token.value === '>>' || token.value === '<') {
if (currentArgs.length === 0)
return { list: [], error: `unexpected "${token.value}" operator` }
expectRedirect = token.value === '<'
? 'stdin'
: token.value === '>>'
? 'append'
: 'stdout'
continue
}
if (token.value === '|') {
if (currentStdoutPath)
return { list: [], error: 'unexpected "|" operator after redirection' }
if (!pushCommand())
return { list: [], error: 'unexpected "|" operator' }
@@ -417,6 +627,9 @@ export class Wush extends Shell {
if (expectCommand)
return { list: [], error: 'unexpected end of input' }
if (expectRedirect)
return { list: [], error: 'expected redirection target' }
if (currentArgs.length > 0)
pushCommand()
@@ -426,8 +639,18 @@ export class Wush extends Shell {
return { list, error: null }
}
const line = this.buffer.join('')
this.FlushBuffer()
// process the buffer
let line: string
if (data) {
// data overrides the buffer
this._buffer = data.split('')
this._bufferPos = 0
line = data
} else {
// use shell buffer if no arbitrary string was provided
line = this._buffer.join('')
this.FlushBuffer()
}
const { tokens, error } = tokenize(line)
if (error) {
@@ -452,38 +675,176 @@ export class Wush extends Shell {
return
}
if (list.some(item => item.pipeline.commands.length > 1)) {
this.terminal.Write(`wush: error: pipes are not supported yet`)
this.terminal.MoveCursor(0, 1, { x: true, y: false })
const resolvePath = (path: string) => Item.NormalizePath(
path.startsWith('/') ? path : `${this.workingDirectory.GetPath()}/${path}`
)
this.Prompt()
return
const openInputRedirect = async (path: string) => {
const resolved = resolvePath(path)
const item = await Item.open(resolved)
if (!(await item.Exists()))
throw new Error(`input file ${resolved} doesn't exist`)
if (item.IsDirectory())
throw new Error(`input file ${resolved} is a directory`)
return { stream: new SimpleStream<string>(), data: item.GetData() ?? '' }
}
const openOutputRedirect = async (path: string, append: boolean) => {
const resolved = resolvePath(path)
const item = await Item.open(resolved)
if (!(await item.Exists()))
await item.Create()
if (item.IsDirectory())
throw new Error(`output path ${resolved} is a directory`)
if (!append)
await item.Write('')
const stream = new SimpleStream<string>()
let writeQueue = Promise.resolve()
const listener = (data: string) => {
writeQueue = writeQueue.then(() => item.Append(data))
}
stream.on(listener)
return {
stream,
finish: () => writeQueue,
teardown: () => stream.off(listener),
}
}
const setupPipelineStreams = async (pipeline: ParsedPipeline) => {
const teardown: Array<() => void> = []
const stdins: SimpleStream<string>[] = []
const stdouts: SimpleStream<string>[] = []
const finishers: Array<() => Promise<void>> = []
const inputFeeds: Array<{ stream: SimpleStream<string>; data: string }> = []
try {
for (const [index, command] of pipeline.commands.entries()) {
let stdin: SimpleStream<string>
let stdout: SimpleStream<string>
if (command.stdinPath) {
if (index !== 0)
throw new Error('input redirection is only supported on the first command in a pipeline')
const { stream, data } = await openInputRedirect(command.stdinPath)
stdin = stream
inputFeeds.push({ stream, data })
} else {
stdin = index === 0 ? this.stdin : new SimpleStream<string>()
}
if (command.stdoutPath) {
if (index !== pipeline.commands.length - 1)
throw new Error('output redirection is only supported on the last command in a pipeline')
const { stream, finish, teardown: remove } = await openOutputRedirect(
command.stdoutPath,
command.stdoutAppend
)
stdout = stream
finishers.push(finish)
teardown.push(remove)
} else {
stdout = index === pipeline.commands.length - 1 ? this.stdout : new SimpleStream<string>()
}
command.stdin = stdin
command.stdout = stdout
stdins.push(stdin)
stdouts.push(stdout)
}
for (let i = 0; i < pipeline.commands.length - 1; i++) {
if (pipeline.commands[i].stdoutPath)
throw new Error('cannot pipe a command with output redirection')
if (pipeline.commands[i + 1].stdinPath)
throw new Error('cannot pipe into a command with input redirection')
const listener = (data: string) => stdins[i + 1].emit(data)
stdouts[i].on(listener)
teardown.push(() => stdouts[i].off(listener))
}
return { stdins, stdouts, teardown, finishers, inputFeeds }
} catch (e) {
teardown.forEach(remove => remove())
throw e
}
}
const executePipeline = async (pipeline: ParsedPipeline): Promise<number> => {
const missing = pipeline.commands.find(command => !(this.programs[command.args[0]] instanceof Program))
if (missing) {
const name = missing.args[0]
if (name.length !== 0) {
this.terminal.Write(`wush: error: unknown command: ${name}.`)
this.terminal.MoveCursor(0, 1, { x: true, y: false })
return 127
}
return 0
}
let setup: Awaited<ReturnType<typeof setupPipelineStreams>>
try {
setup = await setupPipelineStreams(pipeline)
} catch (e) {
const message = e instanceof Error ? e.message : String(e)
this.terminal.Write(`wush: error: ${message}`)
this.terminal.MoveCursor(0, 1, { x: true, y: false })
return 1
}
try {
const exitCodes = await Promise.all(pipeline.commands.map(async (command, index) => {
try {
return await this.programs[command.args[0]].Exec(
setup.stdins[index],
setup.stdouts[index],
this.workingDirectory,
command.args
)
} catch (e) {
this.WriteEscapedString(`wush: command ${command.args[0]} exited with the following exception\n`)
this.WriteEscapedString(` | ${String(e)}\n`)
return -2
}
}))
setup.inputFeeds.forEach(feed => {
queueMicrotask(() => feed.stream.emit(feed.data))
})
await Promise.all(setup.finishers.map(finish => finish()))
const lastExitCode = exitCodes[exitCodes.length - 1]
return lastExitCode !== -1 ? lastExitCode : -2
} finally {
setup.teardown.forEach(remove => remove())
}
}
for (const item of list) {
const command = item.pipeline.commands[0]
this.execExitCode = -1
if (this.programs[command.args[0]] instanceof Program) {
await this.ExecuteProgram(command.args[0], command.args)
} else {
this.execExitCode = 0
// don't print anything if there are no arguments
if (command.args[0].length !== 0) {
this.terminal.Write(`wush: error: unknown command: ${command.args[0]}.`)
this.terminal.MoveCursor(0, 1, { x: true, y: false })
this.execExitCode = 127
}
}
this.SetExitCode(-1)
this.SetExitCode(await executePipeline(item.pipeline))
}
this.Prompt()
}
ProcessSimpleControlCode(code: string): boolean {
ProcessControlCode(code: string): boolean {
switch (code) {
case '\f':
this.terminal.NewPage()
@@ -537,84 +898,14 @@ export class Wush extends Shell {
this.terminal.NewPage()
return true
}
case 'm': {
this.terminal.ApplyCellStyleCodes(values)
return true
}
default:
return false
}
}
HandleKeyInput(key: string, isCharacter: boolean) {
if (this.execExitCode === -1) console.log('program running')
if (!isCharacter) {
switch (key) {
case 'ArrowLeft':
if (this.bufferPos > 0) {
this.bufferPos -= 1
this.SyncCursorToBuffer()
}
break
case 'ArrowRight':
if (this.bufferPos < this.buffer.length) {
this.bufferPos += 1
this.SyncCursorToBuffer()
}
break
case 'ArrowUp':
this.NavigateHistory(-1)
break
case 'ArrowDown':
this.NavigateHistory(1)
break
case 'Backspace':
// don't erase anything if there's nothing left in the buffer
if (this.bufferPos === 0)
break
this.ExitHistoryNavigation()
this.terminal.RemoveCell()
this.RemoveCharFromBuffer(1, this.bufferPos)
this.SyncCursorToBuffer()
break
case 'Delete':
if (this.bufferPos >= this.buffer.length || this.buffer.length <= 0)
break
this.ExitHistoryNavigation()
this.bufferPos += 1
this.SyncCursorToBuffer()
this.terminal.RemoveCell()
this.RemoveCharFromBuffer(1, this.bufferPos)
this.SyncCursorToBuffer()
break
case 'Enter':
// send the buffer to stdin if an exec is running
if (this.execExitCode === -1) {
this.WriteStdin(`${this.buffer.join('')}\n`)
this.FlushBuffer()
} else {
// "execute" the buffer
this.terminal.MoveCursor(0, 1, { x: true, y: false })
const command = this.buffer.join('')
if (command.length > 0)
this.history.push(command)
this.historyIndex = null
this.historyDraft = ''
this.ExecuteBuffer()
}
break
case 'F5':
location.reload()
break
}
} else {
this.ExitHistoryNavigation()
// push the character into the buffer
this.InsertText(key)
}
}
private GetWrapWidth(): number {
const width = Math.floor(this.terminal.GetWidthCells())
if (!Number.isFinite(width) || width <= 0)
@@ -625,83 +916,47 @@ export class Wush extends Shell {
private GetCursorPositionForBufferPos(pos: number): CursorPosition {
const width = this.GetWrapWidth()
const absoluteIndex = this.promptStart.col + Math.max(pos, 0)
const absoluteIndex = this._promptStart.col + Math.max(pos, 0)
const rowOffset = Math.floor(absoluteIndex / width)
const col = absoluteIndex % width
return { row: this.promptStart.row + rowOffset, col }
return { row: this._promptStart.row + rowOffset, col }
}
private SyncCursorToBuffer() {
const position = this.GetCursorPositionForBufferPos(this.bufferPos)
_SyncCursorToBuffer() {
const position = this.GetCursorPositionForBufferPos(this._bufferPos)
this.terminal.SetCursorPosition(position.col, position.row)
}
private ClearBuffer() {
if (this.buffer.length === 0)
if (this._buffer.length === 0)
return
if (this.bufferPos < this.buffer.length) {
this.bufferPos = this.buffer.length
this.SyncCursorToBuffer()
if (this._bufferPos < this._buffer.length) {
this._bufferPos = this._buffer.length
this._SyncCursorToBuffer()
}
while (this.bufferPos > 0) {
while (this._bufferPos > 0) {
this.terminal.RemoveCell()
this.RemoveCharFromBuffer(1, this.bufferPos)
this.SyncCursorToBuffer()
this.RemoveCharFromBuffer(1, this._bufferPos)
this._SyncCursorToBuffer()
}
}
private InsertText(text: string) {
_InsertText(text: string) {
if (text.length === 0)
return
for (const char of text) {
this.terminal.InsertCell(char)
this.PushToBuffer(char)
this.SyncCursorToBuffer()
this._SyncCursorToBuffer()
}
}
private SetBuffer(text: string) {
_SetBuffer(text: string) {
this.ClearBuffer()
this.InsertText(text)
}
private ExitHistoryNavigation() {
this.historyIndex = null
this.historyDraft = ''
}
private NavigateHistory(direction: -1 | 1) {
if (this.history.length === 0)
return
if (direction === -1) {
if (this.historyIndex === null) {
this.historyDraft = this.buffer.join('')
this.historyIndex = this.history.length - 1
} else if (this.historyIndex > 0) {
this.historyIndex -= 1
} else {
return
}
this.SetBuffer(this.history[this.historyIndex])
return
}
if (this.historyIndex === null)
return
if (this.historyIndex < this.history.length - 1) {
this.historyIndex += 1
this.SetBuffer(this.history[this.historyIndex])
return
}
this.historyIndex = null
this.SetBuffer(this.historyDraft)
this._InsertText(text)
}
}

View File

@@ -5,7 +5,25 @@ import sqs from '../utils/sqs'
import type { CursorPosition, CursorStyle } from './CursorProperties'
export class Terminal {
public static readonly Version = "0.1.1"
public static readonly Version = "0.2.2"
private static readonly AnsiColors = [
'#000000',
'#800000',
'#008000',
'#808000',
'#000080',
'#800080',
'#008080',
'#ffffff',
'#808080',
'#ff0000',
'#00ff00',
'#ffff00',
'#0000ff',
'#ff00ff',
'#00ffff',
'#ffffff',
]
private terminal: HTMLElement
private cursor: HTMLElement
@@ -15,6 +33,10 @@ export class Terminal {
private lines: string[] = []
private lineElements: HTMLElement[] = []
private lineWrapped: boolean[] = []
private lineStyles: Map<number, Map<number, string>> = new Map()
private currentForeground: string | null = null
private currentBackground: string | null = null
private currentCellStyle: string | null = null
private scrollPending = false
private cursorRange: Range | null = null
@@ -34,7 +56,7 @@ export class Terminal {
this.SetCursorStyle('bar')
this.NewPage()
this.SetupMetricsRefresh()
this.CreateMetricsRefreshListener()
}
async LoadShell(shell: Shell) {
@@ -53,6 +75,7 @@ export class Terminal {
this.lines = []
this.lineElements = []
this.lineWrapped = []
this.lineStyles.clear()
this.SetCursorPosition(0, 0)
}
@@ -74,6 +97,7 @@ export class Terminal {
const width = this.GetWrapWidth()
let row = this.cursorPosition.row
let col = this.cursorPosition.col
const style = this.currentCellStyle
while (col >= width) {
this.EnsureLine(row)
@@ -110,6 +134,7 @@ export class Terminal {
}
this.lines[row] = line
this.ApplyStyleRange(row, col, chunk.length, style)
this.UpdateLine(row)
remaining = remaining.slice(chunk.length)
@@ -155,9 +180,146 @@ export class Terminal {
}
this.lines[row] = line
this.ApplyStyleRange(row, col, 1, this.currentCellStyle)
this.UpdateLine(row)
}
SetCellStyle(col: number, row: number, style: string | null) {
if (!Number.isFinite(col) || !Number.isFinite(row))
return
const targetRow = Math.max(0, Math.floor(row))
const targetCol = Math.max(0, Math.floor(col))
const width = this.GetWrapWidth()
if (targetCol >= width)
return
this.EnsureLine(targetRow)
let line = this.lines[targetRow] ?? ''
if (targetCol >= line.length) {
line += ' '.repeat(targetCol - line.length + 1)
this.lines[targetRow] = line
}
const cssText = style?.trim()
if (cssText) {
let rowStyles = this.lineStyles.get(targetRow)
if (!rowStyles) {
rowStyles = new Map()
this.lineStyles.set(targetRow, rowStyles)
}
rowStyles.set(targetCol, cssText)
} else {
const rowStyles = this.lineStyles.get(targetRow)
if (rowStyles) {
rowStyles.delete(targetCol)
if (rowStyles.size === 0)
this.lineStyles.delete(targetRow)
}
}
this.UpdateLine(targetRow)
this.UpdateCursor()
}
ApplyCellStyleCodes(values: number[]) {
const params = values.length === 0 ? [0] : values
let foreground = this.currentForeground
let background = this.currentBackground
let i = 0
while (i < params.length) {
const code = params[i]
if (!Number.isFinite(code)) {
i += 1
continue
}
if (code === 0) {
foreground = null
background = null
i += 1
continue
}
if (code === 39) {
foreground = null
i += 1
continue
}
if (code === 49) {
background = null
i += 1
continue
}
if (code >= 30 && code <= 37) {
foreground = Terminal.AnsiColors[code - 30]
i += 1
continue
}
if (code >= 90 && code <= 97) {
foreground = Terminal.AnsiColors[code - 90 + 8]
i += 1
continue
}
if (code >= 40 && code <= 47) {
background = Terminal.AnsiColors[code - 40]
i += 1
continue
}
if (code >= 100 && code <= 107) {
background = Terminal.AnsiColors[code - 100 + 8]
i += 1
continue
}
if (code === 38 || code === 48) {
const isForeground = code === 38
const mode = params[i + 1]
if (mode === 2) {
const red = params[i + 2]
const green = params[i + 3]
const blue = params[i + 4]
if (Number.isFinite(red) && Number.isFinite(green) && Number.isFinite(blue)) {
const color = Terminal.ToRgbColor(red, green, blue)
if (isForeground)
foreground = color
else
background = color
}
i += 5
continue
}
if (mode === 5) {
const index = params[i + 2]
const color = Terminal.GetAnsi256Color(index)
if (color) {
if (isForeground)
foreground = color
else
background = color
}
i += 3
continue
}
}
i += 1
}
this.currentForeground = foreground
this.currentBackground = background
this.UpdateCurrentStyle()
}
InsertCell(char: string) {
const width = this.GetWrapWidth()
let row = this.cursorPosition.row
@@ -178,6 +340,7 @@ export class Terminal {
line = line.slice(0, col) + char[0] + line.slice(col)
this.lines[row] = line
this.ApplyInsertStyle(row, col, this.currentCellStyle)
this.UpdateLine(row)
this.ReflowFromRow(row)
}
@@ -203,12 +366,13 @@ export class Terminal {
line = line.slice(0, removeIndex) + line.slice(removeIndex + 1)
this.lines[row] = line
this.ApplyRemoveStyle(row, removeIndex)
this.UpdateLine(row)
this.ReflowFromRow(row)
}
ResetCellSize() {
// dynamically determine cell size using dom
// dynamically determine cell size with dom
const cell = document.createElement('span')
cell.textContent = 'A'
cell.style.position = 'absolute'
@@ -328,8 +492,61 @@ export class Terminal {
private UpdateLine(row: number) {
const line = this.lineElements[row]
if (line)
line.textContent = this.lines[row]
if (!line)
return
const text = this.lines[row] ?? ''
const styles = this.lineStyles.get(row)
if (!styles || styles.size === 0) {
line.textContent = text
return
}
for (const col of Array.from(styles.keys())) {
if (col < 0 || col >= text.length)
styles.delete(col)
}
if (styles.size === 0) {
this.lineStyles.delete(row)
line.textContent = text
return
}
const sorted = Array.from(styles.entries()).sort((a, b) => a[0] - b[0])
const fragment = document.createDocumentFragment()
let cursor = 0
let index = 0
while (index < sorted.length) {
const [col, style] = sorted[index]
if (col > cursor)
fragment.append(document.createTextNode(text.slice(cursor, col)))
let runStart = col
let runEnd = col
while (index + 1 < sorted.length) {
const [nextCol, nextStyle] = sorted[index + 1]
if (nextCol !== runEnd + 1 || nextStyle !== style)
break
index += 1
runEnd = nextCol
}
const span = document.createElement('span')
span.textContent = text.slice(runStart, runEnd + 1)
span.style.cssText = style
fragment.append(span)
cursor = runEnd + 1
index += 1
}
if (cursor < text.length)
fragment.append(document.createTextNode(text.slice(cursor)))
line.replaceChildren(fragment)
}
private ReflowFromRow(startRow: number) {
@@ -350,19 +567,35 @@ export class Terminal {
text += this.lines[endRow] ?? ''
}
const lineLengths: number[] = []
for (let row = startRow; row <= endRow; row++)
lineLengths.push((this.lines[row] ?? '').length)
const styledIndexes = new Map<number, string>()
let styleOffset = 0
for (let row = startRow; row <= endRow; row++) {
const rowStyles = this.lineStyles.get(row)
const rowLength = lineLengths[row - startRow]
if (rowStyles && rowLength > 0) {
for (const [col, style] of rowStyles) {
if (col >= 0 && col < rowLength)
styledIndexes.set(styleOffset + col, style)
}
}
styleOffset += rowLength
}
let row = startRow
let index = 0
if (text.length === 0) {
this.lines[row] = ''
this.UpdateLine(row)
this.lineWrapped[row] = false
row += 1
} else {
while (index < text.length) {
const chunk = text.slice(index, index + width)
this.lines[row] = chunk
this.UpdateLine(row)
this.lineWrapped[row] = index + width < text.length
row += 1
@@ -373,13 +606,147 @@ export class Terminal {
}
}
const newLastRow = text.length > 0 ? startRow + Math.floor((text.length - 1) / width) : startRow
const clearEnd = Math.max(endRow, newLastRow)
for (let clearRow = startRow; clearRow <= clearEnd; clearRow++)
this.lineStyles.delete(clearRow)
if (styledIndexes.size > 0) {
for (const [styleIndex, style] of styledIndexes) {
const targetRow = startRow + Math.floor(styleIndex / width)
const targetCol = styleIndex % width
let rowStyles = this.lineStyles.get(targetRow)
if (!rowStyles) {
rowStyles = new Map()
this.lineStyles.set(targetRow, rowStyles)
}
rowStyles.set(targetCol, style)
}
}
for (let i = row; i <= endRow; i++) {
if (this.lines[i] !== '' || this.lineWrapped[i]) {
this.lines[i] = ''
this.UpdateLine(i)
this.lineWrapped[i] = false
}
}
const renderEnd = Math.max(endRow, newLastRow)
for (let renderRow = startRow; renderRow <= renderEnd; renderRow++)
this.UpdateLine(renderRow)
}
private UpdateCurrentStyle() {
const styles: string[] = []
if (this.currentForeground)
styles.push(`color: ${this.currentForeground}`)
if (this.currentBackground)
styles.push(`background-color: ${this.currentBackground}`)
this.currentCellStyle = styles.length > 0 ? styles.join('; ') : null
}
private ApplyStyleRange(row: number, startCol: number, length: number, style: string | null) {
if (!Number.isFinite(row) || !Number.isFinite(startCol) || length <= 0)
return
let rowStyles = this.lineStyles.get(row)
if (!rowStyles && !style)
return
if (!rowStyles) {
rowStyles = new Map()
this.lineStyles.set(row, rowStyles)
}
const start = Math.max(0, Math.floor(startCol))
const end = start + Math.max(0, Math.floor(length))
for (let col = start; col < end; col++) {
if (style)
rowStyles.set(col, style)
else
rowStyles.delete(col)
}
if (rowStyles.size === 0)
this.lineStyles.delete(row)
}
private ApplyInsertStyle(row: number, col: number, style: string | null) {
const rowStyles = this.lineStyles.get(row)
if (!rowStyles && !style)
return
const updated = new Map<number, string>()
if (rowStyles) {
for (const [index, cssText] of rowStyles) {
if (index >= col)
updated.set(index + 1, cssText)
else
updated.set(index, cssText)
}
}
if (style)
updated.set(col, style)
if (updated.size > 0)
this.lineStyles.set(row, updated)
else
this.lineStyles.delete(row)
}
private ApplyRemoveStyle(row: number, col: number) {
const rowStyles = this.lineStyles.get(row)
if (!rowStyles)
return
const updated = new Map<number, string>()
for (const [index, cssText] of rowStyles) {
if (index === col)
continue
if (index > col)
updated.set(index - 1, cssText)
else
updated.set(index, cssText)
}
if (updated.size > 0)
this.lineStyles.set(row, updated)
else
this.lineStyles.delete(row)
}
private static ToRgbColor(red: number, green: number, blue: number): string {
const clamp = (value: number) => Math.min(255, Math.max(0, Math.round(value)))
const r = clamp(red)
const g = clamp(green)
const b = clamp(blue)
return `rgb(${r}, ${g}, ${b})`
}
private static GetAnsi256Color(code: number): string | null {
if (!Number.isFinite(code))
return null
const index = Math.floor(code)
if (index < 0 || index > 255)
return null
if (index < 16)
return Terminal.AnsiColors[index]
if (index <= 231) {
const offset = index - 16
const r = Math.floor(offset / 36)
const g = Math.floor((offset % 36) / 6)
const b = offset % 6
const levels = [0, 95, 135, 175, 215, 255]
return `rgb(${levels[r]}, ${levels[g]}, ${levels[b]})`
}
const grayscale = 8 + (index - 232) * 10
return `rgb(${grayscale}, ${grayscale}, ${grayscale})`
}
private GetCursorXOffset(): number {
@@ -395,23 +762,55 @@ export class Terminal {
const clamped = Math.min(col, textLength)
let width = 0
const textNode = line.firstChild
if (textNode && textNode.nodeType === Node.TEXT_NODE && clamped > 0) {
const hasSingleTextNode = line.childNodes.length === 1 && line.firstChild?.nodeType === Node.TEXT_NODE
if (clamped > 0) {
if (clamped === textLength) {
width = line.getBoundingClientRect().width
} else if (this.cursorRange) {
this.cursorRange.setStart(textNode, 0)
this.cursorRange.setEnd(textNode, clamped)
width = this.cursorRange.getBoundingClientRect().width
if (hasSingleTextNode) {
const textNode = line.firstChild as Text
this.cursorRange.setStart(textNode, 0)
this.cursorRange.setEnd(textNode, clamped)
width = this.cursorRange.getBoundingClientRect().width
} else {
const target = this.FindTextNodeAtOffset(line, clamped)
if (target) {
this.cursorRange.setStart(line, 0)
this.cursorRange.setEnd(target.node, target.offset)
width = this.cursorRange.getBoundingClientRect().width
}
}
}
}
if (clamped > 0 && width === 0)
width = clamped * this.cellWidth
if (col > textLength)
width += (col - textLength) * this.cellWidth
return width
}
private FindTextNodeAtOffset(root: HTMLElement, offset: number): { node: Text; offset: number } | null {
if (offset <= 0)
return null
const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT)
let remaining = offset
let node = walker.nextNode() as Text | null
while (node) {
const length = node.data.length
if (remaining <= length)
return { node, offset: remaining }
remaining -= length
node = walker.nextNode() as Text | null
}
return null
}
private RefreshMetrics() {
this.ResetCellSize()
this.lineElements.forEach(line => {
@@ -420,7 +819,7 @@ export class Terminal {
this.UpdateCursor()
}
private SetupMetricsRefresh() {
private CreateMetricsRefreshListener() {
if ('fonts' in document) {
document.fonts.ready.then(() => {
this.RefreshMetrics()