Terminal-Bugfix: In-App-PTY-Terminal im Dracula-Theme, .command-Fallback, ANSI-Parser-Fix, Doku
This commit is contained in:
@@ -0,0 +1,188 @@
|
||||
import Foundation
|
||||
|
||||
/// Reine ANSI/SGR-Logik ohne UI-Abhängigkeiten (unit-testbar).
|
||||
/// Versteht: SGR-Farben (30-37, 90-97, 38;5;n, 38;2;r;g;b + BG-Varianten),
|
||||
/// Clear Screen (ESC[2J), Clear Line (ESC[K]), CR/LF/Tab/Backspace/Bell.
|
||||
/// Alles andere (Cursor-Moves etc.) wird ignoriert.
|
||||
|
||||
/// Vorder-/Hintergrund als Dracula-Index 0-15, nil = Standard.
|
||||
struct TermStyle: Equatable {
|
||||
var fg: Int? = nil
|
||||
var bg: Int? = nil
|
||||
var bold: Bool = false
|
||||
}
|
||||
|
||||
struct StyledText: Equatable {
|
||||
var text: String
|
||||
var style: TermStyle
|
||||
}
|
||||
|
||||
enum TerminalEvent: Equatable {
|
||||
case text(StyledText)
|
||||
case newline
|
||||
case carriageReturn
|
||||
case backspace
|
||||
case clearScreen
|
||||
case clearLine
|
||||
case bell
|
||||
}
|
||||
|
||||
struct AnsiParser {
|
||||
private(set) var style = TermStyle()
|
||||
|
||||
mutating func feed(_ data: Data) -> [TerminalEvent] {
|
||||
var events: [TerminalEvent] = []
|
||||
var chunk = ""
|
||||
func flush() {
|
||||
if !chunk.isEmpty {
|
||||
events.append(.text(StyledText(text: chunk, style: style)))
|
||||
chunk = ""
|
||||
}
|
||||
}
|
||||
let bytes = [UInt8](data)
|
||||
var i = 0
|
||||
while i < bytes.count {
|
||||
let b = bytes[i]
|
||||
switch b {
|
||||
case 0x07: // BEL
|
||||
flush(); events.append(.bell); i += 1
|
||||
case 0x08: // BS
|
||||
flush(); events.append(.backspace); i += 1
|
||||
case 0x09: // TAB -> 8er-Stopp angenähert mit Spaces
|
||||
chunk += " "; i += 1
|
||||
case 0x0A: // LF
|
||||
flush(); events.append(.newline); i += 1
|
||||
case 0x0D: // CR (+ LF folgt -> nur Newline, sonst Overwrite)
|
||||
if i + 1 < bytes.count && bytes[i + 1] == 0x0A {
|
||||
i += 1 // CR vor LF schlucken, LF handled es
|
||||
} else {
|
||||
flush(); events.append(.carriageReturn)
|
||||
i += 1
|
||||
}
|
||||
case 0x1B: // ESC
|
||||
if i + 1 < bytes.count && bytes[i + 1] == UInt8(ascii: "[") {
|
||||
flush() // pending Text gehört noch zum alten Stil
|
||||
let (consumed, evs) = parseCSI(bytes: bytes, from: i, chunk: &chunk)
|
||||
events.append(contentsOf: evs)
|
||||
i += consumed
|
||||
} else if i + 1 < bytes.count && bytes[i + 1] == UInt8(ascii: "]") {
|
||||
// OSC (z. B. Fenstertitel) bis BEL oder ESC\ skippen
|
||||
flush()
|
||||
i += 2
|
||||
while i < bytes.count {
|
||||
if bytes[i] == 0x07 { i += 1; break }
|
||||
if bytes[i] == 0x1B && i + 1 < bytes.count && bytes[i + 1] == UInt8(ascii: "\\") { i += 2; break }
|
||||
i += 1
|
||||
}
|
||||
} else {
|
||||
i += 2 // sonstige ESC-Sequenz ignorieren
|
||||
}
|
||||
default:
|
||||
if b < 0x20 {
|
||||
i += 1 // übrige Steuerzeichen ignorieren
|
||||
} else {
|
||||
// UTF-8: Folgebytes mitnehmen
|
||||
let len: Int
|
||||
if b & 0x80 == 0 { len = 1 }
|
||||
else if b & 0xE0 == 0xC0 { len = 2 }
|
||||
else if b & 0xF0 == 0xE0 { len = 3 }
|
||||
else { len = 4 }
|
||||
let slice = bytes[i..<min(i + len, bytes.count)]
|
||||
chunk += String(decoding: slice, as: UTF8.self)
|
||||
i += slice.count
|
||||
}
|
||||
}
|
||||
}
|
||||
flush()
|
||||
return events
|
||||
}
|
||||
|
||||
private mutating func parseCSI(bytes: [UInt8], from start: Int, chunk: inout String) -> (Int, [TerminalEvent]) {
|
||||
var i = start + 2 // hinter ESC[
|
||||
var params = ""
|
||||
while i < bytes.count && !(bytes[i] >= 0x40 && bytes[i] <= 0x7E) {
|
||||
params.append(Character(UnicodeScalar(bytes[i])))
|
||||
i += 1
|
||||
}
|
||||
guard i < bytes.count else { return (bytes.count - start, []) }
|
||||
let final = bytes[i]
|
||||
i += 1
|
||||
switch final {
|
||||
case UInt8(ascii: "m"):
|
||||
applySGR(params)
|
||||
return (i - start, [])
|
||||
case UInt8(ascii: "J"):
|
||||
if params == "2" || params == "3" { return (i - start, [.clearScreen]) }
|
||||
return (i - start, [])
|
||||
case UInt8(ascii: "K"):
|
||||
return (i - start, [.clearLine])
|
||||
case UInt8(ascii: "H"), UInt8(ascii: "f"):
|
||||
return (i - start, [.carriageReturn])
|
||||
default:
|
||||
return (i - start, []) // Cursor-Moves etc. ignorieren
|
||||
}
|
||||
}
|
||||
|
||||
private mutating func applySGR(_ params: String) {
|
||||
let codes = params.isEmpty ? [0] : params.split(separator: ";").compactMap { Int($0) }
|
||||
var i = 0
|
||||
while i < codes.count {
|
||||
let c = codes[i]
|
||||
switch c {
|
||||
case 0: style = TermStyle()
|
||||
case 1: style.bold = true
|
||||
case 22: style.bold = false
|
||||
case 30...37: style.fg = c - 30
|
||||
case 39: style.fg = nil
|
||||
case 40...47: style.bg = c - 40
|
||||
case 49: style.bg = nil
|
||||
case 90...97: style.fg = c - 90 + 8
|
||||
case 100...107: style.bg = c - 100 + 8
|
||||
case 38, 48:
|
||||
let isFg = (c == 38)
|
||||
if i + 1 < codes.count && codes[i + 1] == 5 && i + 2 < codes.count {
|
||||
let mapped = Self.map256(codes[i + 2])
|
||||
if isFg { style.fg = mapped } else { style.bg = mapped }
|
||||
i += 2
|
||||
} else if i + 1 < codes.count && codes[i + 1] == 2 && i + 4 < codes.count {
|
||||
let mapped = Self.nearestDracula(r: codes[i + 2], g: codes[i + 3], b: codes[i + 4])
|
||||
if isFg { style.fg = mapped } else { style.bg = mapped }
|
||||
i += 4
|
||||
}
|
||||
default: break
|
||||
}
|
||||
i += 1
|
||||
}
|
||||
}
|
||||
|
||||
/// 256-Farben grob auf Dracula 0-15 mappen.
|
||||
static func map256(_ n: Int) -> Int {
|
||||
if n < 16 { return n }
|
||||
if n >= 232 {
|
||||
if n < 238 { return 0 }
|
||||
if n < 248 { return 8 }
|
||||
return 15
|
||||
}
|
||||
let x = n - 16
|
||||
let r = (x / 36) % 6, g = (x / 6) % 6, b = x % 6
|
||||
let bright = (r > 2 || g > 2 || b > 2) ? 8 : 0
|
||||
if r >= g && r >= b { return 1 + bright }
|
||||
if g >= b { return 2 + bright }
|
||||
if b == g && b > r { return 6 + bright }
|
||||
return 4 + bright
|
||||
}
|
||||
|
||||
/// Truecolor -> nächstliegende Dracula-Farbe (vereinfachte Distanz).
|
||||
static func nearestDracula(r: Int, g: Int, b: Int) -> Int {
|
||||
let palette = [(33, 34, 44), (255, 85, 85), (80, 250, 123), (241, 250, 140),
|
||||
(189, 147, 249), (255, 121, 198), (139, 233, 253), (248, 248, 242),
|
||||
(98, 114, 164), (255, 110, 110), (105, 255, 148), (255, 255, 165),
|
||||
(214, 172, 255), (255, 146, 223), (164, 255, 255), (255, 255, 255)]
|
||||
var best = 7, bestDist = Int.max
|
||||
for (idx, (pr, pg, pb)) in palette.enumerated() {
|
||||
let d = (r - pr) * (r - pr) + (g - pg) * (g - pg) + (b - pb) * (b - pb)
|
||||
if d < bestDist { bestDist = d; best = idx }
|
||||
}
|
||||
return best
|
||||
}
|
||||
}
|
||||
@@ -20,14 +20,18 @@ enum SSHService {
|
||||
return "ssh " + escaped.joined(separator: " ")
|
||||
}
|
||||
|
||||
/// Öffnet die SSH-Session in Terminal.app
|
||||
/// Öffnet die SSH-Session in Terminal.app — ohne AppleScript (das scheiterte
|
||||
/// still an fehlender Automation-Berechtigung), sondern über eine .command-Datei.
|
||||
static func openInTerminal(profile: ConnectionProfile, key: StoredSSHKey?) {
|
||||
let cmd = sshCommandString(for: profile, key: key)
|
||||
let script = "tell application \"Terminal\" to do script \"\(cmd.replacingOccurrences(of: "\"", with: "\\\""))\""
|
||||
var err: NSDictionary?
|
||||
if let appleScript = NSAppleScript(source: script) {
|
||||
appleScript.executeAndReturnError(&err)
|
||||
}
|
||||
let dir = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first!
|
||||
.appendingPathComponent("RemminaMac", isDirectory: true)
|
||||
try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
|
||||
let url = dir.appendingPathComponent("launch-\(profile.id.uuidString).command")
|
||||
// exec bash hält das Fenster nach Sitzungsende offen
|
||||
try? "#!/bin/bash\n\(cmd)\nexec bash\n".write(to: url, atomically: true, encoding: .utf8)
|
||||
try? FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: url.path)
|
||||
NSWorkspace.shared.open(url)
|
||||
}
|
||||
|
||||
static func copyCommandToClipboard(profile: ConnectionProfile, key: StoredSSHKey?) {
|
||||
|
||||
@@ -0,0 +1,225 @@
|
||||
import Foundation
|
||||
import Combine
|
||||
import Darwin
|
||||
import AppKit
|
||||
|
||||
enum PTYState: Equatable {
|
||||
case never
|
||||
case running
|
||||
case done(exitCode: Int32?, message: String)
|
||||
}
|
||||
|
||||
/// SSH/SFTP-Session über ein echtes Pseudo-Terminal (PTY), damit interaktive
|
||||
/// Prompts (Passwort, Host-Key) funktionieren. Ausgabe wird via AnsiParser
|
||||
/// in gestylte Zeilen für die Dracula-Ansicht übersetzt.
|
||||
final class PTYSession: ObservableObject {
|
||||
@Published private(set) var lines: [[StyledText]] = [[]]
|
||||
@Published private(set) var state: PTYState = .never
|
||||
|
||||
var executable = ""
|
||||
var arguments: [String] = []
|
||||
|
||||
private var masterFD: Int32 = -1
|
||||
private var process: Process?
|
||||
private var readSource: DispatchSourceRead?
|
||||
private let ioQueue = DispatchQueue(label: "RemminaMac.pty")
|
||||
private var parser = AnsiParser()
|
||||
private var finished = false
|
||||
private let maxLines = 2000
|
||||
|
||||
var isRunning: Bool {
|
||||
if case .running = state { return true }
|
||||
return false
|
||||
}
|
||||
|
||||
var plainText: String {
|
||||
lines.map { $0.map(\.text).joined() }.joined(separator: "\n")
|
||||
}
|
||||
|
||||
func configure(executable: String, arguments: [String]) {
|
||||
self.executable = executable
|
||||
self.arguments = arguments
|
||||
}
|
||||
|
||||
func start() {
|
||||
stop()
|
||||
finished = false
|
||||
parser = AnsiParser()
|
||||
state = .running
|
||||
lines = [[]]
|
||||
|
||||
let master = posix_openpt(O_RDWR | O_NOCTTY)
|
||||
guard master >= 0, grantpt(master) == 0, unlockpt(master) == 0,
|
||||
let cName = ptsname(master),
|
||||
!String(cString: cName).isEmpty else {
|
||||
finish(message: "PTY konnte nicht geöffnet werden (errno \(errno)).", code: nil)
|
||||
return
|
||||
}
|
||||
let slavePath = String(cString: cName)
|
||||
let slave = open(slavePath, O_RDWR | O_NOCTTY)
|
||||
guard slave >= 0 else {
|
||||
close(master)
|
||||
finish(message: "PTY-Slave \(slavePath) ließ sich nicht öffnen.", code: nil)
|
||||
return
|
||||
}
|
||||
masterFD = master
|
||||
|
||||
let p = Process()
|
||||
p.executableURL = URL(fileURLWithPath: executable)
|
||||
p.arguments = arguments
|
||||
var env = ProcessInfo.processInfo.environment
|
||||
env["TERM"] = "xterm-256color"
|
||||
if env["LANG"] == nil { env["LANG"] = "de_DE.UTF-8" }
|
||||
p.environment = env
|
||||
// closeOnDealloc=false: Parent schließt slave explizit nach run().
|
||||
p.standardInput = FileHandle(fileDescriptor: slave)
|
||||
p.standardOutput = FileHandle(fileDescriptor: slave)
|
||||
p.standardError = FileHandle(fileDescriptor: slave)
|
||||
p.terminationHandler = { [weak self] proc in
|
||||
DispatchQueue.main.async {
|
||||
self?.finish(message: "Sitzung beendet (Code \(proc.terminationStatus)).", code: proc.terminationStatus)
|
||||
}
|
||||
}
|
||||
do {
|
||||
try p.run()
|
||||
} catch {
|
||||
close(slave); close(master); masterFD = -1
|
||||
finish(message: "Start fehlgeschlagen: \(error.localizedDescription)", code: nil)
|
||||
return
|
||||
}
|
||||
process = p
|
||||
close(slave) // Parent behält nur Master
|
||||
|
||||
let source = DispatchSource.makeReadSource(fileDescriptor: master, queue: ioQueue)
|
||||
source.setEventHandler { [weak self] in self?.drain() }
|
||||
source.setCancelHandler { [master] in close(master) }
|
||||
readSource = source
|
||||
source.resume()
|
||||
}
|
||||
|
||||
private func drain() {
|
||||
let fd = masterFD
|
||||
guard fd >= 0 else { return }
|
||||
var buf = [UInt8](repeating: 0, count: 8192)
|
||||
let n = read(fd, &buf, buf.count)
|
||||
if n > 0 {
|
||||
let events = parser.feed(Data(buf[..<n]))
|
||||
DispatchQueue.main.async { [weak self] in self?.apply(events) }
|
||||
} else {
|
||||
readSource?.cancel()
|
||||
masterFD = -1
|
||||
}
|
||||
}
|
||||
|
||||
private func apply(_ events: [TerminalEvent]) {
|
||||
for ev in events {
|
||||
switch ev {
|
||||
case .text(let seg):
|
||||
if lines.isEmpty { lines.append([]) }
|
||||
if var last = lines[lines.count - 1].last, last.style == seg.style {
|
||||
last.text += seg.text
|
||||
lines[lines.count - 1][lines[lines.count - 1].count - 1] = last
|
||||
} else {
|
||||
lines[lines.count - 1].append(seg)
|
||||
}
|
||||
case .newline:
|
||||
lines.append([])
|
||||
case .carriageReturn:
|
||||
// Overwrite-Modus (Fortschrittsbalken): aktuelle Zeile leeren
|
||||
if !lines.isEmpty { lines[lines.count - 1] = [] }
|
||||
case .backspace:
|
||||
guard !lines.isEmpty, !lines[lines.count - 1].isEmpty else { break }
|
||||
var row = lines[lines.count - 1]
|
||||
if var last = row.last, !last.text.isEmpty {
|
||||
last.text.removeLast()
|
||||
if last.text.isEmpty { row.removeLast() } else { row[row.count - 1] = last }
|
||||
lines[lines.count - 1] = row
|
||||
}
|
||||
case .clearScreen:
|
||||
lines = [[]]
|
||||
case .clearLine:
|
||||
if !lines.isEmpty { lines[lines.count - 1] = [] }
|
||||
case .bell:
|
||||
NSSound.beep()
|
||||
}
|
||||
}
|
||||
if lines.count > maxLines {
|
||||
lines.removeFirst(lines.count - maxLines)
|
||||
}
|
||||
}
|
||||
|
||||
func send(_ string: String) {
|
||||
let fd = masterFD
|
||||
guard fd >= 0 else { return }
|
||||
guard let data = string.data(using: .utf8) else { return }
|
||||
ioQueue.async {
|
||||
data.withUnsafeBytes { ptr in
|
||||
var written = 0
|
||||
while written < data.count {
|
||||
let n = write(fd, ptr.baseAddress!.advanced(by: written), data.count - written)
|
||||
if n <= 0 { break }
|
||||
written += n
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func clear() {
|
||||
lines = [[]]
|
||||
}
|
||||
|
||||
func stop() {
|
||||
process?.terminate()
|
||||
process = nil
|
||||
if !finished {
|
||||
finished = true
|
||||
readSource?.cancel()
|
||||
readSource = nil
|
||||
masterFD = -1
|
||||
if case .running = state {
|
||||
state = .done(exitCode: nil, message: "Getrennt.")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func finish(message: String, code: Int32?) {
|
||||
guard !finished else { return }
|
||||
finished = true
|
||||
readSource?.cancel()
|
||||
readSource = nil
|
||||
masterFD = -1
|
||||
process = nil
|
||||
state = .done(exitCode: code, message: message)
|
||||
let note = StyledText(text: "— \(message) —", style: TermStyle(fg: 8))
|
||||
lines.append([note])
|
||||
lines.append([])
|
||||
}
|
||||
|
||||
deinit {
|
||||
process?.terminate()
|
||||
readSource?.cancel()
|
||||
}
|
||||
}
|
||||
|
||||
/// Hält pro Profil genau eine PTYSession, damit Tab-Wechsel die Session nicht killen.
|
||||
@MainActor
|
||||
final class TerminalManager: ObservableObject {
|
||||
private var sessions: [UUID: PTYSession] = [:]
|
||||
|
||||
func session(for profile: ConnectionProfile, key: StoredSSHKey?) -> PTYSession {
|
||||
if let existing = sessions[profile.id] { return existing }
|
||||
let s = PTYSession()
|
||||
if profile.proto == .sftp {
|
||||
s.configure(executable: "/usr/bin/sftp", arguments: ["-P", "\(profile.port)"] + (key.map { ["-i", $0.privateKeyPath] } ?? []) + ["\(profile.username)@\(profile.host)"])
|
||||
} else {
|
||||
s.configure(executable: "/usr/bin/ssh", arguments: SSHService.sshArguments(for: profile, key: key))
|
||||
}
|
||||
sessions[profile.id] = s
|
||||
return s
|
||||
}
|
||||
|
||||
func close(_ profile: ConnectionProfile) {
|
||||
sessions[profile.id]?.stop()
|
||||
sessions.removeValue(forKey: profile.id)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import SwiftUI
|
||||
import AppKit
|
||||
|
||||
/// Offizielle Dracula-Palette (https://draculatheme.com/contribute).
|
||||
enum Dracula {
|
||||
static let background = Color(hex: "282A36")
|
||||
static let currentLine = Color(hex: "44475A")
|
||||
static let foreground = Color(hex: "F8F8F2")
|
||||
static let comment = Color(hex: "6272A4")
|
||||
static let cyan = Color(hex: "8BE9FD")
|
||||
static let green = Color(hex: "50FA7B")
|
||||
static let orange = Color(hex: "FFB86C")
|
||||
static let pink = Color(hex: "FF79C6")
|
||||
static let purple = Color(hex: "BD93F9")
|
||||
static let red = Color(hex: "FF5555")
|
||||
static let yellow = Color(hex: "F1FA8C")
|
||||
|
||||
/// ANSI-Index 0-15 -> Dracula-Farbe.
|
||||
static func color(for index: Int?) -> Color {
|
||||
guard let index else { return foreground }
|
||||
switch index {
|
||||
case 0: return Color(hex: "21222C")
|
||||
case 1: return red
|
||||
case 2: return green
|
||||
case 3: return yellow
|
||||
case 4: return purple
|
||||
case 5: return pink
|
||||
case 6: return cyan
|
||||
case 7: return foreground
|
||||
case 8: return comment
|
||||
case 9: return Color(hex: "FF6E6E")
|
||||
case 10: return Color(hex: "69FF94")
|
||||
case 11: return Color(hex: "FFFFA5")
|
||||
case 12: return Color(hex: "D6ACFF")
|
||||
case 13: return Color(hex: "FF92DF")
|
||||
case 14: return Color(hex: "A4FFFF")
|
||||
default: return Color(hex: "FFFFFF")
|
||||
}
|
||||
}
|
||||
|
||||
static func nsColor(for index: Int?) -> NSColor {
|
||||
NSColor(color(for: index))
|
||||
}
|
||||
|
||||
static let nsBackground = NSColor(Color(hex: "282A36"))
|
||||
static let nsSelection = NSColor(Color(hex: "44475A"))
|
||||
}
|
||||
|
||||
extension Color {
|
||||
init(hex: String) {
|
||||
let clean = hex.trimmingCharacters(in: CharacterSet.alphanumerics.inverted)
|
||||
var value: UInt64 = 0
|
||||
Scanner(string: clean).scanHexInt64(&value)
|
||||
let r = Double((value >> 16) & 0xFF) / 255
|
||||
let g = Double((value >> 8) & 0xFF) / 255
|
||||
let b = Double(value & 0xFF) / 255
|
||||
self.init(red: r, green: g, blue: b)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user