T11: terminal canvas, keyboard toolbar, settings

TerminalSession:
- shell integration: ensureShell() opens PTY+shell with emulator created
  first (renderable during handshake); channel onClose -> CLOSED
- I/O API: sendBytes/sendText/sendKey (DECCKM-aware)/sendPaste
  (bracketed-paste aware); resizeTerminal -> emulator.resize + pty
  window-change; OSC 0/2 title wins over label; inputVersion counter
  lets the canvas snap back to live view on any user input

TerminalCanvas:
- full-area Canvas renderer; cell size from measureText('M')
- merged style runs (one fillText per run), wide-cell 2-cell spans
- dirty-row incremental redraw live, full redraw while scrolled back
- block/underline cursor, always visible on alternate screen
- xterm-256 palette + truecolor + reverse/dim/bold/italic/underline/strike
- pinch zoom 6-30vp with persisted setting; PTY resize on relayout
- touch: SGR mouse reports in mouse mode, else scrollback drag + tap
  focuses the hidden 1px IME anchor TextInput

KeyboardToolbar (Haven default two-row layout):
- Row1: snippets/keyboard/Esc/Tab/Paste/Text///Home/Up/End/PgUp
- Row2: Shift/Ctrl/Alt/arrows/PgDn/|/~/\backslash/`
- sticky modifiers: one-shot tap, double-tap lock (bordered), consume
  on dispatch; Ctrl+symbol via ch & 0x1f; Alt prefixes ESC

TerminalPage:
- READY body mounts canvas + toolbar + whole-line text input overlay
  (CJK path) + snippet macro panel (^C ^D ^Z ^L ^A ^E ^W ^U Shift-Tab)
- soft-keyboard toggle via FocusController on the hidden IME anchor

SettingsPage:
- color scheme picker with live preview blocks (4 schemes)
- font size slider 6-30vp, keep-screen-on toggle (window API)
- about (AGPL-3.0 + upstream attribution), diagnostics entry
This commit is contained in:
STRIX
2026-09-08 18:48:25 +08:00
parent 72a4e127e3
commit 6aed2f3634
5 changed files with 1455 additions and 37 deletions
@@ -14,8 +14,12 @@
import { AuthMethod } from '../data/Models'; import { AuthMethod } from '../data/Models';
import type { ClientPrivateKey } from '../ssh/Auth'; import type { ClientPrivateKey } from '../ssh/Auth';
import { SshSession, SshSessionState } from '../ssh/SshSession'; import { SshSession, SshSessionState } from '../ssh/SshSession';
import type { SshChannel } from '../ssh/Channel';
import type { SshSessionOptions } from '../ssh/SshSession'; import type { SshSessionOptions } from '../ssh/SshSession';
import type { HostKeyDecision, HostKeyPrompt, KnownHostStore } from '../ssh/HostKeyVerifier'; import type { HostKeyDecision, HostKeyPrompt, KnownHostStore } from '../ssh/HostKeyVerifier';
import { TerminalEmulator } from '../vterm/TerminalEmulator';
import { encodeKey, encodePaste, encodeText } from '../vterm/VtInput';
import { VtKey } from '../vterm/VtInput';
import { Log } from '../common/Log'; import { Log } from '../common/Log';
/** High-level lifecycle of one interactive SSH connection attempt. */ /** High-level lifecycle of one interactive SSH connection attempt. */
@@ -74,6 +78,12 @@ export class TerminalSession {
private passwordOverride: string | null = null; private passwordOverride: string | null = null;
private pendingRemember: boolean = false; private pendingRemember: boolean = false;
private ssh: SshSession | null = null; private ssh: SshSession | null = null;
private channel: SshChannel | null = null;
private emulator: TerminalEmulator | null = null;
private shellPending: boolean = false;
private oscTitle: string = '';
private dataListeners: Array<() => void> = [];
private inputVersion: number = 0;
constructor(id: number, spec: ConnectSpec, deps: SessionDeps) { constructor(id: number, spec: ConnectSpec, deps: SessionDeps) {
this.id = id; this.id = id;
@@ -111,6 +121,9 @@ export class TerminalSession {
} }
getTitle(): string { getTitle(): string {
if (this.oscTitle.length > 0) {
return this.oscTitle;
}
if (this.spec.label.length > 0) { if (this.spec.label.length > 0) {
return this.spec.label; return this.spec.label;
} }
@@ -153,10 +166,158 @@ export class TerminalSession {
} }
} }
// ------------------------------------------------------------ terminal I/O
/** VT emulator backing this session's screen; null before the shell opens. */
getEmulator(): TerminalEmulator | null {
return this.emulator;
}
/** Register for per-packet screen updates; returns the unsubscribe fn. */
addDataListener(listener: () => void): () => void {
this.dataListeners.push(listener);
return (): void => {
const idx: number = this.dataListeners.indexOf(listener);
if (idx >= 0) {
this.dataListeners.splice(idx, 1);
}
};
}
/**
* Open the interactive shell with the requested PTY size. No-op unless the
* session is READY and no shell exists yet. The emulator is created first
* so the UI can render into it even while the shell handshake completes.
*/
ensureShell(cols: number, rows: number): void {
const ssh: SshSession | null = this.ssh;
if (ssh === null || this.state !== SessionState.READY ||
this.emulator !== null || this.shellPending || cols < 2 || rows < 2) {
return;
}
this.shellPending = true;
const emu: TerminalEmulator = new TerminalEmulator(cols, rows,
(data: Uint8Array): void => {
const ch: SshChannel | null = this.channel;
if (ch !== null) {
ch.write(data).catch((e: Object): void => {
Log.warn(TerminalSession.TAG, `write failed: ${(e as Error).message}`);
});
}
});
emu.onTitle = (title: string): void => {
this.oscTitle = title;
this.deps.onStateChange(this);
};
this.emulator = emu;
const feed = (data: Uint8Array): void => {
if (this.emulator === emu) {
emu.feed(data);
this.notifyData();
}
};
const shellClosed = (): void => {
if (this.emulator === emu && this.state === SessionState.READY) {
this.closeReason = '会话已结束';
this.disposeSsh();
this.state = SessionState.CLOSED;
this.deps.onStateChange(this);
Log.info(TerminalSession.TAG, `session #${this.id} shell exited`);
}
};
ssh.openShell(cols, rows, feed, feed, shellClosed)
.then((ch: SshChannel): void => {
this.shellPending = false;
if (this.ssh === ssh && this.emulator === emu && this.state === SessionState.READY) {
this.channel = ch;
this.notifyData();
} else {
ch.close().catch((): void => {
});
}
})
.catch((e: Object): void => {
this.shellPending = false;
if (this.ssh === ssh && this.emulator === emu && this.state === SessionState.READY) {
Log.error(TerminalSession.TAG, `openShell failed: ${(e as Error).message}`);
this.emulator = null;
this.failStale(ssh, friendlyError((e as Error).message));
}
});
}
/** Resize the emulator and forward window-change to the PTY. */
resizeTerminal(cols: number, rows: number): void {
const emu: TerminalEmulator | null = this.emulator;
if (emu === null || cols < 2 || rows < 2) {
return;
}
if (emu.getCols() !== cols || emu.getRows() !== rows) {
emu.resize(cols, rows);
const ch: SshChannel | null = this.channel;
if (ch !== null) {
ch.resize(cols, rows).catch((e: Object): void => {
Log.warn(TerminalSession.TAG, `pty resize failed: ${(e as Error).message}`);
});
}
this.notifyData();
}
}
/** Raw bytes straight to the channel (mouse reports, control codes). */
sendBytes(data: Uint8Array): void {
this.inputVersion++;
const ch: SshChannel | null = this.channel;
if (ch !== null) {
ch.write(data).catch((e: Object): void => {
Log.warn(TerminalSession.TAG, `write failed: ${(e as Error).message}`);
});
}
}
/** Monotonic counter of user-input events; the canvas resets scroll on change. */
getInputVersion(): number {
return this.inputVersion;
}
/** UTF-8 text as typed input. */
sendText(text: string): void {
if (text.length > 0) {
this.sendBytes(encodeText(text));
}
}
/** Functional key with modifiers (arrows, nav keys; DECCKM-aware). */
sendKey(key: VtKey, mods: number): void {
const appMode: boolean = this.emulator !== null && this.emulator.isCursorAppMode();
this.sendBytes(encodeKey(key, mods, appMode));
}
/** Paste text, honoring the app's bracketed-paste mode. */
sendPaste(text: string): void {
if (text.length === 0) {
return;
}
const bracketed: boolean = this.emulator !== null && this.emulator.isBracketedPaste();
this.sendBytes(encodePaste(text, bracketed));
}
/** True while a one-shot Shift is armed (toolbar coordinates its own state). */
isReadyForInput(): boolean {
return this.state === SessionState.READY;
}
private notifyData(): void {
for (let i: number = 0; i < this.dataListeners.length; i++) {
this.dataListeners[i]();
}
}
// ---------------------------------------------------------------- private // ---------------------------------------------------------------- private
private async attempt(): Promise<void> { private async attempt(): Promise<void> {
this.disposeSsh(); this.disposeSsh();
this.oscTitle = '';
const ssh: SshSession = new SshSession(this.buildSshOptions()); const ssh: SshSession = new SshSession(this.buildSshOptions());
this.ssh = ssh; this.ssh = ssh;
this.setState(SessionState.CONNECTING); this.setState(SessionState.CONNECTING);
@@ -290,6 +451,9 @@ export class TerminalSession {
private disposeSsh(): void { private disposeSsh(): void {
const ssh: SshSession | null = this.ssh; const ssh: SshSession | null = this.ssh;
this.ssh = null; this.ssh = null;
this.channel = null;
this.emulator = null;
this.shellPending = false;
if (ssh !== null) { if (ssh !== null) {
ssh.close(); ssh.close();
} }
+243
View File
@@ -0,0 +1,243 @@
/*
* Copyright (c) 2026 Haven for HarmonyOS contributors.
* Port of Haven by GlassHaven (AGPL-3.0). See LICENSE.
*
* T11: two-row soft-key toolbar (plan §5 KeyboardToolbar, aligned with
* Haven's default ToolbarLayout):
*
* Row 1: ✂ ⌨ Esc Tab Paste Text / Home ↑ End PgUp
* Row 2: Shift Ctrl Alt ← ↓ → PgDn | ~ / \ `
*
* Sticky modifiers (Haven semantics): Ctrl/Alt tap = arm for one key,
* double-tap = lock (bordered), tap again = release. Shift is one-shot.
* Any dispatch consumes one-shot modifiers; locks survive.
*/
import { VtKey, VtModifier } from '../vterm/VtInput';
/** Max gap (ms) between taps that counts as a double-tap lock. */
const DOUBLE_TAP_MS: number = 350;
/** One toolbar key: text label, tap handler, modifier tint states. */
@Component
struct ToolbarKey {
label: string = '';
active: boolean = false;
locked: boolean = false;
onTap?: () => void = (): void => {
};
build() {
Text(this.label)
.fontSize(this.label.length > 3 ? 10 : 13)
.fontWeight(this.active ? FontWeight.Bold : FontWeight.Medium)
.fontColor(this.active ? '#FFFFFF' : '#4A4A4A')
.textAlign(TextAlign.Center)
.height(32)
.constraintSize({ minWidth: 38 })
.padding({ left: 7, right: 7 })
.backgroundColor(this.active ? '#0A59F7' : '#F0F1F3')
.borderRadius(8)
.border({
width: this.locked ? 2 : 0,
color: this.locked ? '#7C3AED' : Color.Transparent
})
.margin({ left: 3, right: 3 })
.onClick((): void => {
this.onTap?.();
})
}
}
@Component
export struct KeyboardToolbar {
/** Plain text / control-byte sequences (ESC, Tab, snippets, symbols). */
onSendText?: (text: string) => void = (): void => {
};
/** Functional keys with the toolbar's armed modifiers (DECCKM-aware). */
onSendKey?: (key: VtKey, mods: number) => void = (): void => {
};
/** Read the clipboard and paste into the session. */
onPaste?: () => void = (): void => {
};
/** Toggle the soft keyboard. */
onToggleKeyboard?: () => void = (): void => {
};
/** Open the snippet macro panel. */
onOpenSnippets?: () => void = (): void => {
};
/** Open the whole-line text input overlay. */
onOpenTextInput?: () => void = (): void => {
};
@State ctrlActive: boolean = false;
@State ctrlLocked: boolean = false;
@State altActive: boolean = false;
@State altLocked: boolean = false;
@State shiftActive: boolean = false;
private lastCtrlClick: number = 0;
private lastAltClick: number = 0;
// -------------------------------------------------------------- modifiers
private armedMods(): number {
let mods: number = VtModifier.NONE;
if (this.shiftActive) {
mods |= VtModifier.SHIFT;
}
if (this.ctrlActive) {
mods |= VtModifier.CTRL;
}
if (this.altActive) {
mods |= VtModifier.ALT;
}
return mods;
}
private tapCtrl(): void {
const now: number = Date.now();
if (this.ctrlLocked) {
this.ctrlLocked = false;
this.ctrlActive = false;
} else if (now - this.lastCtrlClick < DOUBLE_TAP_MS) {
this.ctrlLocked = true;
this.ctrlActive = true;
} else {
this.ctrlActive = true;
}
this.lastCtrlClick = now;
}
private tapAlt(): void {
const now: number = Date.now();
if (this.altLocked) {
this.altLocked = false;
this.altActive = false;
} else if (now - this.lastAltClick < DOUBLE_TAP_MS) {
this.altLocked = true;
this.altActive = true;
} else {
this.altActive = true;
}
this.lastAltClick = now;
}
/** Consume one-shot modifiers after a dispatch; locks stay armed. */
private consumeModifiers(): void {
this.shiftActive = false;
if (!this.ctrlLocked) {
this.ctrlActive = false;
}
if (!this.altLocked) {
this.altActive = false;
}
}
// -------------------------------------------------------------- dispatch
/**
* Send a symbol (possibly with armed Ctrl/Alt). Ctrl maps via
* `ch & 0x1f` (so Ctrl+/ = ^_, Ctrl+\ = ^\, ...); Alt prefixes ESC.
*/
private sendSymbol(ch: string): void {
const ctrl: boolean = this.ctrlActive && ch.length === 1 && ch.charCodeAt(0) < 0x80;
const ctrlByte: number = ctrl ? (ch.charCodeAt(0) & 0x1f) : 0;
if (ctrl && ctrlByte === 0) {
// Ctrl+` and friends have no encoding — fall through as plain text.
this.sendPlain(ch);
return;
}
let text: string = ctrl ? String.fromCharCode(ctrlByte) : ch;
if (this.altActive) {
text = '\u001b' + text;
}
this.onSendText?.(text);
this.consumeModifiers();
}
private sendPlain(text: string): void {
this.onSendText?.(text);
this.consumeModifiers();
}
private sendNav(key: VtKey): void {
this.onSendKey?.(key, this.armedMods());
this.consumeModifiers();
}
// -------------------------------------------------------------- build
build() {
Column({ space: 2 }) {
Scroll() {
Row({ space: 0 }) {
ToolbarKey({ label: '✂', onTap: (): void => this.onOpenSnippets?.() })
ToolbarKey({ label: '⌨', onTap: (): void => this.onToggleKeyboard?.() })
ToolbarKey({ label: 'Esc', onTap: (): void => this.sendPlain('\u001b') })
ToolbarKey({
label: 'Tab',
active: this.shiftActive,
onTap: (): void => {
if (this.shiftActive) {
this.onSendKey?.(VtKey.TAB, VtModifier.SHIFT);
this.consumeModifiers();
} else {
this.sendPlain('\t');
}
}
})
ToolbarKey({ label: 'Paste', onTap: (): void => this.onPaste?.() })
ToolbarKey({ label: 'Text', onTap: (): void => this.onOpenTextInput?.() })
ToolbarKey({ label: '/', onTap: (): void => this.sendSymbol('/') })
ToolbarKey({ label: 'Home', onTap: (): void => this.sendNav(VtKey.HOME) })
ToolbarKey({ label: '↑', onTap: (): void => this.sendNav(VtKey.UP) })
ToolbarKey({ label: 'End', onTap: (): void => this.sendNav(VtKey.END) })
ToolbarKey({ label: 'PgUp', onTap: (): void => this.sendNav(VtKey.PAGE_UP) })
}
.padding({ left: 4, right: 4 })
}
.scrollable(ScrollDirection.Horizontal)
.scrollBar(BarState.Off)
.width('100%')
Scroll() {
Row({ space: 0 }) {
ToolbarKey({
label: 'Shift',
active: this.shiftActive,
onTap: (): void => {
this.shiftActive = !this.shiftActive;
}
})
ToolbarKey({
label: 'Ctrl',
active: this.ctrlActive,
locked: this.ctrlLocked,
onTap: (): void => this.tapCtrl()
})
ToolbarKey({
label: 'Alt',
active: this.altActive,
locked: this.altLocked,
onTap: (): void => this.tapAlt()
})
ToolbarKey({ label: '←', onTap: (): void => this.sendNav(VtKey.LEFT) })
ToolbarKey({ label: '↓', onTap: (): void => this.sendNav(VtKey.DOWN) })
ToolbarKey({ label: '→', onTap: (): void => this.sendNav(VtKey.RIGHT) })
ToolbarKey({ label: 'PgDn', onTap: (): void => this.sendNav(VtKey.PAGE_DOWN) })
ToolbarKey({ label: '|', onTap: (): void => this.sendSymbol('|') })
ToolbarKey({ label: '~', onTap: (): void => this.sendSymbol('~') })
ToolbarKey({ label: '\\', onTap: (): void => this.sendSymbol('\\') })
ToolbarKey({ label: '`', onTap: (): void => this.sendSymbol('`') })
}
.padding({ left: 4, right: 4 })
}
.scrollable(ScrollDirection.Horizontal)
.scrollBar(BarState.Off)
.width('100%')
}
.width('100%')
.padding({ top: 2, bottom: 2 })
.backgroundColor('#FFFFFF')
}
}
+210 -10
View File
@@ -2,13 +2,124 @@
* Copyright (c) 2026 Haven for HarmonyOS contributors. * Copyright (c) 2026 Haven for HarmonyOS contributors.
* Port of Haven by GlassHaven (AGPL-3.0). See LICENSE. * Port of Haven by GlassHaven (AGPL-3.0). See LICENSE.
* *
* T9: settings placeholder — real settings (font size, color scheme, * T11: settings — default color scheme (with live preview blocks),
* keepalive, background task) arrive with the terminal stage. The * default terminal font size (6-30vp slider), keep-screen-on toggle,
* diagnostics page stays reachable here. * about (AGPL-3.0 / upstream attribution) and the diagnostics entry.
*/ */
import { window } from '@kit.ArkUI';
import { common } from '@kit.AbilityKit';
import { SettingsRepository, FONT_SIZE_MAX, FONT_SIZE_MIN } from '../data/SettingsRepository';
import { COLOR_SCHEMES } from '../vterm/ColorSchemes';
import type { TerminalColorScheme } from '../vterm/ColorSchemes';
function rgbToCss(rgb: number): string {
const s: string = (rgb & 0xffffff).toString(16);
const padded: string = s.length >= 6 ? s : '000000'.substring(0, 6 - s.length) + s;
return `#${padded}`;
}
@Component @Component
export struct SettingsPage { export struct SettingsPage {
@State schemeName: string = 'Haven';
@State fontSizeVp: number = 14;
@State keepScreenOn: boolean = false;
private settings: SettingsRepository | null = null;
aboutToAppear(): void {
const context: common.Context | undefined = this.getUIContext().getHostContext();
if (context === undefined) {
return;
}
this.settings = SettingsRepository.getInstance(context);
this.schemeName = this.settings.getDefaultColorScheme();
this.fontSizeVp = this.settings.getFontSize();
this.keepScreenOn = this.settings.getKeepScreenOn();
if (this.keepScreenOn) {
this.applyKeepScreenOn(true);
}
}
private applyKeepScreenOn(on: boolean): void {
const context: common.Context | undefined = this.getUIContext().getHostContext();
if (context === undefined) {
return;
}
window.getLastWindow(context).then((win: window.Window): void => {
win.setWindowKeepScreenOn(on).catch((): void => {
});
}).catch((): void => {
});
}
private pickScheme(scheme: TerminalColorScheme): void {
this.schemeName = scheme.name;
this.settings?.setDefaultColorScheme(scheme.name).catch((): void => {
});
}
private pickFontSize(sizeVp: number): void {
this.fontSizeVp = sizeVp;
this.settings?.setFontSize(sizeVp).catch((): void => {
});
}
private toggleKeepScreenOn(on: boolean): void {
this.keepScreenOn = on;
this.applyKeepScreenOn(on);
this.settings?.setKeepScreenOn(on).catch((): void => {
});
}
// ---------------------------------------------------------------- builders
@Builder
schemePreview(scheme: TerminalColorScheme) {
// Background + foreground sample + the first four ANSI colors.
Row({ space: 3 }) {
ForEach(scheme.ansi.slice(0, 4), (color: number) => {
Circle({ width: 12, height: 12 })
.fill(rgbToCss(color))
}, (color: number) => color.toString())
}
.padding({ left: 6, right: 6, top: 5, bottom: 5 })
.backgroundColor(rgbToCss(scheme.background))
.borderRadius(6)
}
@Builder
schemeCard(scheme: TerminalColorScheme) {
Column({ space: 8 }) {
this.schemePreview(scheme)
Text(scheme.name)
.fontSize(12)
.fontColor(scheme.name === this.schemeName ? '#0A59F7' : '#333333')
.fontWeight(scheme.name === this.schemeName ? FontWeight.Bold : FontWeight.Normal)
}
.padding(10)
.borderRadius(12)
.backgroundColor(scheme.name === this.schemeName ? '#E8F1FF' : '#FFFFFF')
.border({
width: scheme.name === this.schemeName ? 2 : 1,
color: scheme.name === this.schemeName ? '#0A59F7' : '#E5E5E5'
})
.onClick((): void => {
this.pickScheme(scheme);
})
}
@Builder
sectionTitle(title: string) {
Text(title)
.fontSize(14)
.fontWeight(FontWeight.Medium)
.fontColor('#333333')
.width('100%')
}
// ---------------------------------------------------------------- build
build() { build() {
Column() { Column() {
Text('设置') Text('设置')
@@ -17,27 +128,116 @@ export struct SettingsPage {
.width('100%') .width('100%')
.padding({ left: 20, right: 20, top: 16 }) .padding({ left: 20, right: 20, top: 16 })
Column({ space: 12 }) { Scroll() {
Text('设置项将在终端阶段开放') Column({ space: 16 }) {
.fontSize(15) // ------------------------------------------------ default scheme
.fontColor('#8C8C8C') Column({ space: 10 }) {
this.sectionTitle('默认配色')
Flex({ wrap: FlexWrap.Wrap }) {
ForEach(COLOR_SCHEMES, (scheme: TerminalColorScheme) => {
this.schemeCard(scheme)
}, (scheme: TerminalColorScheme) => scheme.name)
} }
.width('100%') .width('100%')
}
.width('100%')
.padding(16)
.backgroundColor('#FFFFFF')
.borderRadius(14)
// ------------------------------------------------- default font
Column({ space: 10 }) {
this.sectionTitle('默认字号')
Row({ space: 12 }) {
Text('A')
.fontSize(10)
.fontColor('#8C8C8C')
Slider({
value: this.fontSizeVp,
min: FONT_SIZE_MIN,
max: FONT_SIZE_MAX,
step: 1,
style: SliderStyle.OutSet
})
.layoutWeight(1) .layoutWeight(1)
.justifyContent(FlexAlign.Center) .selectedColor('#0A59F7')
.onChange((value: number, mode: SliderChangeMode): void => {
if (mode === SliderChangeMode.End || mode === SliderChangeMode.Click) {
this.pickFontSize(Math.round(value));
}
})
Text(`${this.fontSizeVp} vp`)
.fontSize(13)
.fontColor('#0A59F7')
.width(48)
.textAlign(TextAlign.End)
}
.width('100%')
}
.width('100%')
.padding(16)
.backgroundColor('#FFFFFF')
.borderRadius(14)
// ---------------------------------------------- keep screen on
Row({ space: 8 }) {
Text('屏幕常亮')
.fontSize(15)
.fontColor('#333333')
.layoutWeight(1)
Toggle({ type: ToggleType.Switch, isOn: this.keepScreenOn })
.selectedColor('#0A59F7')
.onChange((isOn: boolean): void => {
this.toggleKeepScreenOn(isOn);
})
}
.width('100%')
.padding(16)
.backgroundColor('#FFFFFF')
.borderRadius(14)
// -------------------------------------------------------- about
Column({ space: 8 }) {
this.sectionTitle('关于')
Text('Haven for HarmonyOS 0.1.0')
.fontSize(13)
.fontColor('#666666')
.width('100%')
Text('基于 Haven(GlassHaven)移植,遵循 AGPL-3.0 开源协议。' +
'SSH 协议栈与 VT 终端模拟器为纯 TypeScript 实现,运行于应用内。')
.fontSize(12)
.fontColor('#8C8C8C')
.width('100%')
Text('本程序为自由软件:你可以依据 Free Software Foundation 发布的 ' +
'GNU Affero General Public License(第 3 版或任意更新版本)重新发布或修改它。')
.fontSize(12)
.fontColor('#8C8C8C')
.width('100%')
}
.width('100%')
.padding(16)
.backgroundColor('#FFFFFF')
.borderRadius(14)
.alignItems(HorizontalAlign.Start)
Button('打开诊断页') Button('打开诊断页')
.width('60%') .width('100%')
.height(44) .height(44)
.fontSize(14) .fontSize(14)
.backgroundColor('#FFFFFF') .backgroundColor('#FFFFFF')
.fontColor('#0A59F7') .fontColor('#0A59F7')
.margin({ bottom: 32 })
.onClick((): void => { .onClick((): void => {
this.getUIContext().getRouter().pushUrl({ url: 'pages/DiagPage' }); this.getUIContext().getRouter().pushUrl({ url: 'pages/DiagPage' });
}) })
} }
.width('100%') .width('100%')
.padding({ left: 16, right: 16, top: 12, bottom: 32 })
}
.layoutWeight(1)
.scrollBar(BarState.Off)
.width('100%')
}
.width('100%')
.height('100%') .height('100%')
.backgroundColor('#F7F8FA') .backgroundColor('#F7F8FA')
} }
+596
View File
@@ -0,0 +1,596 @@
/*
* Copyright (c) 2026 Haven for HarmonyOS contributors.
* Port of Haven by GlassHaven (AGPL-3.0). See LICENSE.
*
* T11: full-screen terminal renderer (plan §5 TerminalCanvas).
*
* - Canvas fills the session area; cell size comes from measuring 'M'.
* - Rows render as merged style-runs (one fillText per run).
* - Dirty-row incremental redraw while live; full redraw while scrolled
* back or after font/size/scheme changes.
* - Block/underline cursor (always visible on the alternate screen).
* - Pinch zooms the font (clamped 6-30vp) and resizes the PTY.
* - Touch: SGR mouse events when the app enables mouse mode, otherwise
* vertical drag scrolls the scrollback and a tap focuses the IME.
* - A hidden 1px TextInput keeps soft-keyboard focus; hardware keys and
* IME text arrive through onChange/onSubmit.
*/
import { SessionManager } from '../session/SessionManager';
import type { TerminalSession } from '../session/TerminalSession';
import { ATTR_BLINK, ATTR_BOLD, ATTR_DIM, ATTR_ITALIC, ATTR_REVERSE, ATTR_STRIKE, ATTR_UNDERLINE, ATTR_WIDE, ATTR_WIDE_CONT, COLOR_DEFAULT, isTruecolor, truecolorRgb } from '../vterm/TerminalBuffer';
import type { VtCell } from '../vterm/TerminalBuffer';
import type { TerminalEmulator } from '../vterm/TerminalEmulator';
import type { TerminalBuffer } from '../vterm/TerminalBuffer';
import { COLOR_SCHEMES, schemeByName } from '../vterm/ColorSchemes';
import type { TerminalColorScheme } from '../vterm/ColorSchemes';
import { encodeMouseSgr, MOUSE_BTN_LEFT, MOUSE_BTN_RELEASE, MOUSE_MOTION_FLAG, MOUSE_WHEEL_UP, MOUSE_WHEEL_DOWN } from '../vterm/VtInput';
const MIN_FONT_VP: number = 6;
const MAX_FONT_VP: number = 30;
const FONT_FAMILY: string = 'monospace';
const LINE_HEIGHT_RATIO: number = 1.35;
/** 6x6x6 color cube levels for xterm-256 indices 16..231. */
const CUBE_LEVELS: number[] = [0, 95, 135, 175, 215, 255];
function clamp(v: number, lo: number, hi: number): number {
return v < lo ? lo : (v > hi ? hi : v);
}
/** xterm-256 palette index (16..255) to 0x00RRGGBB. */
function ansi256Rgb(index: number): number {
if (index < 16) {
return 0x000000;
}
if (index <= 231) {
const c: number = index - 16;
const r: number = CUBE_LEVELS[Math.floor(c / 36) % 6];
const g: number = CUBE_LEVELS[Math.floor(c / 6) % 6];
const b: number = CUBE_LEVELS[c % 6];
return (r << 16) | (g << 8) | b;
}
const gray: number = 8 + (index - 232) * 10;
return (gray << 16) | (gray << 8) | gray;
}
function rgbToCss(rgb: number): string {
const s: string = (rgb & 0xffffff).toString(16);
const padded: string = s.length >= 6 ? s : '000000'.substring(0, 6 - s.length) + s;
return `#${padded}`;
}
@Component
export struct TerminalCanvas {
/** Active session id; change re-binds the canvas to another session. */
@Prop @Watch('onSessionIdChanged') sessionId: number = -1;
/** Color scheme name (vterm ColorSchemes); change re-resolves and repaints. */
@Prop @Watch('onStyleChanged') schemeName: string = 'Haven';
/** Base font size in vp; the user's pinch zoom reports back through the callback. */
@Prop @Watch('onStyleChanged') fontSizeVp: number = 14;
/** Persist a pinch-zoomed font size (clamped 6..30). */
onFontSizeChange?: (sizeVp: number) => void = (): void => {
};
/** Soft keyboard appeared/disappeared around the hidden IME anchor. */
onImeFocusChanged?: (focused: boolean) => void = (): void => {
};
private session: TerminalSession | null = null;
private paintSettings: RenderingContextSettings = new RenderingContextSettings(true);
private ctx: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.paintSettings);
@State imeText: string = '';
private cellW: number = 0;
private cellH: number = 0;
private fontPx: number = 0;
private canvasW: number = 0;
private canvasH: number = 0;
private cols: number = 0;
private rows: number = 0;
private scrollOffset: number = 0;
private fullDirty: boolean = true;
private renderPending: boolean = false;
private lastCursorRow: number = -1;
private lastCursorCol: number = -1;
private lastCursorVisible: boolean = false;
private lastInputVersion: number = -1;
private scheme: TerminalColorScheme = COLOR_SCHEMES[0];
private bgCss: string = '#1A1A2E';
private fgCss: string = '#00E676';
private cursorCss: string = '#00E676';
private ansiCss: string[] = [];
private ansi256Cache: string[] = [];
private unsubData: (() => void) | null = null;
private touchStartY: number = 0;
private touchMoved: boolean = false;
private scrollAtTouch: number = 0;
private mouseDown: boolean = false;
private pinchBaseFont: number = 14;
aboutToAppear(): void {
this.resolveSession();
this.applyScheme(this.schemeName);
}
aboutToDisappear(): void {
this.releaseSession();
}
// ------------------------------------------------------------------ binding
private onSessionIdChanged(): void {
this.releaseSession();
this.resolveSession();
this.scrollOffset = 0;
this.fullDirty = true;
this.scheduleRender();
}
private onStyleChanged(): void {
this.applyScheme(this.schemeName);
this.remeasure();
this.fullDirty = true;
this.scheduleRender();
}
private resolveSession(): void {
const s: TerminalSession | null = SessionManager.getInstance().get(this.sessionId);
this.session = s;
if (s !== null) {
this.unsubData = s.addDataListener((): void => {
this.scheduleRender();
});
}
}
private releaseSession(): void {
if (this.unsubData !== null) {
this.unsubData();
this.unsubData = null;
}
this.session = null;
}
private applyScheme(name: string): void {
this.scheme = schemeByName(name);
this.bgCss = rgbToCss(this.scheme.background);
this.fgCss = rgbToCss(this.scheme.foreground);
this.cursorCss = rgbToCss(this.scheme.cursor);
this.ansiCss = [];
for (let i: number = 0; i < this.scheme.ansi.length; i++) {
this.ansiCss.push(rgbToCss(this.scheme.ansi[i]));
}
}
// ------------------------------------------------------------------ metrics
private remeasure(): void {
this.fontPx = vp2px(this.fontSizeVp);
this.ctx.font = `${this.fontPx}px ${FONT_FAMILY}`;
const tm: TextMetrics = this.ctx.measureText('M');
this.cellW = tm.width > 0 ? tm.width : this.fontPx * 0.6;
this.cellH = Math.round(this.fontPx * LINE_HEIGHT_RATIO);
}
private relayout(widthVp: number, heightVp: number): void {
this.canvasW = vp2px(widthVp);
this.canvasH = vp2px(heightVp);
this.remeasure();
const newCols: number = Math.max(2, Math.floor(this.canvasW / this.cellW));
const newRows: number = Math.max(2, Math.floor(this.canvasH / this.cellH));
if (newCols === this.cols && newRows === this.rows) {
return;
}
this.cols = newCols;
this.rows = newRows;
const s: TerminalSession | null = this.session;
if (s === null) {
return;
}
const emu: TerminalEmulator | null = s.getEmulator();
if (emu === null) {
s.ensureShell(this.cols, this.rows);
} else {
s.resizeTerminal(this.cols, this.rows);
}
this.fullDirty = true;
}
// ------------------------------------------------------------------ render
private scheduleRender(): void {
if (this.renderPending) {
return;
}
this.renderPending = true;
setTimeout((): void => {
this.renderPending = false;
this.render();
}, 16);
}
private render(): void {
const s: TerminalSession | null = this.session;
if (s === null || this.canvasW <= 0 || this.canvasH <= 0) {
return;
}
// Any user input snaps the view back to the live screen.
const inputVersion: number = s.getInputVersion();
if (inputVersion !== this.lastInputVersion) {
this.lastInputVersion = inputVersion;
if (this.scrollOffset > 0) {
this.scrollOffset = 0;
this.fullDirty = true;
}
}
const emu: TerminalEmulator | null = s.getEmulator();
if (emu === null) {
this.ctx.fillStyle = this.bgCss;
this.ctx.fillRect(0, 0, this.canvasW, this.canvasH);
return;
}
const buf: TerminalBuffer = emu.getBuffer();
const scrolled: boolean = this.scrollOffset > 0;
if (this.fullDirty || scrolled) {
this.ctx.fillStyle = this.bgCss;
this.ctx.fillRect(0, 0, this.canvasW, this.canvasH);
for (let v: number = 0; v < this.rows; v++) {
this.drawVisibleLine(emu, buf, v);
}
} else {
for (let r: number = 0; r < emu.getRows(); r++) {
if (buf.isRowDirty(r)) {
this.drawScreenRow(emu, buf, r, r);
buf.clearRowDirty(r);
}
}
// A cursor move without content change still repaints its two rows.
const cursorVisible: boolean = this.cursorVisible(emu);
if (cursorVisible !== this.lastCursorVisible ||
(cursorVisible &&
(emu.getCursorRow() !== this.lastCursorRow || emu.getCursorCol() !== this.lastCursorCol))) {
if (this.lastCursorVisible && this.lastCursorRow >= 0 && this.lastCursorRow < emu.getRows()) {
this.drawScreenRow(emu, buf, this.lastCursorRow, this.lastCursorRow);
}
const cr: number = emu.getCursorRow();
if (cr >= 0 && cr < emu.getRows()) {
this.drawScreenRow(emu, buf, cr, cr);
}
}
}
this.drawCursor(emu, buf);
this.lastCursorRow = emu.getCursorRow();
this.lastCursorCol = emu.getCursorCol();
this.lastCursorVisible = this.cursorVisible(emu);
this.fullDirty = false;
}
/** Draw visual row v of the scroll window (scrollback + screen). */
private drawVisibleLine(emu: TerminalEmulator, buf: TerminalBuffer, v: number): void {
const sbCount: number = buf.getScrollbackCount();
const screenRows: number = emu.getRows();
const idx: number = sbCount - this.scrollOffset + v;
if (idx < 0) {
this.clearVisualRow(v);
return;
}
if (idx < sbCount) {
this.drawCells(buf.getScrollbackLine(idx), v);
return;
}
const sr: number = idx - sbCount;
if (sr < screenRows) {
this.drawScreenRow(emu, buf, sr, v);
} else {
this.clearVisualRow(v);
}
}
private clearVisualRow(v: number): void {
this.ctx.fillStyle = this.bgCss;
this.ctx.fillRect(0, v * this.cellH, this.canvasW, this.cellH);
}
private drawScreenRow(emu: TerminalEmulator, buf: TerminalBuffer, screenRow: number, visualRow: number): void {
if (screenRow < 0 || screenRow >= emu.getRows()) {
this.clearVisualRow(visualRow);
return;
}
this.drawCells(buf.getRow(screenRow), visualRow);
}
/**
* Render one line of cells into visual row v as merged style runs.
* Wide (CJK) cells draw as a single 2-cell span and break runs.
*/
private drawCells(cells: VtCell[], v: number): void {
const rowY: number = v * this.cellH;
const cols: number = this.cols;
this.ctx.fillStyle = this.bgCss;
this.ctx.fillRect(0, rowY, this.canvasW, this.cellH);
const n: number = cells.length < cols ? cells.length : cols;
let col: number = 0;
while (col < n) {
const cell: VtCell = cells[col];
if ((cell.attr & ATTR_WIDE_CONT) !== 0) {
col++;
continue;
}
const wide: boolean = (cell.attr & ATTR_WIDE) !== 0;
const span: number = wide ? 2 : 1;
let runLen: number = span;
if (!wide) {
while (col + runLen < n) {
const next: VtCell = cells[col + runLen];
if ((next.attr & (ATTR_WIDE | ATTR_WIDE_CONT)) !== 0) {
break;
}
if (next.fg !== cell.fg || next.bg !== cell.bg || !sameFontStyle(next.attr, cell.attr)) {
break;
}
runLen++;
}
}
const bg: string = this.effectiveBg(cell);
if (bg !== this.bgCss) {
this.ctx.fillStyle = bg;
this.ctx.fillRect(col * this.cellW, rowY, runLen * this.cellW, this.cellH);
}
this.applyFont(cell.attr);
this.ctx.fillStyle = this.effectiveFg(cell);
let text: string = '';
for (let k: number = col; k < col + runLen; k++) {
text += cellToChar(cells[k]);
}
this.ctx.fillText(text, col * this.cellW, rowY + this.cellH / 2);
if ((cell.attr & ATTR_UNDERLINE) !== 0) {
this.ctx.fillRect(col * this.cellW, rowY + this.cellH - 2, runLen * this.cellW, 2);
}
if ((cell.attr & ATTR_STRIKE) !== 0) {
this.ctx.fillRect(col * this.cellW, rowY + this.cellH / 2, runLen * this.cellW, 1);
}
this.ctx.globalAlpha = 1;
col += runLen;
}
}
private effectiveFg(cell: VtCell): string {
const fg: string = this.colorCss(cell.fg, this.fgCss);
return (cell.attr & ATTR_REVERSE) !== 0 ? this.effectiveBgRaw(cell) : fg;
}
private effectiveBg(cell: VtCell): string {
const bg: string = this.effectiveBgRaw(cell);
return (cell.attr & ATTR_REVERSE) !== 0 ? this.colorCss(cell.fg, this.fgCss) : bg;
}
private effectiveBgRaw(cell: VtCell): string {
return this.colorCss(cell.bg, this.bgCss);
}
/** Map a VtCell color (-1 / 0-255 / truecolor) to a CSS string. */
private colorCss(c: number, fallback: string): string {
if (c === COLOR_DEFAULT) {
return fallback;
}
if (isTruecolor(c)) {
return rgbToCss(truecolorRgb(c));
}
if (c >= 0 && c < 16) {
return this.ansiCss[c];
}
if (c >= 16 && c <= 255) {
let cached: string = this.ansi256Cache[c];
if (cached === undefined) {
cached = rgbToCss(ansi256Rgb(c));
this.ansi256Cache[c] = cached;
}
return cached;
}
return fallback;
}
private applyFont(attr: number): void {
let font: string = '';
if ((attr & ATTR_BOLD) !== 0) {
font += 'bold ';
}
if ((attr & ATTR_ITALIC) !== 0) {
font += 'italic ';
}
this.ctx.font = `${font}${this.fontPx}px ${FONT_FAMILY}`;
this.ctx.globalAlpha = (attr & ATTR_DIM) !== 0 ? 0.55 : 1;
}
private cursorVisible(emu: TerminalEmulator): boolean {
return emu.isCursorVisible() || emu.isAltScreen();
}
private drawCursor(emu: TerminalEmulator, buf: TerminalBuffer): void {
if (this.scrollOffset > 0 || !this.cursorVisible(emu)) {
return;
}
const cr: number = emu.getCursorRow();
const cc: number = emu.getCursorCol();
if (cr < 0 || cr >= emu.getRows() || cc < 0 || cc >= this.cols) {
return;
}
const rowY: number = cr * this.cellH;
const cells: VtCell[] = buf.getRow(cr);
const cell: VtCell | undefined = cells[cc];
const wide: boolean = cell !== undefined && (cell.attr & ATTR_WIDE) !== 0;
const w: number = (wide ? 2 : 1) * this.cellW;
if (emu.getCursorStyle() === 2) {
// Underline cursor.
this.ctx.fillStyle = this.cursorCss;
this.ctx.fillRect(cc * this.cellW, rowY + this.cellH - 2, w, 2);
return;
}
// Block cursor: fill, then redraw the glyph in the background color.
this.ctx.fillStyle = this.cursorCss;
this.ctx.fillRect(cc * this.cellW, rowY, w, this.cellH);
if (cell !== undefined) {
this.applyFont(cell.attr);
this.ctx.fillStyle = this.effectiveBg(cell);
this.ctx.fillText(cellToChar(cell), cc * this.cellW, rowY + this.cellH / 2);
this.ctx.globalAlpha = 1;
}
}
// ------------------------------------------------------------------ input
private focusIme(): void {
try {
this.getUIContext().getFocusController().requestFocus(`term-ime-${this.sessionId}`);
} catch (e) {
// Focus moved elsewhere; non-fatal.
}
}
private cellOf(xVp: number, yVp: number): number[] {
const col: number = Math.floor(vp2px(xVp) / this.cellW);
const row: number = Math.floor(vp2px(yVp) / this.cellH);
return [clamp(col, 0, this.cols - 1), clamp(row, 0, this.rows - 1)];
}
private handleTouch(event: TouchEvent): void {
const s: TerminalSession | null = this.session;
const emu: TerminalEmulator | null = s === null ? null : s.getEmulator();
if (s === null || emu === null) {
return;
}
const t: TouchObject = event.touches[0];
if (t === undefined) {
return;
}
const mouseMode: boolean = emu.getMouseMode() > 0 && emu.isSgrMouse();
if (event.type === TouchType.Down) {
this.touchStartY = t.y;
this.touchMoved = false;
this.scrollAtTouch = this.scrollOffset;
if (mouseMode && this.scrollOffset === 0) {
this.mouseDown = true;
const cellPos: number[] = this.cellOf(t.x, t.y);
s.sendBytes(encodeMouseSgr(MOUSE_BTN_LEFT, true, cellPos[0], cellPos[1], 0));
}
return;
}
if (event.type === TouchType.Move) {
if (mouseMode && this.mouseDown) {
const cellPos: number[] = this.cellOf(t.x, t.y);
s.sendBytes(encodeMouseSgr(MOUSE_BTN_LEFT | MOUSE_MOTION_FLAG, true, cellPos[0], cellPos[1], 0));
return;
}
const dy: number = vp2px(this.touchStartY - t.y);
if (Math.abs(dy) > this.cellH / 2) {
this.touchMoved = true;
const sbCount: number = emu.getBuffer().getScrollbackCount();
const target: number = this.scrollAtTouch + Math.round(dy / this.cellH);
this.scrollOffset = clamp(target, 0, sbCount);
this.scheduleRender();
}
return;
}
if (event.type === TouchType.Up) {
if (mouseMode && this.mouseDown) {
this.mouseDown = false;
const cellPos: number[] = this.cellOf(t.x, t.y);
s.sendBytes(encodeMouseSgr(MOUSE_BTN_RELEASE, false, cellPos[0], cellPos[1], 0));
return;
}
if (!this.touchMoved) {
this.focusIme();
}
return;
}
if (event.type === TouchType.Cancel && this.mouseDown) {
this.mouseDown = false;
const cellPos: number[] = this.cellOf(t.x, t.y);
s.sendBytes(encodeMouseSgr(MOUSE_BTN_RELEASE, false, cellPos[0], cellPos[1], 0));
}
}
// ------------------------------------------------------------------ build
build() {
Stack({ alignContent: Alignment.TopStart }) {
Canvas(this.ctx)
.width('100%')
.height('100%')
.onTouch((event: TouchEvent): void => {
this.handleTouch(event);
})
.gesture(PinchGesture({ fingers: 2 })
.onActionStart((event: GestureEvent): void => {
this.pinchBaseFont = this.fontSizeVp;
})
.onActionUpdate((event: GestureEvent): void => {
const next: number = clamp(Math.round(this.pinchBaseFont * event.scale), MIN_FONT_VP, MAX_FONT_VP);
if (next !== this.fontSizeVp) {
this.fontSizeVp = next;
this.onStyleChanged();
this.onFontSizeChange?.(next);
}
}))
.onAreaChange((oldArea: Area, newArea: Area): void => {
this.relayout(lengthToVp(newArea.width), lengthToVp(newArea.height));
this.scheduleRender();
})
// Hidden IME anchor: 1px, fully transparent, never shows content.
TextInput({ text: this.imeText, placeholder: '' })
.id(`term-ime-${this.sessionId}`)
.type(InputType.USER_NAME)
.width('100%')
.height(1)
.opacity(0)
.caretColor(Color.Transparent)
.fontSize(10)
.onChange((value: string): void => {
if (value.length > 0) {
this.session?.sendText(value);
this.imeText = '';
}
})
.onFocus((): void => {
this.onImeFocusChanged?.(true);
})
.onBlur((): void => {
this.onImeFocusChanged?.(false);
})
.onSubmit((enterKey: EnterKeyType): void => {
this.session?.sendText('\r');
this.imeText = '';
})
}
.width('100%')
.height('100%')
}
}
/** Cells sharing every font-affecting attribute merge into one fillText. */
function sameFontStyle(a: number, b: number): boolean {
const mask: number = ATTR_BOLD | ATTR_DIM | ATTR_ITALIC | ATTR_UNDERLINE | ATTR_STRIKE | ATTR_REVERSE | ATTR_BLINK;
return (a & mask) === (b & mask);
}
function cellToChar(cell: VtCell): string {
const cp: number = cell.cp;
if (cp <= 0 || cp > 0x10ffff || (cp >= 0xd800 && cp <= 0xdfff)) {
return ' ';
}
return String.fromCodePoint(cp);
}
/** Area dimensions arrive as Length; treat numbers as vp, otherwise parse. */
function lengthToVp(value: Length): number {
if (typeof value === 'number') {
return value;
}
const parsed: number = Number(value);
return Number.isNaN(parsed) ? 0 : parsed;
}
+231 -16
View File
@@ -2,17 +2,40 @@
* Copyright (c) 2026 Haven for HarmonyOS contributors. * Copyright (c) 2026 Haven for HarmonyOS contributors.
* Port of Haven by GlassHaven (AGPL-3.0). See LICENSE. * Port of Haven by GlassHaven (AGPL-3.0). See LICENSE.
* *
* T9: terminal page skeleton — session tab strip plus per-state overlays * T9/T11: terminal page — session tab strip, per-state overlays (connecting,
* (connecting progress, host-key notice, inline password prompt, error * host-key notice, inline password prompt, error/closed panels) and, once a
* and closed panels with reconnect). The terminal canvas itself lands in * session is READY, the full terminal canvas with the two-row keyboard
* the next stage. * toolbar, snippet panel and whole-line text input overlay.
*/ */
import { pasteboard } from '@kit.BasicServicesKit';
import { HostColors } from '../common/HostColors'; import { HostColors } from '../common/HostColors';
import { SessionManager } from '../session/SessionManager'; import { SessionManager } from '../session/SessionManager';
import { SessionState, TerminalSession } from '../session/TerminalSession'; import { SessionState, TerminalSession } from '../session/TerminalSession';
import { SettingsRepository } from '../data/SettingsRepository';
import { VtKey } from '../vterm/VtInput';
import { KeyboardToolbar } from './KeyboardToolbar';
import { TerminalCanvas } from './TerminalCanvas';
import { showToast } from './SessionLaunch'; import { showToast } from './SessionLaunch';
/** Hardcoded snippet macros (Haven MACRO_PRESETS). */
interface SnippetDef {
label: string;
seq: string;
}
const SNIPPETS: SnippetDef[] = [
{ label: '^C', seq: '\u0003' },
{ label: '^D', seq: '\u0004' },
{ label: '^Z', seq: '\u001a' },
{ label: '^L', seq: '\u000c' },
{ label: '^A', seq: '\u0001' },
{ label: '^E', seq: '\u0005' },
{ label: '^W', seq: '\u0017' },
{ label: '^U', seq: '\u0015' },
{ label: '⇧Tab', seq: '\u001b[Z' }
];
@Component @Component
export struct TerminalPage { export struct TerminalPage {
@State sessions: TerminalSession[] = []; @State sessions: TerminalSession[] = [];
@@ -20,6 +43,12 @@ export struct TerminalPage {
@State activeSnapshot: TerminalSession | null = null; @State activeSnapshot: TerminalSession | null = null;
@State passwordInput: string = ''; @State passwordInput: string = '';
@State rememberPassword: boolean = true; @State rememberPassword: boolean = true;
@State fontSizeVp: number = 14;
@State schemeName: string = 'Haven';
@State imeVisible: boolean = false;
@State snippetsVisible: boolean = false;
@State textInputVisible: boolean = false;
@State textInputValue: string = '';
private unsubscribe: (() => void) | null = null; private unsubscribe: (() => void) | null = null;
@@ -28,6 +57,7 @@ export struct TerminalPage {
SessionManager.getInstance().subscribe((): void => { SessionManager.getInstance().subscribe((): void => {
this.refresh(); this.refresh();
}); });
this.loadSettings();
this.refresh(); this.refresh();
} }
@@ -38,6 +68,13 @@ export struct TerminalPage {
} }
} }
private loadSettings(): void {
const settings: SettingsRepository =
SettingsRepository.getInstance(this.getUIContext().getHostContext());
this.fontSizeVp = settings.getFontSize();
this.schemeName = settings.getDefaultColorScheme();
}
private refresh(): void { private refresh(): void {
const manager: SessionManager = SessionManager.getInstance(); const manager: SessionManager = SessionManager.getInstance();
this.sessions = manager.all(); this.sessions = manager.all();
@@ -48,6 +85,10 @@ export struct TerminalPage {
if (current === null || current.getState() !== SessionState.AUTH_REQUIRED) { if (current === null || current.getState() !== SessionState.AUTH_REQUIRED) {
this.passwordInput = ''; this.passwordInput = '';
} }
if (current === null || current.getState() !== SessionState.READY) {
this.snippetsVisible = false;
this.textInputVisible = false;
}
} }
private submitPassword(session: TerminalSession): void { private submitPassword(session: TerminalSession): void {
@@ -60,6 +101,57 @@ export struct TerminalPage {
session.providePassword(pwd, this.rememberPassword); session.providePassword(pwd, this.rememberPassword);
} }
private applyFontSize(sizeVp: number): void {
this.fontSizeVp = sizeVp;
const settings: SettingsRepository =
SettingsRepository.getInstance(this.getUIContext().getHostContext());
settings.setFontSize(sizeVp).catch((): void => {
});
}
private toggleKeyboard(): void {
const controller = this.getUIContext().getFocusController();
if (this.imeVisible) {
controller.clearFocus();
} else {
try {
controller.requestFocus(`term-ime-${this.activeId}`);
} catch (e) {
// Canvas not mounted yet; non-fatal.
}
}
}
private pasteInto(session: TerminalSession): void {
this.readClipboard().then((text: string): void => {
if (text.length > 0) {
session.sendPaste(text);
} else {
showToast(this.getUIContext(), '剪贴板为空');
}
}).catch((): void => {
showToast(this.getUIContext(), '读取剪贴板失败');
});
}
private async readClipboard(): Promise<string> {
const board: pasteboard.SystemPasteboard = pasteboard.getSystemPasteboard();
if (!board.hasData()) {
return '';
}
const data: pasteboard.PasteData = await board.getData();
return data.getPrimaryText();
}
private sendTextLine(session: TerminalSession, withEnter: boolean): void {
const v: string = this.textInputValue;
this.textInputValue = '';
this.textInputVisible = false;
if (v.length > 0) {
session.sendText(withEnter ? v + '\r' : v);
}
}
// ---------------------------------------------------------------- builders // ---------------------------------------------------------------- builders
@Builder @Builder
@@ -197,22 +289,145 @@ export struct TerminalPage {
.justifyContent(FlexAlign.Center) .justifyContent(FlexAlign.Center)
} }
/** Whole-line text input overlay (CJK IME composition path). */
@Builder
textInputPanel(session: TerminalSession) {
Column({ space: 8 }) {
TextArea({ text: this.textInputValue, placeholder: '输入整行文本…' })
.width('100%')
.height(72)
.fontSize(14)
.backgroundColor('#F5F6F7')
.borderRadius(10)
.onChange((value: string): void => {
this.textInputValue = value;
})
Row({ space: 8 }) {
Button('发送')
.layoutWeight(1)
.height(38)
.fontSize(14)
.backgroundColor('#0A59F7')
.fontColor('#FFFFFF')
.onClick((): void => {
this.sendTextLine(session, false);
})
Button('发送并回车')
.layoutWeight(2)
.height(38)
.fontSize(14)
.backgroundColor('#0A59F7')
.fontColor('#FFFFFF')
.onClick((): void => {
this.sendTextLine(session, true);
})
Button('取消')
.height(38)
.fontSize(14)
.padding({ left: 14, right: 14 })
.backgroundColor('#FFFFFF')
.fontColor('#666666')
.onClick((): void => {
this.textInputValue = '';
this.textInputVisible = false;
})
}
.width('100%')
}
.width('100%')
.padding(8)
.backgroundColor('#FFFFFF')
}
/** Snippet macro chips (Ctrl combos and Shift-Tab). */
@Builder
snippetsPanel(session: TerminalSession) {
Column({ space: 8 }) {
Text('宏')
.fontSize(13)
.fontColor('#8C8C8C')
Flex({ wrap: FlexWrap.Wrap, justifyContent: FlexAlign.Center }) {
ForEach(SNIPPETS, (snippet: SnippetDef) => {
Text(snippet.label)
.fontSize(14)
.fontColor('#333333')
.padding({ left: 14, right: 14, top: 8, bottom: 8 })
.backgroundColor('#F0F1F3')
.borderRadius(8)
.margin(4)
.onClick((): void => {
session.sendText(snippet.seq);
this.snippetsVisible = false;
})
}, (snippet: SnippetDef) => snippet.label)
}
.width('100%')
Text('收起')
.fontSize(13)
.fontColor('#0A59F7')
.padding(6)
.onClick((): void => {
this.snippetsVisible = false;
})
}
.width('100%')
.padding(8)
.backgroundColor('#FFFFFF')
}
@Builder
readyBody(session: TerminalSession) {
Column() {
TerminalCanvas({
sessionId: session.getId(),
schemeName: this.schemeName,
fontSizeVp: this.fontSizeVp,
onFontSizeChange: (sizeVp: number): void => {
this.applyFontSize(sizeVp);
},
onImeFocusChanged: (focused: boolean): void => {
this.imeVisible = focused;
}
})
.layoutWeight(1)
if (this.textInputVisible) {
this.textInputPanel(session)
}
if (this.snippetsVisible) {
this.snippetsPanel(session)
}
KeyboardToolbar({
onSendText: (text: string): void => {
session.sendText(text);
},
onSendKey: (key: VtKey, mods: number): void => {
session.sendKey(key, mods);
},
onPaste: (): void => {
this.pasteInto(session);
},
onToggleKeyboard: (): void => {
this.toggleKeyboard();
},
onOpenSnippets: (): void => {
this.snippetsVisible = !this.snippetsVisible;
},
onOpenTextInput: (): void => {
this.textInputVisible = !this.textInputVisible;
}
})
}
.width('100%')
.layoutWeight(1)
}
@Builder @Builder
sessionBody(session: TerminalSession) { sessionBody(session: TerminalSession) {
Column() { Column() {
if (session.getState() === SessionState.READY) { if (session.getState() === SessionState.READY) {
Column({ space: 8 }) { this.readyBody(session)
Text('会话已就绪')
.fontSize(14)
.fontColor('#4ADE80')
Text('终端渲染将在下一阶段启用')
.fontSize(12)
.fontColor('#888888')
}
.width('100%')
.layoutWeight(1)
.justifyContent(FlexAlign.Center)
.backgroundColor('#1E1E1E')
} else if (session.getState() === SessionState.CONNECTING) { } else if (session.getState() === SessionState.CONNECTING) {
this.progressPanel(`正在连接 ${session.getSubtitle()} …`) this.progressPanel(`正在连接 ${session.getSubtitle()} …`)
} else if (session.getState() === SessionState.HOSTKEY_WAIT) { } else if (session.getState() === SessionState.HOSTKEY_WAIT) {