forked from dnpp73/Terminal
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SSHTerminalViewController.swift
359 lines (286 loc) · 11.6 KB
/
SSHTerminalViewController.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
import UIKit
import NMSSH
import Terminal
func debugLog(fileName: String = #file, line: Int = #line, functionName: String = #function, _ msg: String = "") {
#if DEBUG
print("\(Date().description) [\(fileName.split(separator: "/").last ?? "") @L\(line) \(functionName)] " + msg)
#endif
}
final class SSHTerminalViewController: UIViewController {
fileprivate let sshQueue = DispatchQueue(label: "NMSSH.queue.SSHTerminalViewController")
fileprivate var session: NMSSHSession?
fileprivate var channel: NMSSHChannel? { session?.channel }
private static let initialFontSize = "9"
private static let fontSizes: [String] = Array(1...50).map { String($0) }
private static let initialCursorShape = TerminalCursorShape.beam.rawValue
private static let cursorShapes: [String] = [
TerminalCursorShape.block.rawValue,
TerminalCursorShape.beam.rawValue,
TerminalCursorShape.underline.rawValue,
]
private static let initialCursorBlink = "true"
private static let cursorBlinks: [String] = ["true", "false"]
private let terminalInputAccessoryView = InputAccessoryView.createFromNib()
@IBOutlet private var userNameTextField: UITextField!
@IBOutlet private var hostNameTextField: UITextField!
@IBOutlet private var passwordTextField: UITextField!
@IBOutlet private var actionBarButtonItem: UIBarButtonItem!
@IBOutlet fileprivate var terminalView: TerminalView!
@IBOutlet fileprivate var fontSizePicker: KeyboardPicker!
@IBOutlet fileprivate var cursorShapePicker: KeyboardPicker!
@IBOutlet fileprivate var cursorBlinkPicker: KeyboardPicker!
@IBOutlet private var terminalModeChangeButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
hostNameTextField?.text = UserDefaults.standard.string(forKey: kSSHHostNameDefaultsKey)
terminalInputAccessoryView?.terminalView = terminalView
terminalView.delegate = self
terminalView.bottomAnchor.constraint(equalTo: view.keyboardLayoutGuide.topAnchor).isActive = true // fail if write `@IBOutlet var didSet` scope
fontSizePicker.dataSource = Self.fontSizes
fontSizePicker.delegate = self
fontSizePicker.selectedData = Self.initialFontSize
cursorShapePicker.dataSource = Self.cursorShapes
cursorShapePicker.delegate = self
cursorShapePicker.selectedData = Self.initialCursorShape
cursorBlinkPicker.dataSource = Self.cursorBlinks
cursorBlinkPicker.delegate = self
cursorBlinkPicker.selectedData = Self.initialCursorBlink
terminalViewDidChangeMode(terminalView)
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
disconnect()
}
fileprivate func changeBarButtonItemTitleOnMainThread(_ title: String) {
let execute: () -> Void = { [weak self] in
guard let actionBarButtonItem = self?.actionBarButtonItem else {
return
}
actionBarButtonItem.title = title
}
if Thread.isMainThread {
execute()
} else {
DispatchQueue.main.async(execute: execute)
}
}
// MARK: - IBActions
@IBAction private func handleActionBarButtonItem(_ sender: UIBarButtonItem) {
if session?.isConnected ?? false {
disconnect()
} else {
connect()
}
}
@IBAction private func handleTouchUpInsideClearScrollbackButton(_ sender: UIButton) {
terminalView?.terminalClear(.clearScrollback)
}
@IBAction private func handleTouchUpInsideResetButton(_ sender: UIButton) {
terminalView?.terminalClear(.reset)
}
@IBAction private func handleTouchUpInsideSoftResetButton(_ sender: UIButton) {
terminalView?.terminalClear(.softReset)
}
@IBAction private func handleTouchUpInsideReload(_ sender: UIButton) {
actionBarButtonItem?.isEnabled = false
disconnect()
terminalView?.reloadTerminal()
}
@IBAction private func handleTouchUpInsideScrollHome(_ sender: UIButton) {
terminalView?.terminalScroll(.home)
}
@IBAction private func handleTouchUpInsideScrollEnd(_ sender: UIButton) {
terminalView?.terminalScroll(.end)
}
@IBAction private func handleTouchUpInsideScrollPageUp(_ sender: UIButton) {
terminalView?.terminalScroll(.pageUp)
}
@IBAction private func handleTouchUpInsideScrollPageDown(_ sender: UIButton) {
terminalView?.terminalScroll(.pageDown)
}
@IBAction private func handleTouchUpInsideScrollLineUp(_ sender: UIButton) {
terminalView?.terminalScroll(.lineUp)
}
@IBAction private func handleTouchUpInsideScrollLineDown(_ sender: UIButton) {
terminalView?.terminalScroll(.lineDown)
}
@IBAction private func handleTouchUpInsideModeButton(_ sender: UIButton) {
guard let t = terminalView else {
return
}
switch t.mode {
case .input: t.enterScrollMode()
case .scroll: t.enterInputMode()
}
}
@IBAction private func handleTouchUpInsideEditableChangeButton(_ sender: UIButton) {
guard let t = terminalView else {
return
}
t.isTerminalContentEditable.toggle()
sender.setTitle("Editable: \(t.isTerminalContentEditable)", for: .normal)
}
@IBAction private func handleTouchUpInsideGetVisibleTextButton(_ sender: UIButton) {
terminalView?.getVisibleText {
print($0)
}
}
@IBAction private func handleTouchUpInsideGetAllTextButton(_ sender: UIButton) {
terminalView?.getAllText {
print($0)
}
}
// MARK: - SSH Connection
private func connect() {
guard let user = userNameTextField?.text, let host = hostNameTextField?.text, let pass = passwordTextField?.text else {
return
}
UserDefaults.standard.set(host, forKey: kSSHHostNameDefaultsKey)
UserDefaults.standard.synchronize()
let s = terminalView.terminalSize
let w = UInt(s.cols)
let h = UInt(s.rows)
sshQueue.async {
let session = NMSSHSession.connect(toHost: host, withUsername: user)
self.session = session
session.delegate = self
if session.isConnected == false {
debugLog("[ERROR] connection failed.")
return
}
debugLog("[INFO] connected: " + session.username + "@" + host)
session.authenticate(byPassword: pass)
if session.isAuthorized == false {
debugLog("[ERROR] authentication failed.")
return
}
debugLog("[INFO] authenticate success.")
session.channel.ptyTerminalType = .xterm
session.channel.requestPty = true
session.channel.delegate = self
// requestSizeWidth() is not here. should be after startShell()
do {
try session.channel.startShell()
let success = session.channel.requestSizeWidth(w, height: h)
debugLog("[INFO] requestSizeWidth success: \(success)")
self.changeBarButtonItemTitleOnMainThread("Disconnect")
} catch let e {
let message = "[ERROR] " + e.localizedDescription
debugLog(message)
}
}
}
private func disconnect() {
sshQueue.async {
if let session = self.session {
session.disconnect()
}
self.session = nil // need clear. should not reuse.
}
changeBarButtonItemTitleOnMainThread("Connect")
}
fileprivate func writeSSHChannel(_ string: String) {
sshQueue.async {
guard let channel = self.channel else {
return
}
var error: NSError?
channel.write(string, error: &error, timeout: NSNumber(value: 10))
}
}
fileprivate func writeSSHChannel(_ data: Data) {
sshQueue.async {
guard let channel = self.channel else {
return
}
var error: NSError?
channel.write(data, error: &error, timeout: NSNumber(value: 10))
}
}
}
extension SSHTerminalViewController: NMSSHSessionDelegate {
func session(_ session: NMSSHSession, shouldConnectToHostWithFingerprint fingerprint: String) -> Bool {
debugLog("[INFO] fingerprint: \(fingerprint)")
return true
}
func session(_ session: NMSSHSession, didDisconnectWithError error: Error) {
let message = "[ERROR] " + error.localizedDescription
debugLog(message)
changeBarButtonItemTitleOnMainThread("Connect")
}
}
extension SSHTerminalViewController: NMSSHChannelDelegate {
func channel(_ channel: NMSSHChannel, didReadRawData data: Data) {
terminalView.appendBuffer(data)
}
func channel(_ channel: NMSSHChannel, didReadRawError error: Data) {
terminalView.appendBuffer(error)
}
func channelShellDidClose(_ channel: NMSSHChannel) {
debugLog("[INFO] Shell Closed.")
}
}
extension SSHTerminalViewController: TerminalViewDelegate {
func terminalViewDidLoad(_ terminalView: TerminalView) {
actionBarButtonItem.isEnabled = true
}
func terminalView(_ terminalView: TerminalView, didChangeTerminalSize oldSize: TerminalSize) {
guard let channel = channel else {
return
}
let s = terminalView.terminalSize
let w = UInt(s.cols)
let h = UInt(s.rows)
let success = channel.requestSizeWidth(w, height: h)
debugLog("oldSize: \(oldSize), currentSize: \(terminalView.terminalSize), success: \(success)")
}
func terminalView(_ terminalView: TerminalView, didHandleURL url: URL) {
}
func terminalView(_ terminalView: TerminalView, didHandleKeyInput string: String) {
writeSSHChannel(string)
}
func terminalViewDidHandleDeleteBackward(_ terminalView: TerminalView) {
terminalView.press(.backspace)
}
func terminalView(_ terminalView: TerminalView, didHandleSendString string: String) {
writeSSHChannel(string)
}
func terminalView(_ terminalView: TerminalView, didHandleOnVTKeyStroke string: String) {
writeSSHChannel(string)
}
func terminalViewRequestInputAccessoryView(_ terminalView: TerminalView) -> UIView? {
terminalInputAccessoryView
}
func terminalViewRequestInputAccessoryViewController(_ terminalView: TerminalView) -> UIInputViewController? {
nil
}
func terminalViewDidChangeMode(_ terminalView: TerminalView) {
let title: String
switch terminalView.mode {
case .input: title = "Mode: input"
case .scroll: title = "Mode: scroll"
}
terminalModeChangeButton.setTitle(title, for: .normal)
}
}
extension SSHTerminalViewController: KeyboardPickerDelegate {
func keyboardPicker(_ keyboardPicker: KeyboardPicker, didSelect index: Int) {
guard let terminalView = terminalView else {
return
}
switch keyboardPicker {
case fontSizePicker:
let fontSize = UInt(keyboardPicker.selectedData, fallback: 9)
terminalView.terminalFontSize = fontSize
case cursorShapePicker:
if let shape = TerminalCursorShape(rawValue: keyboardPicker.selectedData) {
terminalView.terminalCursorShape = shape
}
case cursorBlinkPicker:
let isBlink = keyboardPicker.selectedData == "true"
terminalView.isTerminalCursorBlink = isBlink
default:
break
}
}
}