SPB Git

Repository Public

TerminalKeys.swift 13.2 KB 297 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : Claude Remote / Codex Remote9// File             : Packages/ClaudeRemoteKit/Sources/ClaudeRemoteTerminal/TerminalKeys.swift10// Module           : ClaudeRemoteTerminal11// Repository       : https://git.spboucher.ai/claude-remote-apple12// Project Website  : https://claude.spboucher.ai13// Created          : 2026-11-2914// Last Modified    : 2026-11-2915//16// =============================================================================17// AUTHOR & PROFESSIONAL AFFILIATION18// =============================================================================19//20// Author           : Simon-Pierre Boucher21// Position         : Professor of Finance22// Institution      : Université du Québec en Outaouais (UQO)23// Department       : Département des sciences administratives24// Organization     : SP Boucher25//26// Website          : https://spboucher.ai27// Git              : https://git.spboucher.ai28//29// =============================================================================30// OFFICIAL CONTACT DIRECTORY31// =============================================================================32//33// General          : info@spboucher.ai34// Professional     : contact@spboucher.ai35// Direct           : simon@spboucher.ai36// Research         : research@spboucher.ai37// Development      : dev@spboucher.ai38// Support          : support@spboucher.ai39// Security/Admin   : admin@spboucher.ai40// Notifications    : notifications@spboucher.ai41//42// Preferred Contact: support@spboucher.ai43//44// =============================================================================45// COPYRIGHT & INTELLECTUAL PROPERTY46// =============================================================================47//48// Copyright (c) 202649// Simon-Pierre Boucher50//51// All rights reserved where applicable.52//53// This file is governed by the applicable project license,54// copyright notices, institutional agreements and relevant law.55//56// Unless expressly authorized by the applicable license or57// rights holder, copying, redistribution, sublicensing,58// publication and commercial exploitation are not permitted.59//60// Existing third-party rights and notices remain unaffected.61//62// =============================================================================63// CONFIDENTIALITY & SECURITY64// =============================================================================65//66// Classification   : Public67// Distribution     : Public repository; use is governed by the project license68// Security Contact : admin@spboucher.ai69//70// Access to this source does not independently grant permission71// to redistribute or disclose confidential materials.72//73// Do not embed credentials, private keys, access tokens,74// certificates or confidential personal information.75//76// =============================================================================77// LICENSE & MAINTENANCE78// =============================================================================79//80// License          : None specified (no license file in this repository)81// Maintainer       : Simon-Pierre Boucher82// Technical Contact: dev@spboucher.ai83//84// =============================================================================85// END OF SP BOUCHER SOURCE HEADER86// =============================================================================8788import ClaudeRemoteModels89import Foundation9091// Terminal key sequences for the accessory key row and sticky modifiers.92// A pure-Swift port of the web client's `components/terminal/keys.ts` (same sequences, same rules).9394/// State of one sticky modifier: off, one-shot (applies to the next key) or locked.95public enum ModifierState: Int, Sendable, Hashable, Codable {96    case off = 0, oneShot = 1, locked = 297    public var isActive: Bool { self != .off }9899    /// tap: off → one-shot → off; double tap: → locked; tap while locked → off.100    public func tapped(doubleTap: Bool) -> ModifierState {101        switch self {102        case .locked: return .off103        case .oneShot: return doubleTap ? .locked : .off104        case .off: return .oneShot105        }106    }107}108109public enum ModifierName: String, Sendable, Hashable, CaseIterable, Codable {110    case ctrl, alt, shift111}112113/// Sticky Ctrl / Alt / Shift of the key row.114public struct StickyModifiers: Sendable, Hashable, Codable {115    public var ctrl: ModifierState116    public var alt: ModifierState117    public var shift: ModifierState118119    public init(ctrl: ModifierState = .off, alt: ModifierState = .off, shift: ModifierState = .off) {120        self.ctrl = ctrl121        self.alt = alt122        self.shift = shift123    }124125    public static let none = StickyModifiers()126    public var hasAny: Bool { ctrl.isActive || alt.isActive || shift.isActive }127128    public subscript(name: ModifierName) -> ModifierState {129        get {130            switch name {131            case .ctrl: ctrl132            case .alt: alt133            case .shift: shift134            }135        }136        set {137            switch name {138            case .ctrl: ctrl = newValue139            case .alt: alt = newValue140            case .shift: shift = newValue141            }142        }143    }144145    /// Applies a tap on a modifier key.146    public mutating func tap(_ name: ModifierName, doubleTap: Bool = false) {147        self[name] = self[name].tapped(doubleTap: doubleTap)148    }149150    /// One-shot modifiers are consumed by a key press; locked ones stay.151    public mutating func consume() { self = consumed() }152153    public func consumed() -> StickyModifiers {154        StickyModifiers(ctrl: ctrl == .locked ? .locked : .off, alt: alt == .locked ? .locked : .off, shift: shift == .locked ? .locked : .off)155    }156}157158/// A key of the accessory row: a named key (`esc`, `up`, …), a modifier, or a literal character.159/// Ids are the ones stored in `UserSettings.mobileToolbar`.160public struct TerminalKey: Sendable, Hashable, Codable, Identifiable, ExpressibleByStringLiteral, CustomStringConvertible {161    public var id: String162    public init(_ id: String) { self.id = id }163    public init(stringLiteral value: String) { id = value }164    public init(from decoder: Decoder) throws { id = try decoder.singleValueContainer().decode(String.self) }165    public func encode(to encoder: Encoder) throws {166        var c = encoder.singleValueContainer()167        try c.encode(id)168    }169    public var description: String { id }170171    public static let esc: TerminalKey = "esc", tab: TerminalKey = "tab", enter: TerminalKey = "enter", backspace: TerminalKey = "backspace"172    public static let up: TerminalKey = "up", down: TerminalKey = "down", left: TerminalKey = "left", right: TerminalKey = "right"173    public static let home: TerminalKey = "home", end: TerminalKey = "end", pageUp: TerminalKey = "pgup", pageDown: TerminalKey = "pgdn"174    public static let delete: TerminalKey = "del", insert: TerminalKey = "ins"175    public static let ctrl: TerminalKey = "ctrl", alt: TerminalKey = "alt", shift: TerminalKey = "shift"176    /// A literal character key.177    public static func character(_ c: Character) -> TerminalKey { TerminalKey(String(c)) }178179    /// The modifier this key toggles, if it is a modifier key.180    public var modifier: ModifierName? { ModifierName(rawValue: id) }181182    /// Default key row (same as the web application's default `mobileToolbar`).183    public static let defaultToolbar: [TerminalKey] = UserSettings.defaultMobileToolbar.map { TerminalKey($0) }184    /// Every id offered by the key row editor.185    public static let allToolbarKeys: [TerminalKey] =186        ["esc", "tab", "ctrl", "alt", "shift", "up", "down", "left", "right", "enter", "home", "end", "pgup", "pgdn", "del", "ins", "backspace",187         "/", "|", "~", "-", "_", ":", ".", "*", "$", "\\"]188}189190/// How a key of the row is presented.191public struct TerminalKeyDescriptor: Sendable, Hashable, Identifiable {192    public enum Kind: Sendable, Hashable { case modifier, key }193    public var key: TerminalKey194    public var label: String195    public var accessibilityLabel: String196    public var kind: Kind197    /// Holding the key repeats it.198    public var repeats: Bool199    /// Optional SF Symbol replacing the label.200    public var symbolName: String?201    public var id: String { key.id }202203    public init(_ key: TerminalKey) {204        self.key = key205        let named: (String, String, Kind, Bool, String?)? = switch key.id {206        case "esc": ("esc", "Escape", .key, false, nil)207        case "tab": ("tab", "Tab", .key, false, nil)208        case "ctrl": ("ctrl", "Control modifier", .modifier, false, nil)209        case "alt": ("alt", "Alt modifier", .modifier, false, nil)210        case "shift": ("shift", "Shift modifier", .modifier, false, nil)211        case "up": ("↑", "Arrow up", .key, true, "arrow.up")212        case "down": ("↓", "Arrow down", .key, true, "arrow.down")213        case "left": ("←", "Arrow left", .key, true, "arrow.left")214        case "right": ("→", "Arrow right", .key, true, "arrow.right")215        case "enter": ("⏎", "Enter", .key, false, "return")216        case "home": ("home", "Home", .key, false, nil)217        case "end": ("end", "End", .key, false, nil)218        case "pgup": ("pgup", "Page up", .key, true, nil)219        case "pgdn": ("pgdn", "Page down", .key, true, nil)220        case "del": ("del", "Delete", .key, true, nil)221        case "ins": ("ins", "Insert", .key, false, nil)222        case "backspace": ("⌫", "Backspace", .key, true, "delete.left")223        default: nil224        }225        if let named {226            (label, accessibilityLabel, kind, repeats, symbolName) = named227        } else {228            (label, accessibilityLabel, kind, repeats, symbolName) = (key.id, "Character \(key.id)", .key, false, nil)229        }230    }231}232233/// Encodes keys into the byte sequences an xterm-compatible program expects.234public enum KeyEncoder {235    /// Control code for a printable character (Ctrl+C → 0x03), or nil if there is none.236    public static func ctrlChar(_ ch: String) -> String? {237        let scalars = Array(ch.unicodeScalars)238        guard scalars.count == 1, scalars[0].isASCII else { return nil }239        let upper = ch.uppercased().unicodeScalars.first!.value240        if upper >= 0x40, upper <= 0x5F { return String(UnicodeScalar(upper & 0x1F)!) } // @ A-Z [ \ ] ^ _241        switch ch {242        case " ", "2": return "\u{00}"243        case "?", "8": return "\u{7F}"244        case "/", "-": return "\u{1F}"245        case "3", "4", "5", "6", "7": return String(UnicodeScalar(0x1B + (scalars[0].value - 0x33))!)246        default: return nil247        }248    }249250    /// Applies sticky modifiers to text produced by the (soft or hardware) keyboard. Only single251    /// characters are affected: pastes, escape sequences and IME commits are left untouched.252    public static func applyModifiers(toInput data: String, modifiers m: StickyModifiers) -> String {253        guard m.hasAny, data.unicodeScalars.count == 1 else { return data }254        var out = data255        if out == "\t", m.shift.isActive { return (m.alt.isActive ? "\u{1B}" : "") + "\u{1B}[Z" }256        if m.shift.isActive { out = out.uppercased() }257        if m.ctrl.isActive { out = ctrlChar(out) ?? out }258        if m.alt.isActive { out = "\u{1B}" + out }259        return out260    }261262    private static let csiFinal: [String: String] = ["up": "A", "down": "B", "right": "C", "left": "D", "home": "H", "end": "F"]263    private static let csiTilde: [String: Int] = ["pgup": 5, "pgdn": 6, "del": 3, "ins": 2]264265    /// Sequence for a key. `applicationCursor` = DECCKM as reported by the emulator. Modifier keys266    /// produce nothing; unknown ids are literal characters.267    public static func sequence(for key: TerminalKey, modifiers m: StickyModifiers = .none, applicationCursor: Bool = false) -> String {268        if key.modifier != nil { return "" }269        let mod = 1 + (m.shift.isActive ? 1 : 0) + (m.alt.isActive ? 2 : 0) + (m.ctrl.isActive ? 4 : 0)270        if let fin = csiFinal[key.id] {271            if mod > 1 { return "\u{1B}[1;\(mod)\(fin)" }272            return applicationCursor ? "\u{1B}O\(fin)" : "\u{1B}[\(fin)"273        }274        if let tilde = csiTilde[key.id] {275            return mod > 1 ? "\u{1B}[\(tilde);\(mod)~" : "\u{1B}[\(tilde)~"276        }277        switch key.id {278        case "esc": return m.alt.isActive ? "\u{1B}\u{1B}" : "\u{1B}"279        case "tab": return (m.alt.isActive ? "\u{1B}" : "") + (m.shift.isActive ? "\u{1B}[Z" : "\t")280        case "enter": return (m.alt.isActive ? "\u{1B}" : "") + "\r"281        case "backspace": return (m.alt.isActive ? "\u{1B}" : "") + (m.ctrl.isActive ? "\u{08}" : "\u{7F}")282        default: return applyModifiers(toInput: key.id, modifiers: m)283        }284    }285286    /// Sequence for several keys pressed in order; one-shot modifiers apply to the first key only.287    public static func sequence(for keys: [TerminalKey], modifiers: StickyModifiers = .none, applicationCursor: Bool = false) -> String {288        var m = modifiers289        var out = ""290        for key in keys where key.modifier == nil {291            out += sequence(for: key, modifiers: m, applicationCursor: applicationCursor)292            m.consume()293        }294        return out295    }296}297
Files main
Menu

Theme