Version 2.8.53: echtes Terminal neben der zeilenweisen Konsole

This commit is contained in:
alientim committed 2026-11-28 18:06:31 +01:00
1 parent 2868586b17
commit bf7e1f99d7
8 files changed
+593 -7

No files matched your search

+1 -1
View File
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project] [project]
name = "tesm" name = "tesm"
version = "2.8.52" version = "2.8.53"
description = "TESM -- Verwaltung und Ueberwachung von PoE-Endgeraeten und Aruba-Switchen" description = "TESM -- Verwaltung und Ueberwachung von PoE-Endgeraeten und Aruba-Switchen"
requires-python = ">=3.11" requires-python = ">=3.11"
dependencies = [ dependencies = [
+126 -2
View File
@@ -46,7 +46,7 @@ from dataclasses import dataclass
from datetime import datetime, timezone from datetime import datetime, timezone
from typing import Any from typing import Any
from flask import Blueprint, abort, render_template from flask import Blueprint, abort, render_template, request
from tesm_core import audit from tesm_core import audit
from tesm_core.auth.models import current_user, permission_required, reauth_required from tesm_core.auth.models import current_user, permission_required, reauth_required
from tesm_core.auth.service import client_ip, reauth_is_fresh from tesm_core.auth.service import client_ip, reauth_is_fresh
@@ -188,13 +188,20 @@ def _render_console(target: Target): # type: ignore[no-untyped-def]
if not target.credential_id: if not target.credential_id:
abort(409, description="Für dieses Ziel sind keine Zugangsdaten hinterlegt.") abort(409, description="Für dieses Ziel sind keine Zugangsdaten hinterlegt.")
# Switche bleiben zeilenweise: ihre CLI ist kein Terminal, und das
# Abmelden am Ende ("exit, exit, y") braucht den geordneten Ablauf.
terminalmodus = _terminalmodus_gewuenscht() and not target.is_switch
return render_template( return render_template(
"tesm/console.html", "tesm/console.html",
target=target, target=target,
host_key_ready=ssh.is_trusted(conn, target.host, target.port), host_key_ready=ssh.is_trusted(conn, target.host, target.port),
presets=switchcli.SAFE_COMMANDS if target.is_switch else CLIENT_COMMANDS, presets=switchcli.SAFE_COMMANDS if target.is_switch else CLIENT_COMMANDS,
idle_timeout=int(extension.settings.get(conn, "terminal_idle_timeout") or 300), idle_timeout=int(extension.settings.get(conn, "terminal_idle_timeout") or 300),
websocket_path=f"/ws/{target.kind}/{target.id}", # Die Betriebsart steht in der Adresse, nicht in einer Nachricht:
# gewaehlt wird vor dem Verbinden.
terminalmodus=terminalmodus,
websocket_path=f"/ws/{target.kind}/{target.id}"
+ ("?modus=terminal" if terminalmodus else ""),
) )
@@ -339,6 +346,10 @@ def _handle_socket(ws, kind: str, target_id: int) -> None: # type: ignore[no-un
commands = _run_switch_session( commands = _run_switch_session(
ws, conn, target, username, password, transcript, idle_timeout ws, conn, target, username, password, transcript, idle_timeout
) )
elif _terminalmodus():
commands = _run_interactive_session(
ws, conn, target, username, password, transcript, idle_timeout
)
else: else:
commands = _run_client_session( commands = _run_client_session(
ws, conn, target, username, password, transcript, idle_timeout ws, conn, target, username, password, transcript, idle_timeout
@@ -370,6 +381,119 @@ def _handle_socket(ws, kind: str, target_id: int) -> None: # type: ignore[no-un
) )
def _terminalmodus_gewuenscht() -> bool:
"""Dieselbe Frage fuer die Seite -- dort steht der Modus in der Adresse."""
return (request.args.get("modus") or "").strip().lower() == "terminal"
def _terminalmodus() -> bool:
"""Welche Betriebsart der Browser angefragt hat.
Vor dem Verbinden entschieden, nicht mittendrin: eine laufende Sitzung
haelt einen Kanal, und den Modus darunter zu tauschen hiesse, ihn
abzureissen und neu aufzubauen -- dann kann man gleich neu verbinden.
"""
return (request.args.get("modus") or "").strip().lower() == "terminal"
def _run_interactive_session( # type: ignore[no-untyped-def]
ws, conn, target: Target, username: str, password: str, transcript, idle_timeout: int
) -> int:
"""Eine durchgehende Shell: Tasten hin, Bildschirm zurueck.
Hier wird nichts gedeutet. Was der Browser schickt, geht unveraendert an
die Shell; was von dort kommt, unveraendert zurueck. Deshalb gibt es auch
keine Rueckgabewerte und keine Dauer je Kommando -- es gibt keine
Kommandos mehr, nur noch einen Strom.
**Mitgeschrieben wird die Ausgabe, nicht die Eingabe.** Wer an einem
Terminal ein Passwort tippt, sieht es nicht: die Gegenseite schaltet das
Echo ab. Die Tastenanschlaege aufzuzeichnen hiesse, es doch aufzuheben --
in einer Datei, die bleibt.
"""
spalten, zeilen = _erste_groesse(ws, idle_timeout)
gesendet = 0
transcript.write(
"# Betriebsart: Terminal. Aufgezeichnet wird die Ausgabe; Tastenanschlaege\n"
"# nicht -- sonst stuende hier jedes am Prompt getippte Passwort.\n"
)
_send(ws, "info", "Terminal wird geöffnet …")
with shellcli.InteractiveShell(
conn,
host=target.host,
port=target.port,
username=username,
password=password,
spalten=spalten,
zeilen=zeilen,
) as shell:
_send(ws, "ready", f"Verbunden mit {target.label} ({target.host}) als {username}.")
letzte_regung = time.monotonic()
while True:
daten = shell.lesen()
if daten:
text = daten.decode("utf-8", "replace")
_send(ws, "terminal", text)
transcript.write(text)
gesendet += len(daten)
letzte_regung = time.monotonic()
if shell.beendet():
_send(ws, "info", "Die Shell wurde beendet.")
break
try:
roh = ws.receive(timeout=0.05)
except Exception: # noqa: BLE001 - Browser weg
break
if roh is None:
if time.monotonic() - letzte_regung > idle_timeout:
_send(ws, "info", "Verbindung wegen Untätigkeit getrennt.")
break
continue
letzte_regung = time.monotonic()
try:
nachricht = json.loads(roh)
except ValueError:
continue
if "groesse" in nachricht:
masse = nachricht["groesse"] or {}
shell.groesse_setzen(masse.get("spalten", spalten), masse.get("zeilen", zeilen))
continue
eingabe = nachricht.get("daten")
if not isinstance(eingabe, str) or not eingabe:
continue
if len(eingabe) > MAX_LINE_LENGTH:
_send(ws, "error", "Die Eingabe ist zu lang.")
continue
try:
shell.schreiben(eingabe)
except ssh.SshError as exc:
_send(ws, "error", str(exc))
break
transcript.flush()
return gesendet
def _erste_groesse(ws, idle_timeout: int) -> tuple[int, int]: # type: ignore[no-untyped-def]
"""Wartet kurz auf die Fenstergroesse des Browsers.
Sie kommt als erste Nachricht. Bleibt sie aus, gilt 120x30 -- lieber ein
brauchbares Fenster als gar keine Sitzung.
"""
try:
roh = ws.receive(timeout=min(5, idle_timeout))
except Exception: # noqa: BLE001
return 120, 30
if not roh:
return 120, 30
try:
masse = (json.loads(roh) or {}).get("groesse") or {}
return int(masse.get("spalten") or 120), int(masse.get("zeilen") or 30)
except (ValueError, TypeError):
return 120, 30
def _read_command(ws, idle_timeout: int) -> str | None: # type: ignore[no-untyped-def] def _read_command(ws, idle_timeout: int) -> str | None: # type: ignore[no-untyped-def]
"""Naechstes Kommando, oder ``None`` wenn die Sitzung enden soll.""" """Naechstes Kommando, oder ``None`` wenn die Sitzung enden soll."""
raw = ws.receive(timeout=idle_timeout) raw = ws.receive(timeout=idle_timeout)
+128
View File
@@ -31,6 +31,7 @@ Vorlagen.
from __future__ import annotations from __future__ import annotations
import logging
import re import re
import sqlite3 import sqlite3
import time import time
@@ -38,6 +39,8 @@ from typing import Any
from .ssh import SshError, open_transport from .ssh import SshError, open_transport
logger = logging.getLogger(__name__)
DEFAULT_COMMAND_TIMEOUT = 60 DEFAULT_COMMAND_TIMEOUT = 60
MAX_OUTPUT_BYTES = 256 * 1024 MAX_OUTPUT_BYTES = 256 * 1024
@@ -71,6 +74,131 @@ def sudo_vorbereiten(command: str) -> tuple[str, bool]:
return vorbereitet, vorbereitet != command return vorbereitet, vorbereitet != command
class InteractiveShell:
"""Eine durchgehende Shell mit Pseudoterminal -- fuer Handarbeit.
Das Gegenstueck zu :class:`ShellSession`. Dort hat jedes Kommando seinen
eigenen Kanal: sauberer Rueckgabewert, kein haengendes Kommando reisst die
Sitzung mit, und fuer Massenbefehle ist genau das richtig. Nur arbeitet
man so nicht an einem Geraet: ``cd`` wirkt nicht auf das naechste
Kommando, ein Editor hat kein Terminal, und eine Rueckfrage mitten im Lauf
erreicht niemanden.
Hier laeuft deshalb **eine** Shell ueber die ganze Sitzung, an einem
Pseudoterminal. Alles, was hereinkommt, geht unveraendert hin; alles, was
herauskommt, unveraendert zurueck. Kein Prompt-Parser -- der war der Grund,
warum es diese Betriebsart lange nicht gab, und er wird hier auch nicht
gebraucht, weil nichts am Prompt entschieden wird.
**Die Mitschrift zeichnet nur die Ausgabe auf.** Wer an einem Terminal ein
Passwort tippt, sieht es nicht -- die Gegenseite schaltet das Echo ab. Die
Tastenanschlaege mitzuschreiben hiesse, es doch aufzubewahren.
"""
def __init__(
self,
conn: sqlite3.Connection,
*,
host: str,
port: int,
username: str,
password: str,
allow_unknown_host_key: bool = False,
spalten: int = 120,
zeilen: int = 30,
) -> None:
self.conn = conn
self.host = host
self.port = int(port)
self.username = username
self.password = password
self.allow_unknown_host_key = allow_unknown_host_key
self.spalten = max(20, min(500, int(spalten)))
self.zeilen = max(5, min(200, int(zeilen)))
self._transport: Any = None
self._channel: Any = None
def __enter__(self) -> "InteractiveShell":
self._transport = open_transport(
self.conn,
host=self.host,
port=self.port,
username=self.username,
password=self.password,
allow_unknown=self.allow_unknown_host_key,
)
kanal = self._transport.open_session()
# xterm-256color, weil im Browser ein xterm steht. Mit "dumb" faerbt
# kein Programm, mit "vt100" kennen manche Editoren die Tasten nicht.
kanal.get_pty(term="xterm-256color", width=self.spalten, height=self.zeilen)
kanal.invoke_shell()
# Nicht blockierend: die Sitzungsschleife fragt abwechselnd Kanal und
# Browser ab. Ein blockierendes recv() wuerde die Eingabe aussperren.
kanal.setblocking(False)
self._channel = kanal
return self
def __exit__(self, *_exc: object) -> None:
self.close()
def lesen(self) -> bytes:
"""Was gerade anliegt -- oder ``b""``."""
kanal = self._channel
if kanal is None:
return b""
stuecke: list[bytes] = []
while kanal.recv_ready():
try:
stueck = kanal.recv(32768)
except Exception: # noqa: BLE001 - geschlossener Kanal
break
if not stueck:
break
stuecke.append(stueck)
if sum(len(s) for s in stuecke) > MAX_OUTPUT_BYTES:
break
return b"".join(stuecke)
def schreiben(self, daten: str) -> None:
kanal = self._channel
if kanal is None:
raise SshError("Die Verbindung wurde getrennt.")
try:
kanal.sendall(daten.encode("utf-8"))
except Exception as exc: # noqa: BLE001
raise SshError(f"Die Eingabe kam nicht an ({exc}).") from exc
def groesse_setzen(self, spalten: int, zeilen: int) -> None:
"""Teilt dem Gegenueber die Fenstergroesse mit.
Ohne das rechnet die Gegenseite mit 80x24, und jeder Editor zeichnet
in ein Fenster, das es nicht gibt.
"""
kanal = self._channel
if kanal is None:
return
self.spalten = max(20, min(500, int(spalten)))
self.zeilen = max(5, min(200, int(zeilen)))
try:
kanal.resize_pty(width=self.spalten, height=self.zeilen)
except Exception: # noqa: BLE001 - nicht schlimm genug, um abzubrechen
logger.debug("Groesse liess sich nicht setzen (%s)", self.host)
def beendet(self) -> bool:
kanal = self._channel
return kanal is None or kanal.exit_status_ready() or kanal.closed
def close(self) -> None:
for teil in (self._channel, self._transport):
try:
if teil is not None:
teil.close()
except Exception: # noqa: BLE001
pass
self._channel = None
self._transport = None
class ShellSession: class ShellSession:
"""Offene SSH-Verbindung zu einem Client; ein ``exec``-Kanal je Kommando.""" """Offene SSH-Verbindung zu einem Client; ein ``exec``-Kanal je Kommando."""
+115 -3
View File
@@ -24,17 +24,39 @@
<p><a class="btn btn--primary" href="{{ back_url }}">Zur Detailseite und Schlüssel freigeben</a></p> <p><a class="btn btn--primary" href="{{ back_url }}">Zur Detailseite und Schlüssel freigeben</a></p>
{% endif %} {% endif %}
{% if terminalmodus %}
{{ alert('Eine durchgehende Shell an einem Pseudoterminal: "cd" wirkt weiter, Editoren und
Rückfragen funktionieren. Mitgeschrieben wird die Ausgabe – Tastenanschläge nicht, sonst
stünde jedes am Prompt getippte Passwort in der Datei. Bei Untätigkeit trennt die
Verbindung nach ' ~ idle_timeout ~ ' Sekunden.', 'warning', 'Terminal') }}
{% else %}
{{ alert('Die Konsole ist zeilenorientiert: ein Kommando pro Zeile, Antwort darunter. Jede {{ alert('Die Konsole ist zeilenorientiert: ein Kommando pro Zeile, Antwort darunter. Jede
Eingabe und jede Ausgabe wird auf dem Server mitgeschrieben und im Änderungsprotokoll Eingabe und jede Ausgabe wird auf dem Server mitgeschrieben und im Änderungsprotokoll
vermerkt. Bei Untätigkeit trennt die Verbindung nach ' ~ idle_timeout ~ ' Sekunden.', vermerkt. Bei Untätigkeit trennt die Verbindung nach ' ~ idle_timeout ~ ' Sekunden.',
'warning', 'Mitschrift') }} 'warning', 'Mitschrift') }}
{% if not is_switch %} {% if not is_switch %}
{{ alert('Jedes Kommando läuft in einer eigenen Sitzung. Das heisst: ein "cd" wirkt nicht {{ alert('Jedes Kommando läuft in einer eigenen Sitzung: ein "cd" wirkt nicht auf das
auf das nächste Kommando, und interaktive Programme (Editoren, Passwortabfragen) laufen nächste Kommando, und ein Editor hat kein Terminal. Für Massenbefehle ist das genau
hier nicht. Für solche Arbeiten einen richtigen SSH-Client nehmen.', 'info', richtig – für Handarbeit am Gerät nehmen Sie das Terminal daneben.', 'info',
'Ein Kommando, eine Sitzung') }} 'Ein Kommando, eine Sitzung') }}
{% endif %} {% endif %}
{% endif %}
{% if not is_switch %}
{# Gewaehlt wird vor dem Verbinden: die laufende Sitzung haelt einen Kanal,
und den Modus darunter zu tauschen hiesse, ihn abzureissen. #}
<div class="row row--tight mb-3">
<a class="btn btn--sm {{ '' if terminalmodus else 'btn--primary' }}"
href="{{ url_for('terminal.device_console', device_id=target.id) }}">
{{ icon('list', size=14) }} Zeilenmodus
</a>
<a class="btn btn--sm {{ 'btn--primary' if terminalmodus else '' }}"
href="{{ url_for('terminal.device_console', device_id=target.id, modus='terminal') }}">
{{ icon('terminal', size=14) }} Terminal
</a>
</div>
{% endif %}
<section class="card"> <section class="card">
<div class="card__header"> <div class="card__header">
@@ -49,6 +71,9 @@ vermerkt. Bei Untätigkeit trennt die Verbindung nach ' ~ idle_timeout ~ ' Sekun
{{ icon('copy', size=14) }} Mitschrift kopieren {{ icon('copy', size=14) }} Mitschrift kopieren
</button> </button>
</div> </div>
{% if terminalmodus %}
<div id="terminal-host" style="padding:var(--sp-3);background:#000;min-height:56dvh"></div>
{% else %}
<pre class="log-view" data-tail id="console-output" style="max-height:56dvh"></pre> <pre class="log-view" data-tail id="console-output" style="max-height:56dvh"></pre>
<div class="card__footer" style="justify-content:stretch;gap:var(--sp-2)"> <div class="card__footer" style="justify-content:stretch;gap:var(--sp-2)">
<select class="select" id="console-preset" style="max-width:280px"> <select class="select" id="console-preset" style="max-width:280px">
@@ -62,14 +87,100 @@ vermerkt. Bei Untätigkeit trennt die Verbindung nach ' ~ idle_timeout ~ ' Sekun
<button class="btn btn--primary" type="button" id="console-send" <button class="btn btn--primary" type="button" id="console-send"
{% if not host_key_ready %}disabled{% endif %}>Senden</button> {% if not host_key_ready %}disabled{% endif %}>Senden</button>
</div> </div>
{% endif %}
</section> </section>
<p class="fs-xs faint"> <p class="fs-xs faint">
{% if terminalmodus %}
Tastatur und Zwischenablage gehen direkt an die Shell. <kbd>exit</kbd> beendet die Sitzung.
{% else %}
Pfeiltasten hoch/runter blättern durch die letzten Eingaben. <kbd>exit</kbd> beendet die Sitzung. Pfeiltasten hoch/runter blättern durch die letzten Eingaben. <kbd>exit</kbd> beendet die Sitzung.
{% endif %}
</p> </p>
{% endblock %} {% endblock %}
{% block scripts %} {% block scripts %}
{% if terminalmodus %}
<link rel="stylesheet" href="{{ asset_url('css/vendor/xterm.css') }}">
{# xterm.js liegt im Paket, nicht an einem fremden Netz: die
Inhaltsrichtlinie erlaubt Skripte nur von hier. #}
<script src="{{ asset_url('js/vendor/xterm.js') }}" nonce="{{ csp_nonce }}"></script>
<script src="{{ asset_url('js/vendor/xterm-addon-fit.js') }}" nonce="{{ csp_nonce }}"></script>
<script nonce="{{ csp_nonce }}">
(function () {
const wirt = document.getElementById("terminal-host");
const state = document.getElementById("console-state");
const hint = document.getElementById("console-hint");
function setState(label, kind) {
state.innerHTML = "";
const pill = document.createElement("span");
pill.className = "pill" + (kind ? " pill--" + kind : "");
pill.textContent = label;
state.appendChild(pill);
}
const term = new window.Terminal({
fontFamily: "ui-monospace, SFMono-Regular, Menlo, Consolas, monospace",
fontSize: 13,
cursorBlink: true,
scrollback: 5000,
theme: { background: "#000000" },
});
const fit = new window.FitAddon.FitAddon();
term.loadAddon(fit);
term.open(wirt);
fit.fit();
const scheme = location.protocol === "https:" ? "wss:" : "ws:";
const socket = new WebSocket(`${scheme}//${location.host}{{ websocket_path }}`);
function groesseMelden() {
fit.fit();
if (socket.readyState === WebSocket.OPEN) {
socket.send(JSON.stringify({ groesse: { spalten: term.cols, zeilen: term.rows } }));
}
}
socket.addEventListener("open", () => {
setState("verbunden", "online");
hint.textContent = "Bereit";
// Die Groesse ist die erste Nachricht -- der Server wartet darauf.
socket.send(JSON.stringify({ groesse: { spalten: term.cols, zeilen: term.rows } }));
term.focus();
});
socket.addEventListener("close", () => {
setState("getrennt", "offline");
hint.textContent = "Die Verbindung ist beendet.";
term.write("\r\n\x1b[33m-- Verbindung beendet --\x1b[0m\r\n");
});
socket.addEventListener("error", () => setState("Fehler", "danger"));
socket.addEventListener("message", (event) => {
let message;
try { message = JSON.parse(event.data); } catch { return; }
if (message.type === "terminal") term.write(message.data);
else if (message.type === "error") {
term.write("\r\n\x1b[31m" + message.data + "\x1b[0m\r\n");
setState("Fehler", "danger");
} else if (message.type === "info" || message.type === "ready") {
term.write("\x1b[33m" + message.data + "\x1b[0m\r\n");
}
});
term.onData((daten) => {
if (socket.readyState === WebSocket.OPEN) {
socket.send(JSON.stringify({ daten }));
}
});
let warten = null;
window.addEventListener("resize", () => {
clearTimeout(warten);
warten = setTimeout(groesseMelden, 150);
});
})();
</script>
{% else %}
<script type="module" nonce="{{ csp_nonce }}"> <script type="module" nonce="{{ csp_nonce }}">
const output = document.getElementById("console-output"); const output = document.getElementById("console-output");
const input = document.getElementById("console-input"); const input = document.getElementById("console-input");
@@ -157,4 +268,5 @@ vermerkt. Bei Untätigkeit trennt die Verbindung nach ' ~ idle_timeout ~ ' Sekun
}); });
input.focus(); input.focus();
</script> </script>
{% endif %}
{% endblock %} {% endblock %}
+1 -1
View File
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project] [project]
name = "tesm-core" name = "tesm-core"
version = "2.8.22" version = "2.8.23"
description = "Gemeinsames Anwendungsgeruest (Auth, RBAC, Navigation, Design-System, Migrationen) fuer TESM und TESM-Lizenzserver" description = "Gemeinsames Anwendungsgeruest (Auth, RBAC, Navigation, Design-System, Migrationen) fuer TESM und TESM-Lizenzserver"
requires-python = ">=3.11" requires-python = ">=3.11"
dependencies = [ dependencies = [
@@ -0,0 +1,218 @@
/**
* Copyright (c) 2014 The xterm.js authors. All rights reserved.
* Copyright (c) 2012-2013, Christopher Jeffrey (MIT License)
* https://github.com/chjj/term.js
* @license MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* Originally forked from (with the author's permission):
* Fabrice Bellard's javascript vt100 for jslinux:
* http://bellard.org/jslinux/
* Copyright (c) 2011 Fabrice Bellard
* The original design remains. The terminal itself
* has been extended to include xterm CSI codes, among
* other features.
*/
/**
* Default styles for xterm.js
*/
.xterm {
cursor: text;
position: relative;
user-select: none;
-ms-user-select: none;
-webkit-user-select: none;
}
.xterm.focus,
.xterm:focus {
outline: none;
}
.xterm .xterm-helpers {
position: absolute;
top: 0;
/**
* The z-index of the helpers must be higher than the canvases in order for
* IMEs to appear on top.
*/
z-index: 5;
}
.xterm .xterm-helper-textarea {
padding: 0;
border: 0;
margin: 0;
/* Move textarea out of the screen to the far left, so that the cursor is not visible */
position: absolute;
opacity: 0;
left: -9999em;
top: 0;
width: 0;
height: 0;
z-index: -5;
/** Prevent wrapping so the IME appears against the textarea at the correct position */
white-space: nowrap;
overflow: hidden;
resize: none;
}
.xterm .composition-view {
/* TODO: Composition position got messed up somewhere */
background: #000;
color: #FFF;
display: none;
position: absolute;
white-space: nowrap;
z-index: 1;
}
.xterm .composition-view.active {
display: block;
}
.xterm .xterm-viewport {
/* On OS X this is required in order for the scroll bar to appear fully opaque */
background-color: #000;
overflow-y: scroll;
cursor: default;
position: absolute;
right: 0;
left: 0;
top: 0;
bottom: 0;
}
.xterm .xterm-screen {
position: relative;
}
.xterm .xterm-screen canvas {
position: absolute;
left: 0;
top: 0;
}
.xterm .xterm-scroll-area {
visibility: hidden;
}
.xterm-char-measure-element {
display: inline-block;
visibility: hidden;
position: absolute;
top: 0;
left: -9999em;
line-height: normal;
}
.xterm.enable-mouse-events {
/* When mouse events are enabled (eg. tmux), revert to the standard pointer cursor */
cursor: default;
}
.xterm.xterm-cursor-pointer,
.xterm .xterm-cursor-pointer {
cursor: pointer;
}
.xterm.column-select.focus {
/* Column selection mode */
cursor: crosshair;
}
.xterm .xterm-accessibility:not(.debug),
.xterm .xterm-message {
position: absolute;
left: 0;
top: 0;
bottom: 0;
right: 0;
z-index: 10;
color: transparent;
pointer-events: none;
}
.xterm .xterm-accessibility-tree:not(.debug) *::selection {
color: transparent;
}
.xterm .xterm-accessibility-tree {
user-select: text;
white-space: pre;
}
.xterm .live-region {
position: absolute;
left: -9999px;
width: 1px;
height: 1px;
overflow: hidden;
}
.xterm-dim {
/* Dim should not apply to background, so the opacity of the foreground color is applied
* explicitly in the generated class and reset to 1 here */
opacity: 1 !important;
}
.xterm-underline-1 { text-decoration: underline; }
.xterm-underline-2 { text-decoration: double underline; }
.xterm-underline-3 { text-decoration: wavy underline; }
.xterm-underline-4 { text-decoration: dotted underline; }
.xterm-underline-5 { text-decoration: dashed underline; }
.xterm-overline {
text-decoration: overline;
}
.xterm-overline.xterm-underline-1 { text-decoration: overline underline; }
.xterm-overline.xterm-underline-2 { text-decoration: overline double underline; }
.xterm-overline.xterm-underline-3 { text-decoration: overline wavy underline; }
.xterm-overline.xterm-underline-4 { text-decoration: overline dotted underline; }
.xterm-overline.xterm-underline-5 { text-decoration: overline dashed underline; }
.xterm-strikethrough {
text-decoration: line-through;
}
.xterm-screen .xterm-decoration-container .xterm-decoration {
z-index: 6;
position: absolute;
}
.xterm-screen .xterm-decoration-container .xterm-decoration.xterm-decoration-top-layer {
z-index: 7;
}
.xterm-decoration-overview-ruler {
z-index: 8;
position: absolute;
top: 0;
right: 0;
pointer-events: none;
}
.xterm-decoration-top {
z-index: 2;
position: relative;
}
@@ -0,0 +1,2 @@
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.FitAddon=t():e.FitAddon=t()}(self,(()=>(()=>{"use strict";var e={};return(()=>{var t=e;Object.defineProperty(t,"__esModule",{value:!0}),t.FitAddon=void 0,t.FitAddon=class{activate(e){this._terminal=e}dispose(){}fit(){const e=this.proposeDimensions();if(!e||!this._terminal||isNaN(e.cols)||isNaN(e.rows))return;const t=this._terminal._core;this._terminal.rows===e.rows&&this._terminal.cols===e.cols||(t._renderService.clear(),this._terminal.resize(e.cols,e.rows))}proposeDimensions(){if(!this._terminal)return;if(!this._terminal.element||!this._terminal.element.parentElement)return;const e=this._terminal._core,t=e._renderService.dimensions;if(0===t.css.cell.width||0===t.css.cell.height)return;const r=0===this._terminal.options.scrollback?0:e.viewport.scrollBarWidth,i=window.getComputedStyle(this._terminal.element.parentElement),o=parseInt(i.getPropertyValue("height")),s=Math.max(0,parseInt(i.getPropertyValue("width"))),n=window.getComputedStyle(this._terminal.element),l=o-(parseInt(n.getPropertyValue("padding-top"))+parseInt(n.getPropertyValue("padding-bottom"))),a=s-(parseInt(n.getPropertyValue("padding-right"))+parseInt(n.getPropertyValue("padding-left")))-r;return{cols:Math.max(2,Math.floor(a/t.css.cell.width)),rows:Math.max(1,Math.floor(l/t.css.cell.height))}}}})(),e})()));
//# sourceMappingURL=addon-fit.js.map
@@ -0,0 +1,2 @@
!function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var i=t();for(var s in i)("object"==typeof exports?exports:e)[s]=i[s]}}(globalThis,(()=>(()=>{"use strict";var e={4567:function(e,t,i){var s=this&&this.__decorate||function(e,t,i,s){var r,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,s);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(n<3?r(o):n>3?r(t,i,o):r(t,i))||o);return n>3&&o&&Object.defineProperty(t,i,o),o},r=this&&this.__param||function(e,t){return function(i,s){t(i,s,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.AccessibilityManager=void 0;const n=i(9042),o=i(9924),a=i(844),h=i(4725),c=i(2585),l=i(3656);let d=t.AccessibilityManager=class extends a.Disposable{constructor(e,t,i,s){super(),this._terminal=e,this._coreBrowserService=i,this._renderService=s,this._rowColumns=new WeakMap,this._liveRegionLineCount=0,this._charsToConsume=[],this._charsToAnnounce="",this._accessibilityContainer=this._coreBrowserService.mainDocument.createElement("div"),this._accessibilityContainer.classList.add("xterm-accessibility"),this._rowContainer=this._coreBrowserService.mainDocument.createElement("div"),this._rowContainer.setAttribute("role","list"),this._rowContainer.classList.add("xterm-accessibility-tree"),this._rowElements=[];for(let e=0;e<this._terminal.rows;e++)this._rowElements[e]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[e]);if(this._topBoundaryFocusListener=e=>this._handleBoundaryFocus(e,0),this._bottomBoundaryFocusListener=e=>this._handleBoundaryFocus(e,1),this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions(),this._accessibilityContainer.appendChild(this._rowContainer),this._liveRegion=this._coreBrowserService.mainDocument.createElement("div"),this._liveRegion.classList.add("live-region"),this._liveRegion.setAttribute("aria-live","assertive"),this._accessibilityContainer.appendChild(this._liveRegion),this._liveRegionDebouncer=this.register(new o.TimeBasedDebouncer(this._renderRows.bind(this))),!this._terminal.element)throw new Error("Cannot enable accessibility before Terminal.open");this._terminal.element.insertAdjacentElement("afterbegin",this._accessibilityContainer),this.register(this._terminal.onResize((e=>this._handleResize(e.rows)))),this.register(this._terminal.onRender((e=>this._refreshRows(e.start,e.end)))),this.register(this._terminal.onScroll((()=>this._refreshRows()))),this.register(this._terminal.onA11yChar((e=>this._handleChar(e)))),this.register(this._terminal.onLineFeed((()=>this._handleChar("\n")))),this.register(this._terminal.onA11yTab((e=>this._handleTab(e)))),this.register(this._terminal.onKey((e=>this._handleKey(e.key)))),this.register(this._terminal.onBlur((()=>this._clearLiveRegion()))),this.register(this._renderService.onDimensionsChange((()=>this._refreshRowsDimensions()))),this.register((0,l.addDisposableDomListener)(document,"selectionchange",(()=>this._handleSelectionChange()))),this.register(this._coreBrowserService.onDprChange((()=>this._refreshRowsDimensions()))),this._refreshRows(),this.register((0,a.toDisposable)((()=>{this._accessibilityContainer.remove(),this._rowElements.length=0})))}_handleTab(e){for(let t=0;t<e;t++)this._handleChar(" ")}_handleChar(e){this._liveRegionLineCount<21&&(this._charsToConsume.length>0?this._charsToConsume.shift()!==e&&(this._charsToAnnounce+=e):this._charsToAnnounce+=e,"\n"===e&&(this._liveRegionLineCount++,21===this._liveRegionLineCount&&(this._liveRegion.textContent+=n.tooMuchOutput)))}_clearLiveRegion(){this._liveRegion.textContent="",this._liveRegionLineCount=0}_handleKey(e){this._clearLiveRegion(),/\p{Control}/u.test(e)||this._charsToConsume.push(e)}_refreshRows(e,t){this._liveRegionDebouncer.refresh(e,t,this._terminal.rows)}_renderRows(e,t){const i=this._terminal.buffer,s=i.lines.length.toString();for(let r=e;r<=t;r++){const e=i.lines.get(i.ydisp+r),t=[],n=e?.translateToString(!0,void 0,void 0,t)||"",o=(i.ydisp+r+1).toString(),a=this._rowElements[r];a&&(0===n.length?(a.innerText=" ",this._rowColumns.set(a,[0,1])):(a.textContent=n,this._rowColumns.set(a,t)),a.setAttribute("aria-posinset",o),a.setAttribute("aria-setsize",s))}this._announceCharacters()}_announceCharacters(){0!==this._charsToAnnounce.length&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce="")}_handleBoundaryFocus(e,t){const i=e.target,s=this._rowElements[0===t?1:this._rowElements.length-2];if(i.getAttribute("aria-posinset")===(0===t?"1":`${this._terminal.buffer.lines.length}`))return;if(e.relatedTarget!==s)return;let r,n;if(0===t?(r=i,n=this._rowElements.pop(),this._rowContainer.removeChild(n)):(r=this._rowElements.shiftLine truncated
//# sourceMappingURL=xterm.js.map