askrobots / network-computer-ios
Public
iPhone client for network-computer: see and drive a remote Linux/Mac desktop over WebRTC, phone as trackpad and keyboard, desktop on a TV via AirPlay.
KeyCaptureView.swift · 2.2 KB · 53 lines
| 1 | import UIKit |
| 2 | |
| 3 | /// Invisible first responder that turns the software keyboard and any hardware |
| 4 | /// keyboard into key events for the host. |
| 5 | final class KeyCaptureView: UIView, UIKeyInput { |
| 6 | var send: ((InputEvent) -> Void)? |
| 7 | |
| 8 | override var canBecomeFirstResponder: Bool { true } |
| 9 | var hasText: Bool { true } |
| 10 | var keyboardType: UIKeyboardType = .asciiCapable |
| 11 | var autocorrectionType: UITextAutocorrectionType = .no |
| 12 | var autocapitalizationType: UITextAutocapitalizationType = .none |
| 13 | var spellCheckingType: UITextSpellCheckingType = .no |
| 14 | var smartQuotesType: UITextSmartQuotesType = .no |
| 15 | var smartDashesType: UITextSmartDashesType = .no |
| 16 | |
| 17 | // Software keyboard: each character becomes press and release, with shift when needed. |
| 18 | func insertText(_ text: String) { |
| 19 | for ch in text { |
| 20 | guard let (code, shift) = KeyMap.code(for: ch) else { continue } |
| 21 | if shift { send?(InputEvent(t: "kd", code: "ShiftLeft")) } |
| 22 | send?(InputEvent(t: "kd", code: code)) |
| 23 | send?(InputEvent(t: "ku", code: code)) |
| 24 | if shift { send?(InputEvent(t: "ku", code: "ShiftLeft")) } |
| 25 | } |
| 26 | } |
| 27 | |
| 28 | func deleteBackward() { |
| 29 | send?(InputEvent(t: "kd", code: "Backspace")) |
| 30 | send?(InputEvent(t: "ku", code: "Backspace")) |
| 31 | } |
| 32 | |
| 33 | // Hardware keyboard (USB-C hub, Bluetooth): real press and release, modifiers included. |
| 34 | override func pressesBegan(_ presses: Set<UIPress>, with event: UIPressesEvent?) { |
| 35 | if !handle(presses, down: true) { super.pressesBegan(presses, with: event) } |
| 36 | } |
| 37 | override func pressesEnded(_ presses: Set<UIPress>, with event: UIPressesEvent?) { |
| 38 | if !handle(presses, down: false) { super.pressesEnded(presses, with: event) } |
| 39 | } |
| 40 | override func pressesCancelled(_ presses: Set<UIPress>, with event: UIPressesEvent?) { |
| 41 | if !handle(presses, down: false) { super.pressesCancelled(presses, with: event) } |
| 42 | } |
| 43 | |
| 44 | private func handle(_ presses: Set<UIPress>, down: Bool) -> Bool { |
| 45 | var handled = false |
| 46 | for p in presses { |
| 47 | guard let key = p.key, let code = KeyMap.code(forHID: Int(key.keyCode.rawValue)) else { continue } |
| 48 | send?(InputEvent(t: down ? "kd" : "ku", code: code)) |
| 49 | handled = true |
| 50 | } |
| 51 | return handled |
| 52 | } |
| 53 | } |