forked from blinksh/blink
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTermController.swift
341 lines (275 loc) · 8.78 KB
/
TermController.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
//////////////////////////////////////////////////////////////////////////////////
//
// B L I N K
//
// Copyright (C) 2016-2019 Blink Mobile Shell Project
//
// This file is part of Blink.
//
// Blink is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Blink is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Blink. If not, see <http://www.gnu.org/licenses/>.
//
// In addition, Blink is also subject to certain additional terms under
// GNU GPL version 3 section 7.
//
// You should have received a copy of these additional terms immediately
// following the terms and conditions of the GNU General Public License
// which accompanied the Blink Source Code. If not, see
// <http://www.github.com/blinksh/blink>.
//
////////////////////////////////////////////////////////////////////////////////
import Foundation
import UIKit
import Combine
@objc protocol TermControlDelegate: NSObjectProtocol {
// May be do it optional
func terminalHangup(control: TermController)
@objc optional func terminalDidResize(control: TermController)
}
@objc protocol ControlPanelDelegate: NSObjectProtocol {
func controlPanelOnClose()
func controlPanelOnPaste()
func currentTerm() -> TermController!
}
class TermController: UIViewController {
private let _meta: SessionMeta
private var _termDevice = TermDevice()
private var _bag = Array<AnyCancellable>()
private var _termView = TermView(frame: .zero)
private var _sessionParams: MCPParams = {
let params = MCPParams()
params.fontSize = BKDefaults.selectedFontSize()?.intValue ?? 16
params.fontName = BKDefaults.selectedFontName()
params.themeName = BKDefaults.selectedThemeName()
params.enableBold = BKDefaults.enableBold()
params.boldAsBright = BKDefaults.isBoldAsBright()
params.viewSize = .zero
params.layoutMode = BKDefaults.layoutMode().rawValue
return params
}()
private var _bgColor: UIColor? = nil
private var _fontSizeBeforeScaling: Int? = nil
@objc public var activityKey: String? = nil
@objc public var termDevice: TermDevice { get { _termDevice } }
@objc weak var delegate: TermControlDelegate? = nil
@objc var sessionParams: MCPParams { _sessionParams }
@objc var bgColor: UIColor? {
get { _bgColor }
set { _bgColor = newValue }
}
private var _session: MCPSession? = nil
required init(meta: SessionMeta? = nil) {
_meta = meta ?? SessionMeta()
super.init(nibName: nil, bundle: nil)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
if !coordinator.isAnimated {
return
}
super.viewWillTransition(to: size, with: coordinator)
}
public override func loadView() {
super.loadView()
_termDevice.delegate = self
_termDevice.attachView(_termView)
_termView.backgroundColor = _bgColor
view = _termView
}
public override func viewDidLoad() {
super.viewDidLoad()
resumeIfNeeded()
_termView.load(with: _sessionParams)
NotificationCenter.default.addObserver(
self,
selector: #selector(_relayout),
name: NSNotification.Name(rawValue: LayoutManagerBottomInsetDidUpdate), object: nil)
}
@objc func _relayout() {
guard
let window = view.window,
window.screen === UIScreen.main
else {
return
}
view.setNeedsLayout()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated);
resumeIfNeeded()
}
public override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
guard let window = view.window,
let windowScene = window.windowScene,
windowScene.activationState == .foregroundActive
else {
return
}
let layoutMode = BKLayoutMode(rawValue: _sessionParams.layoutMode) ?? BKLayoutMode.default
_termView.additionalInsets = LayoutManager.buildSafeInsets(for: self, andMode: layoutMode)
_termView.layoutLockedFrame = _sessionParams.layoutLockedFrame
_termView.layoutLocked = _sessionParams.layoutLocked
}
public override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
_sessionParams.viewSize = view.bounds.size
}
@objc public func terminate() {
_termDevice.delegate = nil
_termView.terminate()
_session?.kill()
}
@objc public func lockLayout() {
_sessionParams.layoutLocked = true
_sessionParams.layoutLockedFrame = _termView.webViewFrame()
}
@objc public func unlockLayout() {
_sessionParams.layoutLocked = false
view.setNeedsLayout()
}
@objc public func isRunningCmd() -> Bool {
return _session?.isRunningCmd() ?? false
}
@objc public func scaleWithPich(_ pinch: UIPinchGestureRecognizer) {
switch pinch.state {
case .began: fallthrough
case .ended:
_fontSizeBeforeScaling = _sessionParams.fontSize
case .changed:
guard let initialSize = _fontSizeBeforeScaling else {
return
}
let newSize = Int(round(CGFloat(initialSize) * pinch.scale))
guard newSize != _sessionParams.fontSize else {
return
}
_termView.setFontSize(newSize as NSNumber)
default: break
}
}
deinit {
NotificationCenter.default.removeObserver(self)
_session?.delegate = nil
_session = nil
}
}
extension TermController: SessionDelegate {
public func indexCommand(_ cmdLine: String!) {
// TODO:
}
public func sessionFinished() {
if _sessionParams.hasEncodedState() {
_session?.delegate = nil
_session = nil
return
}
delegate?.terminalHangup(control: self)
}
}
let _apiRoutes:[String: (MCPSession, String) -> AnyPublisher<String, Never>] = [
"history.search": History.searchAPI,
"completion.for": Complete.forAPI
]
extension TermController: TermDeviceDelegate {
func apiCall(_ api: String!, andRequest request: String!) {
guard
let api = api,
let session = _session,
let call = _apiRoutes[api]
else {
return
}
weak var termView = _termView
_ = call(session, request)
.receive(on: RunLoop.main)
.sink { termView?.apiResponse(api, response: $0) }
}
public func deviceIsReady() {
startSession()
}
public func deviceSizeChanged() {
_sessionParams.rows = _termDevice.rows
_sessionParams.cols = _termDevice.cols
delegate?.terminalDidResize?(control: self)
_session?.sigwinch()
}
public func viewFontSizeChanged(_ size: Int) {
_sessionParams.fontSize = size
_termDevice.input?.reset()
}
public func handleControl(_ control: String!) -> Bool {
return _session?.handleControl(control) ?? false
}
public func deviceFocused() {
_session?.setActiveSession()
view.setNeedsLayout()
}
public func viewController() -> UIViewController! {
return self
}
public func lineSubmitted(_ line: String!) {
_session?.enqueueCommand(line)
}
}
extension TermController: SuspendableSession {
var meta: SessionMeta { _meta }
var _decodableKey: String { "params" }
func startSession() {
guard _session == nil
else {
if view.bounds.size != _sessionParams.viewSize {
_session?.sigwinch()
}
return
}
_session = MCPSession(
device: _termDevice,
andParams: _sessionParams)
_session?.delegate = self
_session?.execute(withArgs: "")
if view.bounds.size != _sessionParams.viewSize {
_session?.sigwinch()
}
}
func resume(with unarchiver: NSKeyedUnarchiver) {
guard
unarchiver.containsValue(forKey: _decodableKey),
let params = unarchiver.decodeObject(of: MCPParams.self, forKey: _decodableKey)
else {
return
}
_sessionParams = params
_session?.sessionParams = params
if _sessionParams.hasEncodedState() {
_session?.execute(withArgs: "")
}
if view.bounds.size != _sessionParams.viewSize {
_session?.sigwinch()
}
}
func suspendedSession(with archiver: NSKeyedArchiver) {
guard
let session = _session
else {
return
}
_sessionParams.cleanEncodedState()
session.suspend()
let hasEncodedState = _sessionParams.hasEncodedState()
debugPrint("has encoded state", hasEncodedState)
archiver.encode(_sessionParams, forKey: _decodableKey)
}
}