Compare commits
16 Commits
b5f53473ed
...
schpr
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
085cec8dc0 | ||
|
|
071d4e3aa4 | ||
|
|
d76119918d | ||
|
|
3798a53395 | ||
|
|
4777552106 | ||
|
|
62038c2814 | ||
|
|
646a9f6b7a | ||
|
|
255cc6a858 | ||
|
|
e0269c9b6a | ||
|
|
0577ee49cf | ||
|
|
729c8a5fd1 | ||
|
|
0649843821 | ||
|
|
abe52acaa7 | ||
|
|
b5089251ff | ||
|
|
1d00cf6deb | ||
|
|
4a484dd546 |
@@ -34,7 +34,8 @@ Aplikace je zdarma hostovaná přes Vercel a je veřejně dostupná na adrese ht
|
|||||||
## testování
|
## testování
|
||||||
|
|
||||||
Aplikace je testována v následujících prohlížečích:
|
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
|
## licence
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"name": "webshell",
|
"name": "webshell",
|
||||||
"private": true,
|
"private": true,
|
||||||
"version": "0.0.0",
|
"version": "0.2.1",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "vite",
|
"dev": "vite",
|
||||||
|
|||||||
@@ -4,7 +4,8 @@ import { Wush } from './shell/wush/Wush'
|
|||||||
import { Terminal } from './terminal/Terminal'
|
import { Terminal } from './terminal/Terminal'
|
||||||
import { EventBroadcaster } from './utils/EventBroadcaster'
|
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 = "This branch is a part of a school project."
|
||||||
|
|
||||||
// initialize object store for webfs
|
// initialize object store for webfs
|
||||||
let WebfsDatabase: IDBDatabase | null = null
|
let WebfsDatabase: IDBDatabase | null = null
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ export class Item {
|
|||||||
private children: string[] = []
|
private children: string[] = []
|
||||||
|
|
||||||
private constructor(path: string) {
|
private constructor(path: string) {
|
||||||
this.path = this.normalizePath(path)
|
this.path = Item.NormalizePath(path)
|
||||||
}
|
}
|
||||||
|
|
||||||
// -------------------------------------------------------------------------
|
// -------------------------------------------------------------------------
|
||||||
@@ -126,6 +126,18 @@ export class Item {
|
|||||||
return this.isDirectory
|
return this.isDirectory
|
||||||
}
|
}
|
||||||
|
|
||||||
|
IsReadable(): boolean {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
IsWritable(): boolean {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
IsExecutable(): boolean {
|
||||||
|
return this.executable
|
||||||
|
}
|
||||||
|
|
||||||
async Append(data: string): Promise<void> {
|
async Append(data: string): Promise<void> {
|
||||||
if (!(await this.Exists())) throw new Error(`Cannot append to a file that has not been created: ${this.path}`)
|
if (!(await this.Exists())) throw new Error(`Cannot append to a file that has not been created: ${this.path}`)
|
||||||
if (this.isDirectory) throw new Error("Cannot append data to a directory")
|
if (this.isDirectory) throw new Error("Cannot append data to a directory")
|
||||||
@@ -160,7 +172,7 @@ export class Item {
|
|||||||
return this.path === '/' ? '/' : this.path.substring(this.path.lastIndexOf('/') + 1)
|
return this.path === '/' ? '/' : this.path.substring(this.path.lastIndexOf('/') + 1)
|
||||||
}
|
}
|
||||||
|
|
||||||
ReadData(): string | null {
|
GetData(): string | null {
|
||||||
return this.data
|
return this.data
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -181,6 +193,49 @@ export class Item {
|
|||||||
return items.filter((item): item is Item => item !== null)
|
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> {
|
async Delete(): Promise<void> {
|
||||||
if (!(await this.Exists())) return
|
if (!(await this.Exists())) return
|
||||||
|
|
||||||
@@ -210,7 +265,7 @@ export class Item {
|
|||||||
return this.path
|
return this.path
|
||||||
}
|
}
|
||||||
|
|
||||||
private normalizePath(path: string): string {
|
public static NormalizePath(path: string): string {
|
||||||
if (!path.startsWith('/')) path = '/' + path
|
if (!path.startsWith('/')) path = '/' + path
|
||||||
|
|
||||||
// Resolve . and .. segments.
|
// Resolve . and .. segments.
|
||||||
@@ -305,6 +360,7 @@ export class Item {
|
|||||||
this.data = parsed.data
|
this.data = parsed.data
|
||||||
this.children = parsed.children
|
this.children = parsed.children
|
||||||
}
|
}
|
||||||
|
|
||||||
resolve()
|
resolve()
|
||||||
}
|
}
|
||||||
request.onerror = () => reject(request.error)
|
request.onerror = () => reject(request.error)
|
||||||
|
|||||||
@@ -3,21 +3,29 @@ import type { SimpleStream } from '../utils/SimpleStream'
|
|||||||
import { Program } from './Program'
|
import { Program } from './Program'
|
||||||
|
|
||||||
export class Cat extends Program {
|
export class Cat extends Program {
|
||||||
async Exec(_: SimpleStream<string>, stdout: SimpleStream<string>, __: Item, args: string[]): Promise<number> {
|
async Exec(_: SimpleStream<string>, stdout: SimpleStream<string>, workdir: Item, args: string[]): Promise<number> {
|
||||||
let item: Item = await Item.open(args[1])
|
if (args.length < 2) {
|
||||||
|
stdout.emit("cat: error: missing path argument\n")
|
||||||
if (!(await item.Exists())) {
|
|
||||||
stdout.emit(`cat: error: item ${item.GetPath()} doesn't exist.\n`)
|
|
||||||
return 1
|
return 1
|
||||||
}
|
}
|
||||||
|
|
||||||
if (item.IsDirectory()) {
|
const path = Item.NormalizePath(args[1].startsWith('/') ? args[1] : `${workdir.GetPath()}/${args[1]}`)
|
||||||
stdout.emit(`cat: error: can't read data from a directory; item ${item.GetPath()} is a directory.\n`)
|
let item: Item
|
||||||
|
|
||||||
|
try {
|
||||||
|
item = await Item.open(path)
|
||||||
|
} catch (err) {
|
||||||
|
stdout.emit(`cat: error: item ${path} is a directory\n`)
|
||||||
return 2
|
return 2
|
||||||
}
|
}
|
||||||
|
|
||||||
stdout.emit(`${item.ReadData()}`)
|
if (!(await item.Exists())) {
|
||||||
stdout.emit('[ EOF ]\n')
|
stdout.emit(`cat: error: item ${item.GetPath()} doesn't exist.\n`)
|
||||||
|
return 3
|
||||||
|
}
|
||||||
|
|
||||||
|
stdout.emit(`${item.GetData()}`)
|
||||||
|
stdout.emit('\x1B[0;30m\x1B[47m EOF \x1B[0m\n')
|
||||||
|
|
||||||
return 0
|
return 0
|
||||||
}
|
}
|
||||||
|
|||||||
39
src/program/Cd.ts
Normal file
39
src/program/Cd.ts
Normal file
@@ -0,0 +1,39 @@
|
|||||||
|
import { Item } from '../fs/Item'
|
||||||
|
import type { Shell } from '../shell/Shell'
|
||||||
|
import type { SimpleStream } from '../utils/SimpleStream'
|
||||||
|
import { Program } from './Program'
|
||||||
|
|
||||||
|
export class Cd extends Program {
|
||||||
|
private shell: Shell
|
||||||
|
|
||||||
|
constructor(shell: Shell) {
|
||||||
|
super()
|
||||||
|
this.shell = shell
|
||||||
|
}
|
||||||
|
|
||||||
|
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("cd: error: the provided path is not a directory\n")
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!(await item.Exists())) {
|
||||||
|
stdout.emit(`cd: error: path ${item.GetPath()} doesn't exist\n`)
|
||||||
|
return 2
|
||||||
|
}
|
||||||
|
|
||||||
|
await this.shell.SetWorkingDirectory(item)
|
||||||
|
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,7 +4,7 @@ import { Program } from './Program'
|
|||||||
|
|
||||||
export class Clear extends Program {
|
export class Clear extends Program {
|
||||||
async Exec(_: SimpleStream<string>, stdout: SimpleStream<string>, __: Item, ___: string[]): Promise<number> {
|
async Exec(_: SimpleStream<string>, stdout: SimpleStream<string>, __: Item, ___: string[]): Promise<number> {
|
||||||
stdout.emit('\f')
|
stdout.emit('\x1b[2J\x1b[H')
|
||||||
|
|
||||||
return 0
|
return 0
|
||||||
}
|
}
|
||||||
|
|||||||
59
src/program/Cp.ts
Normal file
59
src/program/Cp.ts
Normal 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
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -7,27 +7,8 @@ export class Echo extends Program {
|
|||||||
super()
|
super()
|
||||||
}
|
}
|
||||||
|
|
||||||
async Exec(_: SimpleStream<string>, stdout: SimpleStream<string>, workdir: Item, args: string[]): Promise<number> {
|
async Exec(_: SimpleStream<string>, stdout: SimpleStream<string>, __: Item, args: string[]): Promise<number> {
|
||||||
if (args.length < 2) {
|
stdout.emit(args.slice(1).join(' ') + '\n')
|
||||||
stdout.emit("echo: error: missing path argument\n")
|
|
||||||
return 1
|
|
||||||
}
|
|
||||||
|
|
||||||
const item = await Item.open(args[1].startsWith('/')
|
|
||||||
? args[1]
|
|
||||||
: `${workdir.GetPath()}${workdir.GetPath().endsWith('/') ? '' : '/'}${args[1]}`)
|
|
||||||
|
|
||||||
if (!(await item.Exists())) {
|
|
||||||
stdout.emit(`echo: error: item ${item.GetPath()} doesn't exist.\n`)
|
|
||||||
return 2
|
|
||||||
}
|
|
||||||
|
|
||||||
if (item.IsDirectory()) {
|
|
||||||
stdout.emit(`echo: error: can't write data to a directory; item ${item.GetPath()} is a directory.\n`)
|
|
||||||
return 3
|
|
||||||
}
|
|
||||||
|
|
||||||
await item.Write(args.slice(2).join(' '))
|
|
||||||
|
|
||||||
return 0
|
return 0
|
||||||
}
|
}
|
||||||
|
|||||||
390
src/program/Edit.ts
Normal file
390
src/program/Edit.ts
Normal 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)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,17 +3,33 @@ import type { SimpleStream } from '../utils/SimpleStream'
|
|||||||
import { Program } from './Program'
|
import { Program } from './Program'
|
||||||
|
|
||||||
export class Eval extends Program {
|
export class Eval extends Program {
|
||||||
async Exec(_: SimpleStream<string>, stdout: SimpleStream<string>, _workdir: Item, args: string[]): Promise<number> {
|
async Exec(stdin: SimpleStream<string>, stdout: SimpleStream<string>, _workdir: Item, args: string[]): Promise<number> {
|
||||||
const javascript = args.slice(1).join(' ')
|
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 {
|
try {
|
||||||
// todo: pass workdir to the program
|
this.RunJs(source, stdout)
|
||||||
eval(javascript)
|
} catch {
|
||||||
} catch (e) {
|
|
||||||
stdout.emit(`${String(e)}\n`)
|
|
||||||
return 1
|
return 1
|
||||||
}
|
}
|
||||||
|
|
||||||
return 0
|
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
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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 type { Item } from '../fs/Item'
|
||||||
import { Terminal } from '../terminal/Terminal'
|
import { Terminal } from '../terminal/Terminal'
|
||||||
import type { SimpleStream } from '../utils/SimpleStream'
|
import type { SimpleStream } from '../utils/SimpleStream'
|
||||||
@@ -6,9 +6,24 @@ import { Program } from './Program'
|
|||||||
|
|
||||||
export class Info extends Program {
|
export class Info extends Program {
|
||||||
async Exec(_: SimpleStream<string>, stdout: SimpleStream<string>, __: Item, ___: string[]): Promise<number> {
|
async Exec(_: SimpleStream<string>, stdout: SimpleStream<string>, __: Item, ___: string[]): Promise<number> {
|
||||||
stdout.emit(`Webshell v${WEBSHELL_VERSION}\n`)
|
stdout.emit('\n')
|
||||||
stdout.emit(`Terminal v${Terminal.Version}\n`)
|
stdout.emit(" --> binekrasik's Webshell / ->\n\n")
|
||||||
stdout.emit(`Running ${GetCurrentTerminal().GetShell()?.Name} v${GetCurrentTerminal().GetShell()?.Version}\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
|
return 0
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import type { Item } from '../fs/Item'
|
import { Item } from '../fs/Item'
|
||||||
import type { Shell } from '../shell/Shell'
|
import type { Shell } from '../shell/Shell'
|
||||||
import type { SimpleStream } from '../utils/SimpleStream'
|
import type { SimpleStream } from '../utils/SimpleStream'
|
||||||
import { Program } from './Program'
|
import { Program } from './Program'
|
||||||
@@ -12,18 +12,58 @@ export class Loadprg extends Program {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async Exec(_: SimpleStream<string>, stdout: SimpleStream<string>, workdir: Item, args: string[]): Promise<number> {
|
async Exec(_: SimpleStream<string>, stdout: SimpleStream<string>, workdir: Item, args: string[]): Promise<number> {
|
||||||
const javascript = args.slice(2).join(' ')
|
const path = Item.NormalizePath(args[1].startsWith('/') ? args[1] : `${workdir.GetPath()}/${args[1]}`)
|
||||||
|
let file: Item
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const program = eval(javascript)
|
file = await Item.open(path)
|
||||||
|
} catch (err) {
|
||||||
this.shell.LoadProgram(new program(), args[1])
|
stdout.emit(`loadprg: error: item ${path} is a directory\n`)
|
||||||
} catch (e) {
|
return 2
|
||||||
stdout.emit(`${String(e)}\n`)
|
|
||||||
stdout.emit(`${String((e as Error).stack)}\n`)
|
|
||||||
return 1
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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
|
return 0
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,10 +8,13 @@ export class Ls extends Program {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async Exec(_: SimpleStream<string>, stdout: SimpleStream<string>, workdir: Item, args: string[]): Promise<number> {
|
async Exec(_: SimpleStream<string>, stdout: SimpleStream<string>, workdir: Item, args: string[]): Promise<number> {
|
||||||
|
// open the target directory, default to workdir
|
||||||
const item = args[1]
|
const item = args[1]
|
||||||
? await Item.openDir(args[1].startsWith('/')
|
? await Item.openDir(Item.NormalizePath(
|
||||||
? args[1]
|
args[1].startsWith('/')
|
||||||
: `${workdir.GetPath()}${workdir.GetPath().endsWith('/') ? '' : '/'}${args[1]}`)
|
? args[1]
|
||||||
|
: `${workdir.GetPath()}/${args[1]}`
|
||||||
|
))
|
||||||
: workdir
|
: workdir
|
||||||
|
|
||||||
if (args[1] && !item.IsDirectory()) {
|
if (args[1] && !item.IsDirectory()) {
|
||||||
@@ -24,14 +27,11 @@ export class Ls extends Program {
|
|||||||
return 2
|
return 2
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log(item)
|
|
||||||
|
|
||||||
stdout.emit(`-> Listing contents of item: '${item.GetPath()}'\n`)
|
stdout.emit(`-> Listing contents of item: '${item.GetPath()}'\n`)
|
||||||
stdout.emit(` [ drwx name ]\n`)
|
stdout.emit(` [ drwx name ]\n`)
|
||||||
const items = await item.List()
|
const items = await item.List()
|
||||||
items.forEach(entry => {
|
items.forEach(entry => {
|
||||||
stdout.emit(item.IsDirectory().toString())
|
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`)
|
||||||
stdout.emit(` | ${(item.IsDirectory() ? 'd' : '').padEnd(4, '-').padEnd(8, ' ')} ${entry.GetName()}\n`)
|
|
||||||
})
|
})
|
||||||
|
|
||||||
return 0
|
return 0
|
||||||
|
|||||||
@@ -13,18 +13,15 @@ export class Mkdir extends Program {
|
|||||||
return 1
|
return 1
|
||||||
}
|
}
|
||||||
|
|
||||||
const item = await Item.openDir(args[1].startsWith('/')
|
const item = await Item.openDir(Item.NormalizePath(args[1].startsWith('/') ? args[1] : `${workdir.GetPath()}/${args[1]}`))
|
||||||
? args[1]
|
|
||||||
: `${workdir.GetPath()}${workdir.GetPath().endsWith('/') ? '' : '/'}${args[1]}`)
|
|
||||||
|
|
||||||
stdout.emit(`does ${args[1]} exist? ${await item.Exists()}\n`)
|
|
||||||
|
|
||||||
if (await item.Exists()) {
|
if (await item.Exists()) {
|
||||||
stdout.emit(`mkdir: directory ${item.GetPath()} already exists.\n`)
|
stdout.emit(`mkdir: directory ${item.GetPath()} already exists.\n`)
|
||||||
return 2
|
return 2
|
||||||
}
|
}
|
||||||
|
|
||||||
item.Create()
|
await item.Create()
|
||||||
|
|
||||||
return 0
|
return 0
|
||||||
}
|
}
|
||||||
|
|||||||
61
src/program/Mv.ts
Normal file
61
src/program/Mv.ts
Normal 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
|
||||||
|
}
|
||||||
|
}
|
||||||
15
src/program/Printf.ts
Normal file
15
src/program/Printf.ts
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
import { Item } from '../fs/Item'
|
||||||
|
import type { SimpleStream } from '../utils/SimpleStream'
|
||||||
|
import { Program } from './Program'
|
||||||
|
|
||||||
|
export class Printf extends Program {
|
||||||
|
constructor() {
|
||||||
|
super()
|
||||||
|
}
|
||||||
|
|
||||||
|
async Exec(_: SimpleStream<string>, stdout: SimpleStream<string>, __: Item, args: string[]): Promise<number> {
|
||||||
|
stdout.emit(args.slice(1).join(' '))
|
||||||
|
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
}
|
||||||
15
src/program/Pwd.ts
Normal file
15
src/program/Pwd.ts
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
import { Item } from '../fs/Item'
|
||||||
|
import type { SimpleStream } from '../utils/SimpleStream'
|
||||||
|
import { Program } from './Program'
|
||||||
|
|
||||||
|
export class Pwd extends Program {
|
||||||
|
constructor() {
|
||||||
|
super()
|
||||||
|
}
|
||||||
|
|
||||||
|
async Exec(_: SimpleStream<string>, stdout: SimpleStream<string>, workdir: Item, __: string[]): Promise<number> {
|
||||||
|
stdout.emit(`${workdir.GetPath()}\n`)
|
||||||
|
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -30,7 +30,7 @@ export class Rm extends Program {
|
|||||||
return 1
|
return 1
|
||||||
}
|
}
|
||||||
|
|
||||||
stdout.emit(`removing: '${item.GetPath()}'\n`)
|
stdout.emit(`-> removing: '${item.GetPath()}'\n`)
|
||||||
|
|
||||||
await item.Delete()
|
await item.Delete()
|
||||||
|
|
||||||
|
|||||||
@@ -1,51 +1,43 @@
|
|||||||
// --- `sl` Command Implementation ---
|
import { GetCurrentTerminal } from '../app'
|
||||||
|
import type { Item } from '../fs/Item'
|
||||||
|
import type { SimpleStream } from '../utils/SimpleStream'
|
||||||
|
import { Program } from './Program'
|
||||||
|
|
||||||
import type { Item } from "../fs/Item"
|
type SmokeState = {
|
||||||
import type { SimpleStream } from "../utils/SimpleStream"
|
y: number
|
||||||
import { Program } from "./Program"
|
x: number
|
||||||
|
ptrn: number
|
||||||
|
kind: number
|
||||||
|
}
|
||||||
|
|
||||||
|
type SlOptions = {
|
||||||
|
accident: boolean
|
||||||
|
fly: boolean
|
||||||
|
logo: boolean
|
||||||
|
c51: boolean
|
||||||
|
}
|
||||||
|
|
||||||
export class Sl extends Program {
|
export class Sl extends Program {
|
||||||
// The classic D51 locomotive ASCII art with 3 frames of wheel animation.
|
private static readonly D51_HEIGHT = 10
|
||||||
// Notice the trailing space on each line: this acts as an automatic "eraser"
|
private static readonly D51_FUNNEL = 7
|
||||||
// for the previous frame as the train moves left!
|
private static readonly D51_LENGTH = 83
|
||||||
private static readonly D51_FRAMES: string[][] = [
|
private static readonly D51_PATTERNS = 6
|
||||||
[
|
|
||||||
' ==== ________ ___________ ',
|
private static readonly LOGO_HEIGHT = 6
|
||||||
' _D _| |_______/ \\__I_I_____===__|_________| ',
|
private static readonly LOGO_FUNNEL = 4
|
||||||
' |(_)--- | H\\________/ | | =|___ ___| ',
|
private static readonly LOGO_LENGTH = 84
|
||||||
' / | | H | | | | ||_| |_|| ',
|
private static readonly LOGO_PATTERNS = 6
|
||||||
' | | | H |__--------------------| [___] | ',
|
|
||||||
' | ________|___H__/__|_____/[][]~\\_______| | ',
|
private static readonly C51_HEIGHT = 11
|
||||||
' |/ | |-----------I_____I [][] [] D |=======| ',
|
private static readonly C51_FUNNEL = 7
|
||||||
'__/ =| o |=-O=====O=====O=====O \\ ____Y___________| ',
|
private static readonly C51_LENGTH = 87
|
||||||
' |/-=|___|= || || || |_____/~\\___/ ',
|
private static readonly C51_PATTERNS = 6
|
||||||
' \\_/ \\__/ \\__/ \\__/ \\__/ \\_/ ',
|
|
||||||
],
|
private static readonly SMOKE_PATTERNS = 16
|
||||||
[
|
private static readonly MAX_SMOKE = 1000
|
||||||
' ==== ________ ___________ ',
|
|
||||||
' _D _| |_______/ \\__I_I_____===__|_________| ',
|
private smokes: SmokeState[] = []
|
||||||
' |(_)--- | H\\________/ | | =|___ ___| ',
|
private smokeSum = 0
|
||||||
' / | | H | | | | ||_| |_|| ',
|
|
||||||
' | | | H |__--------------------| [___] | ',
|
|
||||||
' | ________|___H__/__|_____/[][]~\\_______| | ',
|
|
||||||
' |/ | |-----------I_____I [][] [] D |=======| ',
|
|
||||||
'__/ =| o |=-~O====O====O====O~ \\ ____Y___________| ',
|
|
||||||
' |/-=|___|= || || || |_____/~\\___/ ',
|
|
||||||
' \\_/ \\__/ \\__/ \\__/ \\__/ \\_/ ',
|
|
||||||
],
|
|
||||||
[
|
|
||||||
' ==== ________ ___________ ',
|
|
||||||
' _D _| |_______/ \\__I_I_____===__|_________| ',
|
|
||||||
' |(_)--- | H\\________/ | | =|___ ___| ',
|
|
||||||
' / | | H | | | | ||_| |_|| ',
|
|
||||||
' | | | H |__--------------------| [___] | ',
|
|
||||||
' | ________|___H__/__|_____/[][]~\\_______| | ',
|
|
||||||
' |/ | |-----------I_____I [][] [] D |=======| ',
|
|
||||||
'__/ =| o |=-~~O===O===O===O~~ \\ ____Y___________| ',
|
|
||||||
' |/-=|___|= || || || |_____/~\\___/ ',
|
|
||||||
' \\_/ \\__/ \\__/ \\__/ \\__/ \\_/ ',
|
|
||||||
],
|
|
||||||
]
|
|
||||||
|
|
||||||
public async Exec(
|
public async Exec(
|
||||||
_: SimpleStream<string>,
|
_: SimpleStream<string>,
|
||||||
@@ -53,67 +45,588 @@ export class Sl extends Program {
|
|||||||
__: Item,
|
__: Item,
|
||||||
args: string[],
|
args: string[],
|
||||||
): Promise<number> {
|
): Promise<number> {
|
||||||
// Original `sl` behavior flags
|
const options = this.parseOptions(args)
|
||||||
const isFly = args.includes('-F')
|
const terminal = GetCurrentTerminal()
|
||||||
|
const cols = Math.max(1, Math.floor(terminal.GetWidthCells()))
|
||||||
|
const lines = Math.max(1, Math.floor(terminal.GetHeightCells()))
|
||||||
|
|
||||||
// Terminal size assumptions since they aren't provided by the API
|
this.resetSmoke()
|
||||||
const termWidth = 100
|
|
||||||
const trainWidth = Sl.D51_FRAMES[0][0].length
|
|
||||||
|
|
||||||
// The train starts off-screen to the right and ends completely off-screen to the left
|
// Clear screen and move cursor home (ANSI CSI)
|
||||||
const startX = termWidth
|
stdout.emit('\x1b[2J\x1b[H')
|
||||||
const endX = -trainWidth
|
|
||||||
|
|
||||||
// Clear screen (new page using form feed)
|
for (let x = cols - 1; ; --x) {
|
||||||
stdout.emit('\f')
|
const ok = options.logo
|
||||||
|
? this.addSl(x, stdout, cols, lines, options)
|
||||||
|
: options.c51
|
||||||
|
? this.addC51(x, stdout, cols, lines, options)
|
||||||
|
: this.addD51(x, stdout, cols, lines, options)
|
||||||
|
|
||||||
let frameIdx = 0
|
if (!ok)
|
||||||
for (let x = startX; x >= endX; x--) {
|
break
|
||||||
const frame = Sl.D51_FRAMES[frameIdx % Sl.D51_FRAMES.length]
|
|
||||||
|
|
||||||
// If the `-F` flag is passed, the train "flies" upwards as it moves forward
|
|
||||||
let startY = isFly ? Math.floor(x / 4) + 2 : 5
|
|
||||||
|
|
||||||
for (let y = 0; y < frame.length; y++) {
|
|
||||||
const line = frame[y]
|
|
||||||
let outLine = line
|
|
||||||
let cursorX = x
|
|
||||||
|
|
||||||
// When the train hits the left edge, we must truncate the string
|
|
||||||
// and lock the drawing cursor to X=0 to prevent terminal wrapping artifacts
|
|
||||||
if (x < 0) {
|
|
||||||
cursorX = 0
|
|
||||||
outLine = line.substring(-x)
|
|
||||||
}
|
|
||||||
|
|
||||||
const cursorY = startY + y
|
|
||||||
|
|
||||||
// Only render if within vertical bounds and there's text left to draw
|
|
||||||
if (cursorY >= 0 && outLine.length > 0) {
|
|
||||||
// Send absolute cursor positioning sequence
|
|
||||||
stdout.emit(`\0cma;${cursorX};${cursorY}\0`)
|
|
||||||
// Render the frame line
|
|
||||||
stdout.emit(outLine)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Artificial delay to pace the animation
|
|
||||||
await this.sleep(40)
|
await this.sleep(40)
|
||||||
frameIdx++
|
|
||||||
|
|
||||||
console.log(frameIdx)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Return the cursor back to a safe position to give shell control back seamlessly
|
stdout.emit(`\x1b[${Math.max(1, lines)};1H\n`)
|
||||||
stdout.emit(`\0cma;0;20\0\n`)
|
return 0
|
||||||
|
}
|
||||||
return 0 // POSIX successful exit code
|
|
||||||
|
private parseOptions(args: string[]): SlOptions {
|
||||||
|
const options: SlOptions = {
|
||||||
|
accident: false,
|
||||||
|
fly: false,
|
||||||
|
logo: false,
|
||||||
|
c51: false,
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const arg of args.slice(1)) {
|
||||||
|
if (!arg.startsWith('-'))
|
||||||
|
continue
|
||||||
|
|
||||||
|
for (const flag of arg.slice(1)) {
|
||||||
|
switch (flag) {
|
||||||
|
case 'a':
|
||||||
|
options.accident = true
|
||||||
|
break
|
||||||
|
case 'F':
|
||||||
|
options.fly = true
|
||||||
|
break
|
||||||
|
case 'l':
|
||||||
|
options.logo = true
|
||||||
|
break
|
||||||
|
case 'c':
|
||||||
|
options.c51 = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return options
|
||||||
|
}
|
||||||
|
|
||||||
|
private addSl(
|
||||||
|
x: number,
|
||||||
|
stdout: SimpleStream<string>,
|
||||||
|
cols: number,
|
||||||
|
lines: number,
|
||||||
|
options: SlOptions,
|
||||||
|
): boolean {
|
||||||
|
if (x < -Sl.LOGO_LENGTH)
|
||||||
|
return false
|
||||||
|
|
||||||
|
let y = Math.max(0, Math.floor(lines / 2) - 3)
|
||||||
|
let py1 = 0
|
||||||
|
let py2 = 0
|
||||||
|
let py3 = 0
|
||||||
|
|
||||||
|
if (options.fly) {
|
||||||
|
y = Math.trunc(x / 6) + lines - Math.trunc(cols / 6) - Sl.LOGO_HEIGHT
|
||||||
|
py1 = 2
|
||||||
|
py2 = 4
|
||||||
|
py3 = 6
|
||||||
|
}
|
||||||
|
|
||||||
|
const pattern = Math.floor((Sl.LOGO_LENGTH + x) / 3) % Sl.LOGO_PATTERNS
|
||||||
|
|
||||||
|
for (let i = 0; i <= Sl.LOGO_HEIGHT; i++) {
|
||||||
|
this.drawString(stdout, cols, lines, y + i, x, Sl.LOGO[pattern][i])
|
||||||
|
this.drawString(stdout, cols, lines, y + i + py1, x + 21, Sl.LOGO_COAL[i])
|
||||||
|
this.drawString(stdout, cols, lines, y + i + py2, x + 42, Sl.LOGO_CAR[i])
|
||||||
|
this.drawString(stdout, cols, lines, y + i + py3, x + 63, Sl.LOGO_CAR[i])
|
||||||
|
}
|
||||||
|
|
||||||
|
if (options.accident) {
|
||||||
|
this.addMan(stdout, cols, lines, y + 1, x + 14)
|
||||||
|
this.addMan(stdout, cols, lines, y + 1 + py2, x + 45)
|
||||||
|
this.addMan(stdout, cols, lines, y + 1 + py2, x + 53)
|
||||||
|
this.addMan(stdout, cols, lines, y + 1 + py3, x + 66)
|
||||||
|
this.addMan(stdout, cols, lines, y + 1 + py3, x + 74)
|
||||||
|
}
|
||||||
|
|
||||||
|
this.addSmoke(stdout, cols, lines, y - 1, x + Sl.LOGO_FUNNEL)
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
private addD51(
|
||||||
|
x: number,
|
||||||
|
stdout: SimpleStream<string>,
|
||||||
|
cols: number,
|
||||||
|
lines: number,
|
||||||
|
options: SlOptions,
|
||||||
|
): boolean {
|
||||||
|
if (x < -Sl.D51_LENGTH)
|
||||||
|
return false
|
||||||
|
|
||||||
|
let y = Math.max(0, Math.floor(lines / 2) - 5)
|
||||||
|
let dy = 0
|
||||||
|
|
||||||
|
if (options.fly) {
|
||||||
|
y = Math.trunc(x / 7) + lines - Math.trunc(cols / 7) - Sl.D51_HEIGHT
|
||||||
|
dy = 1
|
||||||
|
}
|
||||||
|
|
||||||
|
const pattern = (Sl.D51_LENGTH + x) % Sl.D51_PATTERNS
|
||||||
|
|
||||||
|
for (let i = 0; i <= Sl.D51_HEIGHT; i++) {
|
||||||
|
this.drawString(stdout, cols, lines, y + i, x, Sl.D51[pattern][i])
|
||||||
|
this.drawString(stdout, cols, lines, y + i + dy, x + 53, Sl.D51_COAL[i])
|
||||||
|
}
|
||||||
|
|
||||||
|
if (options.accident) {
|
||||||
|
this.addMan(stdout, cols, lines, y + 2, x + 43)
|
||||||
|
this.addMan(stdout, cols, lines, y + 2, x + 47)
|
||||||
|
}
|
||||||
|
|
||||||
|
this.addSmoke(stdout, cols, lines, y - 1, x + Sl.D51_FUNNEL)
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
private addC51(
|
||||||
|
x: number,
|
||||||
|
stdout: SimpleStream<string>,
|
||||||
|
cols: number,
|
||||||
|
lines: number,
|
||||||
|
options: SlOptions,
|
||||||
|
): boolean {
|
||||||
|
if (x < -Sl.C51_LENGTH)
|
||||||
|
return false
|
||||||
|
|
||||||
|
let y = Math.max(0, Math.floor(lines / 2) - 5)
|
||||||
|
let dy = 0
|
||||||
|
|
||||||
|
if (options.fly) {
|
||||||
|
y = Math.trunc(x / 7) + lines - Math.trunc(cols / 7) - Sl.C51_HEIGHT
|
||||||
|
dy = 1
|
||||||
|
}
|
||||||
|
|
||||||
|
const pattern = (Sl.C51_LENGTH + x) % Sl.C51_PATTERNS
|
||||||
|
|
||||||
|
for (let i = 0; i <= Sl.C51_HEIGHT; i++) {
|
||||||
|
this.drawString(stdout, cols, lines, y + i, x, Sl.C51[pattern][i])
|
||||||
|
this.drawString(stdout, cols, lines, y + i + dy, x + 55, Sl.C51_COAL[i])
|
||||||
|
}
|
||||||
|
|
||||||
|
if (options.accident) {
|
||||||
|
this.addMan(stdout, cols, lines, y + 3, x + 45)
|
||||||
|
this.addMan(stdout, cols, lines, y + 3, x + 49)
|
||||||
|
}
|
||||||
|
|
||||||
|
this.addSmoke(stdout, cols, lines, y - 1, x + Sl.C51_FUNNEL)
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
private addMan(
|
||||||
|
stdout: SimpleStream<string>,
|
||||||
|
cols: number,
|
||||||
|
lines: number,
|
||||||
|
y: number,
|
||||||
|
x: number,
|
||||||
|
) {
|
||||||
|
const man = [['', '(O)'], ['Help!', '\\O/']]
|
||||||
|
const index = Math.floor((Sl.LOGO_LENGTH + x) / 12) % 2
|
||||||
|
|
||||||
|
for (let i = 0; i < 2; i++)
|
||||||
|
this.drawString(stdout, cols, lines, y + i, x, man[index][i])
|
||||||
|
}
|
||||||
|
|
||||||
|
private addSmoke(
|
||||||
|
stdout: SimpleStream<string>,
|
||||||
|
cols: number,
|
||||||
|
lines: number,
|
||||||
|
y: number,
|
||||||
|
x: number,
|
||||||
|
) {
|
||||||
|
if (x % 4 !== 0)
|
||||||
|
return
|
||||||
|
|
||||||
|
for (let i = 0; i < this.smokeSum; i++) {
|
||||||
|
const smoke = this.smokes[i]
|
||||||
|
|
||||||
|
this.drawString(stdout, cols, lines, smoke.y, smoke.x, Sl.SMOKE_ERASER[smoke.ptrn])
|
||||||
|
smoke.y -= Sl.SMOKE_DY[smoke.ptrn]
|
||||||
|
smoke.x += Sl.SMOKE_DX[smoke.ptrn]
|
||||||
|
smoke.ptrn = smoke.ptrn < Sl.SMOKE_PATTERNS - 1 ? smoke.ptrn + 1 : smoke.ptrn
|
||||||
|
this.drawString(stdout, cols, lines, smoke.y, smoke.x, Sl.SMOKE[smoke.kind][smoke.ptrn])
|
||||||
|
}
|
||||||
|
|
||||||
|
this.drawString(stdout, cols, lines, y, x, Sl.SMOKE[this.smokeSum % 2][0])
|
||||||
|
|
||||||
|
if (this.smokeSum < Sl.MAX_SMOKE) {
|
||||||
|
this.smokes[this.smokeSum] = { y, x, ptrn: 0, kind: this.smokeSum % 2 }
|
||||||
|
this.smokeSum++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private drawString(
|
||||||
|
stdout: SimpleStream<string>,
|
||||||
|
cols: number,
|
||||||
|
lines: number,
|
||||||
|
y: number,
|
||||||
|
x: number,
|
||||||
|
text: string,
|
||||||
|
) {
|
||||||
|
if (y < 0 || y >= lines)
|
||||||
|
return
|
||||||
|
|
||||||
|
let cursorX = x
|
||||||
|
let out = text
|
||||||
|
|
||||||
|
if (cursorX < 0) {
|
||||||
|
out = out.slice(-cursorX)
|
||||||
|
cursorX = 0
|
||||||
|
}
|
||||||
|
|
||||||
|
if (cursorX >= cols || out.length === 0)
|
||||||
|
return
|
||||||
|
|
||||||
|
if (cursorX + out.length > cols)
|
||||||
|
out = out.slice(0, cols - cursorX)
|
||||||
|
|
||||||
|
stdout.emit(`\x1b[${y + 1};${cursorX + 1}H${out}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
private resetSmoke() {
|
||||||
|
this.smokes = []
|
||||||
|
this.smokeSum = 0
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Utility method to pause execution to pace the animation frames.
|
|
||||||
*/
|
|
||||||
private sleep(ms: number): Promise<void> {
|
private sleep(ms: number): Promise<void> {
|
||||||
return new Promise(resolve => setTimeout(resolve, ms))
|
return new Promise(resolve => setTimeout(resolve, ms))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static readonly LOGO: string[][] = [
|
||||||
|
[
|
||||||
|
' ++ +------ ',
|
||||||
|
' || |+-+ | ',
|
||||||
|
' /---------|| | | ',
|
||||||
|
' + ======== +-+ | ',
|
||||||
|
' _|--O========O~\\-+ ',
|
||||||
|
'//// \\_/ \\_/ ',
|
||||||
|
' ',
|
||||||
|
],
|
||||||
|
[
|
||||||
|
' ++ +------ ',
|
||||||
|
' || |+-+ | ',
|
||||||
|
' /---------|| | | ',
|
||||||
|
' + ======== +-+ | ',
|
||||||
|
' _|--/O========O\\-+ ',
|
||||||
|
'//// \\_/ \\_/ ',
|
||||||
|
' ',
|
||||||
|
],
|
||||||
|
[
|
||||||
|
' ++ +------ ',
|
||||||
|
' || |+-+ | ',
|
||||||
|
' /---------|| | | ',
|
||||||
|
' + ======== +-+ | ',
|
||||||
|
' _|--/~O========O-+ ',
|
||||||
|
'//// \\_/ \\_/ ',
|
||||||
|
' ',
|
||||||
|
],
|
||||||
|
[
|
||||||
|
' ++ +------ ',
|
||||||
|
' || |+-+ | ',
|
||||||
|
' /---------|| | | ',
|
||||||
|
' + ======== +-+ | ',
|
||||||
|
' _|--/~\\------/~\\-+ ',
|
||||||
|
'//// \\_O========O ',
|
||||||
|
' ',
|
||||||
|
],
|
||||||
|
[
|
||||||
|
' ++ +------ ',
|
||||||
|
' || |+-+ | ',
|
||||||
|
' /---------|| | | ',
|
||||||
|
' + ======== +-+ | ',
|
||||||
|
' _|--/~\\------/~\\-+ ',
|
||||||
|
'//// \\O========O/ ',
|
||||||
|
' ',
|
||||||
|
],
|
||||||
|
[
|
||||||
|
' ++ +------ ',
|
||||||
|
' || |+-+ | ',
|
||||||
|
' /---------|| | | ',
|
||||||
|
' + ======== +-+ | ',
|
||||||
|
' _|--/~\\------/~\\-+ ',
|
||||||
|
'//// O========O_/ ',
|
||||||
|
' ',
|
||||||
|
],
|
||||||
|
]
|
||||||
|
|
||||||
|
private static readonly LOGO_COAL = [
|
||||||
|
'____ ',
|
||||||
|
'| \\@@@@@@@@@@@ ',
|
||||||
|
'| \\@@@@@@@@@@@@@_ ',
|
||||||
|
'| | ',
|
||||||
|
'|__________________| ',
|
||||||
|
' (O) (O) ',
|
||||||
|
' ',
|
||||||
|
]
|
||||||
|
|
||||||
|
private static readonly LOGO_CAR = [
|
||||||
|
'____________________ ',
|
||||||
|
'| ___ ___ ___ ___ | ',
|
||||||
|
'| |_| |_| |_| |_| | ',
|
||||||
|
'|__________________| ',
|
||||||
|
'|__________________| ',
|
||||||
|
' (O) (O) ',
|
||||||
|
' ',
|
||||||
|
]
|
||||||
|
|
||||||
|
private static readonly D51 = [
|
||||||
|
[
|
||||||
|
' ==== ________ ___________ ',
|
||||||
|
' _D _| |_______/ \\__I_I_____===__|_________| ',
|
||||||
|
' |(_)--- | H\\________/ | | =|___ ___| ',
|
||||||
|
' / | | H | | | | ||_| |_|| ',
|
||||||
|
' | | | H |__--------------------| [___] | ',
|
||||||
|
' | ________|___H__/__|_____/[][]~\\_______| | ',
|
||||||
|
' |/ | |-----------I_____I [][] [] D |=======|__ ',
|
||||||
|
'__/ =| o |=-~~\\ /~~\\ /~~\\ /~~\\ ____Y___________|__ ',
|
||||||
|
' |/-=|___|= || || || |_____/~\\___/ ',
|
||||||
|
' \\_/ \\O=====O=====O=====O_/ \\_/ ',
|
||||||
|
' ',
|
||||||
|
],
|
||||||
|
[
|
||||||
|
' ==== ________ ___________ ',
|
||||||
|
' _D _| |_______/ \\__I_I_____===__|_________| ',
|
||||||
|
' |(_)--- | H\\________/ | | =|___ ___| ',
|
||||||
|
' / | | H | | | | ||_| |_|| ',
|
||||||
|
' | | | H |__--------------------| [___] | ',
|
||||||
|
' | ________|___H__/__|_____/[][]~\\_______| | ',
|
||||||
|
' |/ | |-----------I_____I [][] [] D |=======|__ ',
|
||||||
|
'__/ =| o |=-~~\\ /~~\\ /~~\\ /~~\\ ____Y___________|__ ',
|
||||||
|
' |/-=|___|=O=====O=====O=====O |_____/~\\___/ ',
|
||||||
|
' \\_/ \\__/ \\__/ \\__/ \\__/ \\_/ ',
|
||||||
|
' ',
|
||||||
|
],
|
||||||
|
[
|
||||||
|
' ==== ________ ___________ ',
|
||||||
|
' _D _| |_______/ \\__I_I_____===__|_________| ',
|
||||||
|
' |(_)--- | H\\________/ | | =|___ ___| ',
|
||||||
|
' / | | H | | | | ||_| |_|| ',
|
||||||
|
' | | | H |__--------------------| [___] | ',
|
||||||
|
' | ________|___H__/__|_____/[][]~\\_______| | ',
|
||||||
|
' |/ | |-----------I_____I [][] [] D |=======|__ ',
|
||||||
|
'__/ =| o |=-O=====O=====O=====O \\ ____Y___________|__ ',
|
||||||
|
' |/-=|___|= || || || |_____/~\\___/ ',
|
||||||
|
' \\_/ \\__/ \\__/ \\__/ \\__/ \\_/ ',
|
||||||
|
' ',
|
||||||
|
],
|
||||||
|
[
|
||||||
|
' ==== ________ ___________ ',
|
||||||
|
' _D _| |_______/ \\__I_I_____===__|_________| ',
|
||||||
|
' |(_)--- | H\\________/ | | =|___ ___| ',
|
||||||
|
' / | | H | | | | ||_| |_|| ',
|
||||||
|
' | | | H |__--------------------| [___] | ',
|
||||||
|
' | ________|___H__/__|_____/[][]~\\_______| | ',
|
||||||
|
' |/ | |-----------I_____I [][] [] D |=======|__ ',
|
||||||
|
'__/ =| o |=-~O=====O=====O=====O\\ ____Y___________|__ ',
|
||||||
|
' |/-=|___|= || || || |_____/~\\___/ ',
|
||||||
|
' \\_/ \\__/ \\__/ \\__/ \\__/ \\_/ ',
|
||||||
|
' ',
|
||||||
|
],
|
||||||
|
[
|
||||||
|
' ==== ________ ___________ ',
|
||||||
|
' _D _| |_______/ \\__I_I_____===__|_________| ',
|
||||||
|
' |(_)--- | H\\________/ | | =|___ ___| ',
|
||||||
|
' / | | H | | | | ||_| |_|| ',
|
||||||
|
' | | | H |__--------------------| [___] | ',
|
||||||
|
' | ________|___H__/__|_____/[][]~\\_______| | ',
|
||||||
|
' |/ | |-----------I_____I [][] [] D |=======|__ ',
|
||||||
|
'__/ =| o |=-~~\\ /~~\\ /~~\\ /~~\\ ____Y___________|__ ',
|
||||||
|
' |/-=|___|= O=====O=====O=====O|_____/~\\___/ ',
|
||||||
|
' \\_/ \\__/ \\__/ \\__/ \\__/ \\_/ ',
|
||||||
|
' ',
|
||||||
|
],
|
||||||
|
[
|
||||||
|
' ==== ________ ___________ ',
|
||||||
|
' _D _| |_______/ \\__I_I_____===__|_________| ',
|
||||||
|
' |(_)--- | H\\________/ | | =|___ ___| ',
|
||||||
|
' / | | H | | | | ||_| |_|| ',
|
||||||
|
' | | | H |__--------------------| [___] | ',
|
||||||
|
' | ________|___H__/__|_____/[][]~\\_______| | ',
|
||||||
|
' |/ | |-----------I_____I [][] [] D |=======|__ ',
|
||||||
|
'__/ =| o |=-~~\\ /~~\\ /~~\\ /~~\\ ____Y___________|__ ',
|
||||||
|
' |/-=|___|= || || || |_____/~\\___/ ',
|
||||||
|
' \\_/ \\_O=====O=====O=====O/ \\_/ ',
|
||||||
|
' ',
|
||||||
|
],
|
||||||
|
]
|
||||||
|
|
||||||
|
private static readonly D51_COAL = [
|
||||||
|
' ',
|
||||||
|
' ',
|
||||||
|
' _________________ ',
|
||||||
|
' _| \\_____A ',
|
||||||
|
' =| | ',
|
||||||
|
' -| | ',
|
||||||
|
'__|________________________|_ ',
|
||||||
|
'|__________________________|_ ',
|
||||||
|
' |_D__D__D_| |_D__D__D_| ',
|
||||||
|
' \\_/ \\_/ \\_/ \\_/ ',
|
||||||
|
' ',
|
||||||
|
]
|
||||||
|
|
||||||
|
private static readonly C51 = [
|
||||||
|
[
|
||||||
|
' ___ ',
|
||||||
|
' _|_|_ _ __ __ ___________',
|
||||||
|
' D__/ \\_(_)___| |__H__| |_____I_Ii_()|_________|',
|
||||||
|
' | `---\' |:: `--\' H `--\' | |___ ___| ',
|
||||||
|
' +|~~~~~~~~++::~~~~~~~H~~+=====+~~~~~~|~~||_| |_|| ',
|
||||||
|
' || | :: H +=====+ | |:: ...| ',
|
||||||
|
'| | _______|_::-----------------[][]-----| | ',
|
||||||
|
'| /~~ || |-----/~~~~\\ /[I_____I][][] --|||_______|__',
|
||||||
|
'------\'|oOo|=[]=- || || | ||=======_|__',
|
||||||
|
'/~\\____|___|/~\\_| O=======O=======O |__|+-/~\\_| ',
|
||||||
|
'\\_/ \\_/ \\____/ \\____/ \\____/ \\_/ ',
|
||||||
|
' ',
|
||||||
|
],
|
||||||
|
[
|
||||||
|
' ___ ',
|
||||||
|
' _|_|_ _ __ __ ___________',
|
||||||
|
' D__/ \\_(_)___| |__H__| |_____I_Ii_()|_________|',
|
||||||
|
' | `---\' |:: `--\' H `--\' | |___ ___| ',
|
||||||
|
' +|~~~~~~~~++::~~~~~~~H~~+=====+~~~~~~|~~||_| |_|| ',
|
||||||
|
' || | :: H +=====+ | |:: ...| ',
|
||||||
|
'| | _______|_::-----------------[][]-----| | ',
|
||||||
|
'| /~~ || |-----/~~~~\\ /[I_____I][][] --|||_______|__',
|
||||||
|
'------\'|oOo|=[]=- O=======O=======O | ||=======_|__',
|
||||||
|
'/~\\____|___|/~\\_| || || |__|+-/~\\_| ',
|
||||||
|
'\\_/ \\_/ \\____/ \\____/ \\____/ \\_/ ',
|
||||||
|
' ',
|
||||||
|
],
|
||||||
|
[
|
||||||
|
' ___ ',
|
||||||
|
' _|_|_ _ __ __ ___________',
|
||||||
|
' D__/ \\_(_)___| |__H__| |_____I_Ii_()|_________|',
|
||||||
|
' | `---\' |:: `--\' H `--\' | |___ ___| ',
|
||||||
|
' +|~~~~~~~~++::~~~~~~~H~~+=====+~~~~~~|~~||_| |_|| ',
|
||||||
|
' || | :: H +=====+ | |:: ...| ',
|
||||||
|
'| | _______|_::-----------------[][]-----| | ',
|
||||||
|
'| /~~ || |-----/~~~~\\ /[I_____I][][] --|||_______|__',
|
||||||
|
'------\'|oOo|==[]=- O=======O=======O | ||=======_|__',
|
||||||
|
'/~\\____|___|/~\\_| || || |__|+-/~\\_| ',
|
||||||
|
'\\_/ \\_/ \\____/ \\____/ \\____/ \\_/ ',
|
||||||
|
' ',
|
||||||
|
],
|
||||||
|
[
|
||||||
|
' ___ ',
|
||||||
|
' _|_|_ _ __ __ ___________',
|
||||||
|
' D__/ \\_(_)___| |__H__| |_____I_Ii_()|_________|',
|
||||||
|
' | `---\' |:: `--\' H `--\' | |___ ___| ',
|
||||||
|
' +|~~~~~~~~++::~~~~~~~H~~+=====+~~~~~~|~~||_| |_|| ',
|
||||||
|
' || | :: H +=====+ | |:: ...| ',
|
||||||
|
'| | _______|_::-----------------[][]-----| | ',
|
||||||
|
'| /~~ || |-----/~~~~\\ /[I_____I][][] --|||_______|__',
|
||||||
|
'------\'|oOo|===[]=- O=======O=======O | ||=======_|__',
|
||||||
|
'/~\\____|___|/~\\_| || || |__|+-/~\\_| ',
|
||||||
|
'\\_/ \\_/ \\____/ \\____/ \\____/ \\_/ ',
|
||||||
|
' ',
|
||||||
|
],
|
||||||
|
[
|
||||||
|
' ___ ',
|
||||||
|
' _|_|_ _ __ __ ___________',
|
||||||
|
' D__/ \\_(_)___| |__H__| |_____I_Ii_()|_________|',
|
||||||
|
' | `---\' |:: `--\' H `--\' | |___ ___| ',
|
||||||
|
' +|~~~~~~~~++::~~~~~~~H~~+=====+~~~~~~|~~||_| |_|| ',
|
||||||
|
' || | :: H +=====+ | |:: ...| ',
|
||||||
|
'| | _______|_::-----------------[][]-----| | ',
|
||||||
|
'| /~~ || |-----/~~~~\\ /[I_____I][][] --|||_______|__',
|
||||||
|
'------\'|oOo|===[]=- || || | ||=======_|__',
|
||||||
|
'/~\\____|___|/~\\_| O=======O=======O |__|+-/~\\_| ',
|
||||||
|
'\\_/ \\_/ \\____/ \\____/ \\____/ \\_/ ',
|
||||||
|
' ',
|
||||||
|
],
|
||||||
|
[
|
||||||
|
' ___ ',
|
||||||
|
' _|_|_ _ __ __ ___________',
|
||||||
|
' D__/ \\_(_)___| |__H__| |_____I_Ii_()|_________|',
|
||||||
|
' | `---\' |:: `--\' H `--\' | |___ ___| ',
|
||||||
|
' +|~~~~~~~~++::~~~~~~~H~~+=====+~~~~~~|~~||_| |_|| ',
|
||||||
|
' || | :: H +=====+ | |:: ...| ',
|
||||||
|
'| | _______|_::-----------------[][]-----| | ',
|
||||||
|
'| /~~ || |-----/~~~~\\ /[I_____I][][] --|||_______|__',
|
||||||
|
'------\'|oOo|==[]=- || || | ||=======_|__',
|
||||||
|
'/~\\____|___|/~\\_| O=======O=======O |__|+-/~\\_| ',
|
||||||
|
'\\_/ \\_/ \\____/ \\____/ \\____/ \\_/ ',
|
||||||
|
' ',
|
||||||
|
],
|
||||||
|
]
|
||||||
|
|
||||||
|
private static readonly C51_COAL = [
|
||||||
|
' ',
|
||||||
|
' ',
|
||||||
|
' ',
|
||||||
|
' _________________ ',
|
||||||
|
' _| \\_____A ',
|
||||||
|
' =| | ',
|
||||||
|
' -| | ',
|
||||||
|
'__|________________________|_ ',
|
||||||
|
'|__________________________|_ ',
|
||||||
|
' |_D__D__D_| |_D__D__D_| ',
|
||||||
|
' \\_/ \\_/ \\_/ \\_/ ',
|
||||||
|
' ',
|
||||||
|
]
|
||||||
|
|
||||||
|
private static readonly SMOKE = [
|
||||||
|
[
|
||||||
|
'( )',
|
||||||
|
'( )',
|
||||||
|
'( )',
|
||||||
|
'( )',
|
||||||
|
'( )',
|
||||||
|
'( )',
|
||||||
|
'( )',
|
||||||
|
'( )',
|
||||||
|
'()',
|
||||||
|
'()',
|
||||||
|
'O',
|
||||||
|
'O',
|
||||||
|
'O',
|
||||||
|
'O',
|
||||||
|
'O',
|
||||||
|
' ',
|
||||||
|
],
|
||||||
|
[
|
||||||
|
'(@@@)',
|
||||||
|
'(@@@@)',
|
||||||
|
'(@@@@)',
|
||||||
|
'(@@@)',
|
||||||
|
'(@@)',
|
||||||
|
'(@@)',
|
||||||
|
'(@)',
|
||||||
|
'(@)',
|
||||||
|
'@@',
|
||||||
|
'@@',
|
||||||
|
'@',
|
||||||
|
'@',
|
||||||
|
'@',
|
||||||
|
'@',
|
||||||
|
'@',
|
||||||
|
' ',
|
||||||
|
],
|
||||||
|
]
|
||||||
|
|
||||||
|
private static readonly SMOKE_ERASER = [
|
||||||
|
' ',
|
||||||
|
' ',
|
||||||
|
' ',
|
||||||
|
' ',
|
||||||
|
' ',
|
||||||
|
' ',
|
||||||
|
' ',
|
||||||
|
' ',
|
||||||
|
' ',
|
||||||
|
' ',
|
||||||
|
' ',
|
||||||
|
' ',
|
||||||
|
' ',
|
||||||
|
' ',
|
||||||
|
' ',
|
||||||
|
' ',
|
||||||
|
]
|
||||||
|
|
||||||
|
private static readonly SMOKE_DY = [2, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
|
||||||
|
private static readonly SMOKE_DX = [-2, -1, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3]
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,18 +8,19 @@ export class Touch extends Program {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async Exec(_: SimpleStream<string>, stdout: SimpleStream<string>, workdir: Item, args: string[]): Promise<number> {
|
async Exec(_: SimpleStream<string>, stdout: SimpleStream<string>, workdir: Item, args: string[]): Promise<number> {
|
||||||
stdout.emit(`touching children, please wait...\n`)
|
if (args.length < 2) {
|
||||||
|
stdout.emit("touch: error: missing path argument\n")
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
|
||||||
const path = args.slice(1).join()
|
const item = await Item.open(Item.NormalizePath(args[1].startsWith('/') ? args[1] : `${workdir.GetPath()}/${args[1]}`))
|
||||||
const item = await Item.open(path.includes('/') ? path : `${workdir.GetPath()}${workdir.GetPath().endsWith('/') ? '' : '/'}${path}`)
|
|
||||||
stdout.emit(`does ${item.GetPath()} exist? ${await item.Exists()}\n`)
|
|
||||||
|
|
||||||
if (await item.Exists()) {
|
if (await item.Exists()) {
|
||||||
stdout.emit("touch: the file already exists.\n")
|
stdout.emit("touch: the file already exists.\n")
|
||||||
return 1
|
return 1
|
||||||
}
|
}
|
||||||
|
|
||||||
item.Create()
|
await item.Create()
|
||||||
|
|
||||||
return 0
|
return 0
|
||||||
}
|
}
|
||||||
|
|||||||
45
src/program/Tree.ts
Normal file
45
src/program/Tree.ts
Normal 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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -7,7 +7,7 @@ export abstract class Shell {
|
|||||||
readonly abstract Version: string
|
readonly abstract Version: string
|
||||||
readonly abstract Name: string
|
readonly abstract Name: string
|
||||||
broadcaster: EventBroadcaster
|
broadcaster: EventBroadcaster
|
||||||
terminal: Terminal
|
readonly terminal: Terminal
|
||||||
|
|
||||||
constructor(broadcaster: EventBroadcaster, terminal: Terminal) {
|
constructor(broadcaster: EventBroadcaster, terminal: Terminal) {
|
||||||
this.broadcaster = broadcaster
|
this.broadcaster = broadcaster
|
||||||
@@ -17,6 +17,5 @@ export abstract class Shell {
|
|||||||
abstract LoadProgram(program: Program, name: string): void
|
abstract LoadProgram(program: Program, name: string): void
|
||||||
abstract ExecuteProgram(name: string, args: string[]): void
|
abstract ExecuteProgram(name: string, args: string[]): void
|
||||||
abstract Init(): Promise<void>
|
abstract Init(): Promise<void>
|
||||||
abstract HandleKeyInput(key: string, isCharacter: boolean): void
|
|
||||||
abstract SetWorkingDirectory(directory: Item): Promise<void>
|
abstract SetWorkingDirectory(directory: Item): Promise<void>
|
||||||
}
|
}
|
||||||
|
|||||||
40
src/shell/wush/Environment.ts
Normal file
40
src/shell/wush/Environment.ts
Normal 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
|
||||||
|
}
|
||||||
|
}
|
||||||
242
src/shell/wush/InputManager.ts
Normal file
242
src/shell/wush/InputManager.ts
Normal 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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
13
src/shell/wush/InputParser.ts
Normal file
13
src/shell/wush/InputParser.ts
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
/**
|
||||||
|
* Wush input parser
|
||||||
|
* Provides necessary parsing functions
|
||||||
|
*/
|
||||||
|
export class InputParser {
|
||||||
|
// static Tokenize(input: string) {
|
||||||
|
|
||||||
|
// }
|
||||||
|
|
||||||
|
// static Parse(tokens: string[]) {
|
||||||
|
|
||||||
|
// }
|
||||||
|
}
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -1,12 +1,14 @@
|
|||||||
@use "colors.scss" as colors;
|
@use "colors.scss" as colors;
|
||||||
|
|
||||||
#cursor {
|
#cursor {
|
||||||
top: 0;
|
|
||||||
left: 0;
|
|
||||||
width: 1px;
|
width: 1px;
|
||||||
height: 20px;
|
height: 20px;
|
||||||
position: absolute;
|
|
||||||
background: colors.$terminal-white;
|
|
||||||
|
|
||||||
|
top: 0;
|
||||||
|
left: 0;
|
||||||
|
|
||||||
|
position: absolute;
|
||||||
|
|
||||||
|
backdrop-filter: invert(100%) saturate(0);
|
||||||
transition: .2s cubic-bezier(0, 1, 0.3, 1);
|
transition: .2s cubic-bezier(0, 1, 0.3, 1);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,6 +6,8 @@
|
|||||||
background: colors.$terminal-background;
|
background: colors.$terminal-background;
|
||||||
color: colors.$terminal-white;
|
color: colors.$terminal-white;
|
||||||
font-family: "CaskaydiaCove", "CaskaydiaCove Nerd Font", "JetBrains Mono", "JetBrains Mono Nerd", monospace;
|
font-family: "CaskaydiaCove", "CaskaydiaCove Nerd Font", "JetBrains Mono", "JetBrains Mono Nerd", monospace;
|
||||||
|
font-variant-ligatures: normal;
|
||||||
|
font-feature-settings: "liga" 1, "calt" 1;
|
||||||
|
|
||||||
::-moz-selection {
|
::-moz-selection {
|
||||||
background: colors.$terminal-white;
|
background: colors.$terminal-white;
|
||||||
@@ -15,16 +17,10 @@
|
|||||||
p {
|
p {
|
||||||
margin: 0;
|
margin: 0;
|
||||||
height: fit-content;
|
height: fit-content;
|
||||||
word-wrap: break-word;
|
|
||||||
text-wrap: nowrap;
|
|
||||||
display: flex;
|
|
||||||
|
|
||||||
span {
|
|
||||||
display: inline-block;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.line {
|
.line {
|
||||||
width: fit-content
|
width: fit-content;
|
||||||
|
white-space: pre;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,13 +5,40 @@ import sqs from '../utils/sqs'
|
|||||||
import type { CursorPosition, CursorStyle } from './CursorProperties'
|
import type { CursorPosition, CursorStyle } from './CursorProperties'
|
||||||
|
|
||||||
export class Terminal {
|
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 terminal: HTMLElement
|
||||||
private cursor: HTMLElement
|
private cursor: HTMLElement
|
||||||
private cursorStyle: CursorStyle = 'bar'
|
private cursorStyle: CursorStyle = 'bar'
|
||||||
private cellHeight = 0
|
private cellHeight = 0
|
||||||
private cellWidth = 0
|
private cellWidth = 0
|
||||||
|
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
|
||||||
|
|
||||||
private cursorPosition: CursorPosition = {
|
private cursorPosition: CursorPosition = {
|
||||||
col: 0,
|
col: 0,
|
||||||
@@ -25,9 +52,11 @@ export class Terminal {
|
|||||||
|
|
||||||
this.terminal = sqs('#terminal')
|
this.terminal = sqs('#terminal')
|
||||||
this.cursor = sqs('#cursor')
|
this.cursor = sqs('#cursor')
|
||||||
|
this.cursorRange = document.createRange()
|
||||||
|
|
||||||
this.SetCursorStyle('bar')
|
this.SetCursorStyle('bar')
|
||||||
this.NewPage()
|
this.NewPage()
|
||||||
|
this.CreateMetricsRefreshListener()
|
||||||
}
|
}
|
||||||
|
|
||||||
async LoadShell(shell: Shell) {
|
async LoadShell(shell: Shell) {
|
||||||
@@ -43,98 +72,312 @@ export class Terminal {
|
|||||||
this.ResetCellSize()
|
this.ResetCellSize()
|
||||||
|
|
||||||
this.terminal.innerHTML = ''
|
this.terminal.innerHTML = ''
|
||||||
|
this.lines = []
|
||||||
|
this.lineElements = []
|
||||||
|
this.lineWrapped = []
|
||||||
|
this.lineStyles.clear()
|
||||||
this.SetCursorPosition(0, 0)
|
this.SetCursorPosition(0, 0)
|
||||||
}
|
}
|
||||||
|
|
||||||
AppendLine() {
|
AppendLine() {
|
||||||
const paragraph = document.createElement('p')
|
this.EnsureLine(this.lineElements.length)
|
||||||
paragraph.style.height = `${this.cellHeight}px`
|
|
||||||
paragraph.id = `line-${this.cursorPosition.row}`
|
|
||||||
paragraph.className = 'line'
|
|
||||||
|
|
||||||
this.terminal.appendChild(paragraph)
|
|
||||||
this.UpdateLines()
|
|
||||||
paragraph.scrollIntoView({behavior: 'smooth'})
|
|
||||||
}
|
|
||||||
|
|
||||||
UpdateLines() {
|
|
||||||
const lines = new Array(...this.terminal.children)
|
|
||||||
lines.forEach((line, i) => line.id = `line-${i}`)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @returns index of the last line on the page. -1 if there are no lines
|
* @returns index of the last line on the page. -1 if there are no lines
|
||||||
*/
|
*/
|
||||||
GetLastLineIndex(): number {
|
GetLastLineIndex(): number {
|
||||||
return this.terminal.children.length - 1
|
return this.lineElements.length - 1
|
||||||
}
|
}
|
||||||
|
|
||||||
Write(text: string) {
|
Write(text: string) {
|
||||||
|
if (text.length === 0)
|
||||||
|
return
|
||||||
|
|
||||||
text.split('').forEach((char) => {
|
const width = this.GetWrapWidth()
|
||||||
this.SetCell(char)
|
let row = this.cursorPosition.row
|
||||||
this.MoveCursor(1, 0)
|
let col = this.cursorPosition.col
|
||||||
})
|
const style = this.currentCellStyle
|
||||||
|
|
||||||
|
while (col >= width) {
|
||||||
|
this.EnsureLine(row)
|
||||||
|
this.lineWrapped[row] = true
|
||||||
|
col -= width
|
||||||
|
row += 1
|
||||||
|
}
|
||||||
|
|
||||||
|
this.EnsureLine(row)
|
||||||
|
|
||||||
|
let remaining = text
|
||||||
|
while (remaining.length > 0) {
|
||||||
|
let line = this.lines[row]
|
||||||
|
if (col > line.length)
|
||||||
|
line += ' '.repeat(col - line.length)
|
||||||
|
|
||||||
|
const available = width - col
|
||||||
|
if (available <= 0) {
|
||||||
|
this.lineWrapped[row] = true
|
||||||
|
row += 1
|
||||||
|
col = 0
|
||||||
|
this.EnsureLine(row)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
const chunk = remaining.slice(0, available)
|
||||||
|
if (col === line.length) {
|
||||||
|
line += chunk
|
||||||
|
} else {
|
||||||
|
const prefix = line.slice(0, col)
|
||||||
|
const suffixStart = Math.min(line.length, col + chunk.length)
|
||||||
|
const suffix = line.slice(suffixStart)
|
||||||
|
line = prefix + chunk + suffix
|
||||||
|
}
|
||||||
|
|
||||||
|
this.lines[row] = line
|
||||||
|
this.ApplyStyleRange(row, col, chunk.length, style)
|
||||||
|
this.UpdateLine(row)
|
||||||
|
|
||||||
|
remaining = remaining.slice(chunk.length)
|
||||||
|
col += chunk.length
|
||||||
|
|
||||||
|
if (remaining.length > 0) {
|
||||||
|
this.lineWrapped[row] = true
|
||||||
|
row += 1
|
||||||
|
col = 0
|
||||||
|
this.EnsureLine(row)
|
||||||
|
} else {
|
||||||
|
this.lineWrapped[row] = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
this.cursorPosition.col = Math.max(col, 0)
|
||||||
|
this.cursorPosition.row = Math.max(row, 0)
|
||||||
|
this.UpdateCursor()
|
||||||
}
|
}
|
||||||
|
|
||||||
SetCell(char: string) {
|
SetCell(char: string) {
|
||||||
const selector = `#line-${this.cursorPosition.row} .cell-${this.cursorPosition.col}`
|
const width = this.GetWrapWidth()
|
||||||
|
let row = this.cursorPosition.row
|
||||||
|
let col = this.cursorPosition.col
|
||||||
|
|
||||||
// adjust for the cursor
|
while (col >= width) {
|
||||||
if (!document.querySelector(`#line-${this.cursorPosition.row}`)) {
|
this.EnsureLine(row)
|
||||||
for (let i = this.terminal.children.length - 1; i < this.cursorPosition.row; i++) {
|
this.lineWrapped[row] = true
|
||||||
this.AppendLine()
|
col -= width
|
||||||
}
|
row += 1
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!document.querySelector(selector)) {
|
this.EnsureLine(row)
|
||||||
const line = sqs(`#line-${this.cursorPosition.row}`)
|
|
||||||
|
|
||||||
for (let i = line.children.length; i < this.cursorPosition.col + 1; i++) {
|
let line = this.lines[row]
|
||||||
const cell = document.createElement('span')
|
if (col > line.length)
|
||||||
cell.className = `cell-${i}`
|
line += ' '.repeat(col - line.length)
|
||||||
cell.style.width = `${this.cellWidth}px`
|
|
||||||
cell.style.height = `${this.cellHeight}px`
|
|
||||||
|
|
||||||
line.appendChild(cell)
|
if (col === line.length) {
|
||||||
}
|
line += char[0]
|
||||||
|
} else {
|
||||||
|
line = line.slice(0, col) + char[0] + line.slice(col + 1)
|
||||||
}
|
}
|
||||||
|
|
||||||
sqs(selector).innerText = char[0]
|
this.lines[row] = line
|
||||||
|
this.ApplyStyleRange(row, col, 1, this.currentCellStyle)
|
||||||
|
this.UpdateLine(row)
|
||||||
}
|
}
|
||||||
|
|
||||||
UpdateCells() {
|
SetCellStyle(col: number, row: number, style: string | null) {
|
||||||
const cells = new Array(...sqs(`#line-${this.cursorPosition.row}`).children)
|
if (!Number.isFinite(col) || !Number.isFinite(row))
|
||||||
cells.forEach((cell, i) => cell.className = `cell-${i}`)
|
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) {
|
InsertCell(char: string) {
|
||||||
const cell = document.createElement('span')
|
const width = this.GetWrapWidth()
|
||||||
cell.className = `cell-${this.cursorPosition.col}`
|
let row = this.cursorPosition.row
|
||||||
cell.style.width = `${this.cellWidth}px`
|
let col = this.cursorPosition.col
|
||||||
cell.style.height = `${this.cellHeight}px`
|
|
||||||
|
|
||||||
cell.innerText = char[0]
|
while (col >= width) {
|
||||||
|
this.EnsureLine(row)
|
||||||
|
this.lineWrapped[row] = true
|
||||||
|
col -= width
|
||||||
|
row += 1
|
||||||
|
}
|
||||||
|
|
||||||
sqs(`#line-${this.cursorPosition.row} .cell-${this.cursorPosition.col}`).insertAdjacentElement('beforebegin', cell)
|
this.EnsureLine(row)
|
||||||
|
|
||||||
this.UpdateCells()
|
let line = this.lines[row]
|
||||||
|
if (col > line.length)
|
||||||
|
line += ' '.repeat(col - line.length)
|
||||||
|
|
||||||
|
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)
|
||||||
}
|
}
|
||||||
|
|
||||||
RemoveCell() {
|
RemoveCell() {
|
||||||
try {
|
let row = this.cursorPosition.row
|
||||||
sqs(`#line-${this.cursorPosition.row} .cell-${this.cursorPosition.col - 1}`).remove()
|
let removeIndex = this.cursorPosition.col - 1
|
||||||
} catch (_) {
|
|
||||||
|
|
||||||
} finally {
|
if (removeIndex < 0) {
|
||||||
this.UpdateCells()
|
if (row <= 0 || !this.lineWrapped[row - 1])
|
||||||
|
return
|
||||||
|
|
||||||
|
row -= 1
|
||||||
|
removeIndex = (this.lines[row] ?? '').length - 1
|
||||||
|
if (removeIndex < 0)
|
||||||
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
this.EnsureLine(row)
|
||||||
|
let line = this.lines[row]
|
||||||
|
if (removeIndex >= line.length)
|
||||||
|
return
|
||||||
|
|
||||||
|
line = line.slice(0, removeIndex) + line.slice(removeIndex + 1)
|
||||||
|
this.lines[row] = line
|
||||||
|
this.ApplyRemoveStyle(row, removeIndex)
|
||||||
|
this.UpdateLine(row)
|
||||||
|
this.ReflowFromRow(row)
|
||||||
}
|
}
|
||||||
|
|
||||||
ResetCellSize() {
|
ResetCellSize() {
|
||||||
// dynamically determine cell size using dom
|
// dynamically determine cell size with dom
|
||||||
const cell = document.createElement('span')
|
const cell = document.createElement('span')
|
||||||
cell.textContent = 'A'
|
cell.textContent = 'A'
|
||||||
|
cell.style.position = 'absolute'
|
||||||
|
cell.style.visibility = 'hidden'
|
||||||
|
cell.style.whiteSpace = 'pre'
|
||||||
|
|
||||||
this.terminal.appendChild(cell)
|
this.terminal.appendChild(cell)
|
||||||
|
|
||||||
@@ -145,42 +388,78 @@ export class Terminal {
|
|||||||
}
|
}
|
||||||
|
|
||||||
GetHeightCells(): number {
|
GetHeightCells(): number {
|
||||||
return this.terminal.clientHeight / this.cellHeight
|
const rect = this.terminal.getBoundingClientRect()
|
||||||
|
const height = Math.max(0, document.documentElement.clientHeight - rect.top)
|
||||||
|
return height / this.cellHeight
|
||||||
}
|
}
|
||||||
|
|
||||||
GetWidthCells(): number {
|
GetWidthCells(): number {
|
||||||
return this.terminal.clientWidth / this.cellWidth
|
const rect = this.terminal.getBoundingClientRect()
|
||||||
|
const width = Math.max(0, document.documentElement.clientWidth - rect.left)
|
||||||
|
return width / this.cellWidth
|
||||||
|
}
|
||||||
|
|
||||||
|
private GetWrapWidth(): number {
|
||||||
|
const width = this.GetWidthCells()
|
||||||
|
if (!Number.isFinite(width) || width <= 0)
|
||||||
|
return 1
|
||||||
|
|
||||||
|
return Math.max(1, Math.floor(width))
|
||||||
}
|
}
|
||||||
|
|
||||||
UpdateCursor() {
|
UpdateCursor() {
|
||||||
this.SetCursorStyle(this.cursorStyle)
|
this.SetCursorStyle(this.cursorStyle)
|
||||||
|
|
||||||
this.cursor.style.left = `${this.cursorPosition.col * this.cellWidth + this.terminal.offsetLeft}px `
|
const rect = this.terminal.getBoundingClientRect()
|
||||||
this.cursor.style.top = `${this.cursorPosition.row * this.cellHeight + this.terminal.offsetTop}px`
|
const left = this.GetCursorXOffset() + rect.left + window.scrollX
|
||||||
|
const top = this.cursorPosition.row * this.cellHeight + rect.top + window.scrollY
|
||||||
|
|
||||||
|
this.cursor.style.left = `${left}px`
|
||||||
|
this.cursor.style.top = `${top}px`
|
||||||
}
|
}
|
||||||
|
|
||||||
GetCursorPosition(): CursorPosition {
|
GetCursorPosition(): CursorPosition {
|
||||||
return this.cursorPosition
|
return { col: this.cursorPosition.col, row: this.cursorPosition.row }
|
||||||
}
|
}
|
||||||
|
|
||||||
SetCursorPosition(col: number, row: number) {
|
SetCursorPosition(col: number, row: number) {
|
||||||
this.cursorPosition.col = Math.max(col, 0)
|
const width = this.GetWrapWidth()
|
||||||
|
const clampedCol = Number.isFinite(width) ? Math.min(col, width - 1) : col
|
||||||
|
|
||||||
|
this.cursorPosition.col = Math.max(clampedCol, 0)
|
||||||
this.cursorPosition.row = Math.max(row, 0)
|
this.cursorPosition.row = Math.max(row, 0)
|
||||||
|
|
||||||
try {
|
this.EnsureLine(this.cursorPosition.row)
|
||||||
sqs(`#line-${this.cursorPosition.row} .cell-${this.cursorPosition.col}`)
|
this.UpdateCursor()
|
||||||
} catch (_) {
|
|
||||||
this.SetCell(' ')
|
|
||||||
} finally {
|
|
||||||
this.UpdateCursor()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
MoveCursor(col: number, row: number, absolute: { x: boolean; y: boolean } = { x: false, y: false }) {
|
MoveCursor(col: number, row: number, absolute: { x: boolean; y: boolean } = { x: false, y: false }) {
|
||||||
this.SetCursorPosition(
|
const width = this.GetWrapWidth()
|
||||||
!absolute.x ? this.cursorPosition.col + col : col,
|
let targetCol = !absolute.x ? this.cursorPosition.col + col : col
|
||||||
!absolute.y ? this.cursorPosition.row + row : row,
|
let targetRow = !absolute.y ? this.cursorPosition.row + row : row
|
||||||
)
|
|
||||||
|
if (!absolute.x && col !== 0) {
|
||||||
|
if (targetCol >= width) {
|
||||||
|
const shift = Math.floor(targetCol / width)
|
||||||
|
targetRow += shift
|
||||||
|
targetCol = targetCol % width
|
||||||
|
} else if (targetCol < 0) {
|
||||||
|
while (targetCol < 0 && targetRow > 0) {
|
||||||
|
if (!this.lineWrapped[targetRow - 1]) {
|
||||||
|
targetCol = 0
|
||||||
|
break
|
||||||
|
}
|
||||||
|
|
||||||
|
targetRow -= 1
|
||||||
|
targetCol += width
|
||||||
|
}
|
||||||
|
|
||||||
|
if (targetCol < 0)
|
||||||
|
targetCol = 0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
this.SetCursorPosition(targetCol, targetRow)
|
||||||
}
|
}
|
||||||
|
|
||||||
SetCursorStyle(style: CursorStyle) {
|
SetCursorStyle(style: CursorStyle) {
|
||||||
@@ -190,4 +469,377 @@ export class Terminal {
|
|||||||
this.cursor.style.height = `${this.cellHeight}px`
|
this.cursor.style.height = `${this.cellHeight}px`
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private EnsureLine(row: number) {
|
||||||
|
let added = false
|
||||||
|
|
||||||
|
while (this.lineElements.length <= row) {
|
||||||
|
const paragraph = document.createElement('p')
|
||||||
|
paragraph.style.height = `${this.cellHeight}px`
|
||||||
|
paragraph.id = `line-${this.lineElements.length}`
|
||||||
|
paragraph.className = 'line'
|
||||||
|
|
||||||
|
this.terminal.appendChild(paragraph)
|
||||||
|
this.lineElements.push(paragraph)
|
||||||
|
this.lines.push('')
|
||||||
|
this.lineWrapped.push(false)
|
||||||
|
added = true
|
||||||
|
}
|
||||||
|
|
||||||
|
if (added)
|
||||||
|
this.ScheduleScroll()
|
||||||
|
}
|
||||||
|
|
||||||
|
private UpdateLine(row: number) {
|
||||||
|
const line = this.lineElements[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) {
|
||||||
|
const width = this.GetWrapWidth()
|
||||||
|
if (width <= 0)
|
||||||
|
return
|
||||||
|
|
||||||
|
this.EnsureLine(startRow)
|
||||||
|
|
||||||
|
let text = this.lines[startRow] ?? ''
|
||||||
|
let endRow = startRow
|
||||||
|
|
||||||
|
while (this.lineWrapped[endRow]) {
|
||||||
|
endRow += 1
|
||||||
|
if (endRow >= this.lines.length)
|
||||||
|
break
|
||||||
|
|
||||||
|
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.lineWrapped[row] = false
|
||||||
|
row += 1
|
||||||
|
} else {
|
||||||
|
while (index < text.length) {
|
||||||
|
const chunk = text.slice(index, index + width)
|
||||||
|
this.lines[row] = chunk
|
||||||
|
this.lineWrapped[row] = index + width < text.length
|
||||||
|
|
||||||
|
row += 1
|
||||||
|
index += width
|
||||||
|
|
||||||
|
if (index < text.length)
|
||||||
|
this.EnsureLine(row)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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.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 {
|
||||||
|
const row = this.cursorPosition.row
|
||||||
|
const col = this.cursorPosition.col
|
||||||
|
const line = this.lineElements[row]
|
||||||
|
const text = this.lines[row] ?? ''
|
||||||
|
|
||||||
|
if (!line)
|
||||||
|
return col * this.cellWidth
|
||||||
|
|
||||||
|
const textLength = text.length
|
||||||
|
const clamped = Math.min(col, textLength)
|
||||||
|
let width = 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) {
|
||||||
|
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 => {
|
||||||
|
line.style.height = `${this.cellHeight}px`
|
||||||
|
})
|
||||||
|
this.UpdateCursor()
|
||||||
|
}
|
||||||
|
|
||||||
|
private CreateMetricsRefreshListener() {
|
||||||
|
if ('fonts' in document) {
|
||||||
|
document.fonts.ready.then(() => {
|
||||||
|
this.RefreshMetrics()
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
window.addEventListener('resize', () => this.RefreshMetrics())
|
||||||
|
}
|
||||||
|
|
||||||
|
private ScheduleScroll() {
|
||||||
|
if (this.scrollPending)
|
||||||
|
return
|
||||||
|
|
||||||
|
this.scrollPending = true
|
||||||
|
requestAnimationFrame(() => {
|
||||||
|
this.scrollPending = false
|
||||||
|
|
||||||
|
const lastLine = this.lineElements[this.lineElements.length - 1]
|
||||||
|
if (lastLine)
|
||||||
|
lastLine.scrollIntoView({ block: 'end' })
|
||||||
|
})
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user