forked from ish-app/ish
-
Notifications
You must be signed in to change notification settings - Fork 0
/
TerminalViewController.m
468 lines (412 loc) · 18.3 KB
/
TerminalViewController.m
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
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
//
// ViewController.m
// iSH
//
// Created by Theodore Dubois on 10/17/17.
//
#import "TerminalViewController.h"
#import "AppDelegate.h"
#import "TerminalView.h"
#import "BarButton.h"
#import "ArrowBarButton.h"
#import "UserPreferences.h"
#import "AboutViewController.h"
#import "NSObject+SaneKVO.h"
#include "kernel/init.h"
#include "kernel/task.h"
#include "kernel/calls.h"
#include "fs/devices.h"
@interface TerminalViewController () <UIGestureRecognizerDelegate>
@property UITapGestureRecognizer *tapRecognizer;
@property (weak, nonatomic) IBOutlet TerminalView *termView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomConstraint;
@property (weak, nonatomic) IBOutlet UIButton *tabKey;
@property (weak, nonatomic) IBOutlet UIButton *controlKey;
@property (weak, nonatomic) IBOutlet UIButton *escapeKey;
@property (strong, nonatomic) IBOutletCollection(id) NSArray *barButtons;
@property (strong, nonatomic) IBOutletCollection(id) NSArray *barControls;
@property (weak, nonatomic) IBOutlet UIInputView *barView;
@property (weak, nonatomic) IBOutlet UIStackView *bar;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *barTop;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *barBottom;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *barLeading;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *barTrailing;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *barButtonWidth;
@property (weak, nonatomic) IBOutlet UIButton *infoButton;
@property (weak, nonatomic) IBOutlet UIButton *pasteButton;
@property (weak, nonatomic) IBOutlet UIButton *hideKeyboardButton;
@property int sessionPid;
@property (nonatomic) Terminal *sessionTerminal;
@property int sessionTerminalNumber;
@property BOOL ignoreKeyboardMotion;
@property (nonatomic) BOOL hasExternalKeyboard;
@end
@implementation TerminalViewController
- (void)viewDidLoad {
[super viewDidLoad];
int bootError = [AppDelegate bootError];
if (bootError < 0) {
NSString *message = [NSString stringWithFormat:@"could not boot"];
NSString *subtitle = [NSString stringWithFormat:@"error code %d", bootError];
if (bootError == _EINVAL)
subtitle = [subtitle stringByAppendingString:@"\n(try reinstalling the app, see release notes for details)"];
[self showMessage:message subtitle:subtitle];
NSLog(@"boot failed with code %d", bootError);
}
self.termView.terminal = self.terminal;
[self.termView becomeFirstResponder];
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
[center addObserver:self
selector:@selector(keyboardDidSomething:)
name:UIKeyboardWillChangeFrameNotification
object:nil];
[center addObserver:self
selector:@selector(keyboardDidSomething:)
name:UIKeyboardDidChangeFrameNotification
object:nil];
[self _updateStyleFromPreferences:NO];
if (UIDevice.currentDevice.userInterfaceIdiom == UIUserInterfaceIdiomPad) {
[self.bar removeArrangedSubview:self.hideKeyboardButton];
[self.hideKeyboardButton removeFromSuperview];
}
if (UIDevice.currentDevice.userInterfaceIdiom == UIUserInterfaceIdiomPhone) {
self.barView.frame = CGRectMake(0, 0, 100, 48);
} else {
self.barView.frame = CGRectMake(0, 0, 100, 55);
}
// SF Symbols is cool
if (@available(iOS 13, *)) {
[self.infoButton setImage:[UIImage systemImageNamed:@"gear"] forState:UIControlStateNormal];
[self.pasteButton setImage:[UIImage systemImageNamed:@"doc.on.clipboard"] forState:UIControlStateNormal];
[self.hideKeyboardButton setImage:[UIImage systemImageNamed:@"keyboard.chevron.compact.down"] forState:UIControlStateNormal];
[self.tabKey setTitle:nil forState:UIControlStateNormal];
[self.tabKey setImage:[UIImage systemImageNamed:@"arrow.right.to.line.alt"] forState:UIControlStateNormal];
[self.controlKey setTitle:nil forState:UIControlStateNormal];
[self.controlKey setImage:[UIImage systemImageNamed:@"control"] forState:UIControlStateNormal];
[self.escapeKey setTitle:nil forState:UIControlStateNormal];
[self.escapeKey setImage:[UIImage systemImageNamed:@"escape"] forState:UIControlStateNormal];
}
[UserPreferences.shared observe:@[@"theme", @"hideExtraKeysWithExternalKeyboard"]
options:0 owner:self usingBlock:^(typeof(self) self) {
[self _updateStyleFromPreferences:YES];
}];
}
- (void)awakeFromNib {
[super awakeFromNib];
[NSNotificationCenter.defaultCenter addObserver:self
selector:@selector(processExited:)
name:ProcessExitedNotification
object:nil];
}
- (void)viewDidAppear:(BOOL)animated {
[AppDelegate maybePresentStartupMessageOnViewController:self];
[super viewDidAppear:animated];
}
- (void)startNewSession {
int err = [self startSession];
if (err < 0) {
[self showMessage:@"could not start session"
subtitle:[NSString stringWithFormat:@"error code %d", err]];
}
}
- (void)reconnectSessionFromTerminalUUID:(NSUUID *)uuid {
self.sessionTerminal = [Terminal terminalWithUUID:uuid];
if (self.sessionTerminal == nil)
[self startNewSession];
}
- (NSUUID *)sessionTerminalUUID {
return self.terminal.uuid;
}
- (int)startSession {
int err = become_new_init_child();
if (err < 0)
return err;
struct tty *tty;
self.sessionTerminal = nil;
Terminal *terminal = [Terminal createPseudoTerminal:&tty];
if (terminal == nil) {
NSAssert(IS_ERR(tty), @"tty should be error");
return (int) PTR_ERR(tty);
}
self.sessionTerminal = terminal;
self.sessionTerminalNumber = tty->num;
NSString *stdioFile = [NSString stringWithFormat:@"/dev/pts/%d", tty->num];
err = create_stdio(stdioFile.fileSystemRepresentation, TTY_PSEUDO_SLAVE_MAJOR, tty->num);
if (err < 0)
return err;
tty_release(tty);
char argv[4096];
NSArray<NSString *> *command = UserPreferences.shared.launchCommand;
[Terminal convertCommand:command toArgs:argv limitSize:sizeof(argv)];
const char *envp = "TERM=xterm-256color\0";
err = do_execve(command[0].UTF8String, command.count, argv, envp);
if (err < 0)
return err;
self.sessionPid = current->pid;
task_start(current);
return 0;
}
- (void)processExited:(NSNotification *)notif {
int pid = [notif.userInfo[@"pid"] intValue];
if (pid != self.sessionPid)
return;
[self.sessionTerminal destroy];
self.sessionTerminalNumber = 0;
// On iOS 13, there are multiple windows, so just close this one.
if (@available(iOS 13, *)) {
// On iPhone, destroying scenes will fail, but the error doesn't actually go to the error handler, which is really stupid. Apple doesn't fix bugs, so I'm forced to just add a check here.
if (UIDevice.currentDevice.userInterfaceIdiom == UIUserInterfaceIdiomPad && self.sceneSession != nil) {
[UIApplication.sharedApplication requestSceneSessionDestruction:self.sceneSession options:nil errorHandler:^(NSError *error) {
NSLog(@"scene destruction error %@", error);
self.sceneSession = nil;
[self processExited:notif];
}];
return;
}
}
current = NULL; // it's been freed
[self startNewSession];
}
- (void)showMessage:(NSString *)message subtitle:(NSString *)subtitle {
dispatch_async(dispatch_get_main_queue(), ^{
UIAlertController *alert = [UIAlertController alertControllerWithTitle:message message:subtitle preferredStyle:UIAlertControllerStyleAlert];
[alert addAction:[UIAlertAction actionWithTitle:@"k"
style:UIAlertActionStyleDefault
handler:nil]];
[self presentViewController:alert animated:YES completion:nil];
});
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
if (object == [UserPreferences shared]) {
[self _updateStyleFromPreferences:YES];
} else {
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}
}
- (void)_updateStyleFromPreferences:(BOOL)animated {
NSTimeInterval duration = animated ? 0.1 : 0;
[UIView animateWithDuration:duration animations:^{
self.view.backgroundColor = UserPreferences.shared.theme.backgroundColor;
UIKeyboardAppearance keyAppearance = UserPreferences.shared.theme.keyboardAppearance;
self.termView.keyboardAppearance = keyAppearance;
for (BarButton *button in self.barButtons) {
button.keyAppearance = keyAppearance;
}
UIColor *tintColor = keyAppearance == UIKeyboardAppearanceLight ? UIColor.blackColor : UIColor.whiteColor;
for (UIControl *control in self.barControls) {
control.tintColor = tintColor;
}
}];
UIView *oldBarView = self.termView.inputAccessoryView;
if (UserPreferences.shared.hideExtraKeysWithExternalKeyboard && self.hasExternalKeyboard) {
self.termView.inputAccessoryView = nil;
} else {
self.termView.inputAccessoryView = self.barView;
}
if (self.termView.inputAccessoryView != oldBarView && self.termView.isFirstResponder) {
self.ignoreKeyboardMotion = YES; // avoid infinite recursion
[self.termView reloadInputViews];
self.ignoreKeyboardMotion = NO;
}
[self setNeedsStatusBarAppearanceUpdate];
}
- (void)_updateStyleAnimated {
[self _updateStyleFromPreferences:YES];
}
- (UIStatusBarStyle)preferredStatusBarStyle {
return UserPreferences.shared.theme.statusBarStyle;
}
- (BOOL)prefersStatusBarHidden {
BOOL isIPhoneX = self.view.window.safeAreaInsets.top > 20;
return !isIPhoneX;
}
- (void)keyboardDidSomething:(NSNotification *)notification {
if (self.ignoreKeyboardMotion)
return;
CGRect keyboardFrame = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
if (CGRectEqualToRect(keyboardFrame, CGRectZero))
return;
NSLog(@"%@ %@", notification.name, [NSValue valueWithCGRect:keyboardFrame]);
self.hasExternalKeyboard = keyboardFrame.size.height < 100;
CGFloat pad = UIScreen.mainScreen.bounds.size.height - keyboardFrame.origin.y;
if (pad != keyboardFrame.size.height) {
pad = 0; // keyboard is not right at the bottom of the screen, must be floating or something
}
if (pad == 0) {
pad = self.view.safeAreaInsets.bottom;
}
// NSLog(@"pad %f", pad);
self.bottomConstraint.constant = pad;
BOOL initialLayout = self.termView.needsUpdateConstraints;
[self.view setNeedsUpdateConstraints];
if (!initialLayout) {
// if initial layout hasn't happened yet, the terminal view is going to be at a really weird place, so animating it is going to look really bad
NSNumber *interval = notification.userInfo[UIKeyboardAnimationDurationUserInfoKey];
NSNumber *curve = notification.userInfo[UIKeyboardAnimationCurveUserInfoKey];
[UIView animateWithDuration:interval.doubleValue
delay:0
options:curve.integerValue << 16
animations:^{
[self.view layoutIfNeeded];
}
completion:nil];
}
}
- (void)setHasExternalKeyboard:(BOOL)hasExternalKeyboard {
_hasExternalKeyboard = hasExternalKeyboard;
[self _updateStyleFromPreferences:YES];
}
- (void)ishExited:(NSNotification *)notification {
[self performSelectorOnMainThread:@selector(displayExitThing) withObject:nil waitUntilDone:YES];
}
- (void)displayExitThing {
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"attempted to kill init" message:nil preferredStyle:UIAlertControllerStyleAlert];
[alert addAction:[UIAlertAction actionWithTitle:@"exit" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
id delegate = [UIApplication sharedApplication].delegate;
[delegate exitApp];
}]];
if ([UserPreferences.shared hasChangedLaunchCommand])
[alert addAction:[UIAlertAction actionWithTitle:@"i typed the init command wrong, let me fix it" style:UIAlertActionStyleDefault handler:nil]];
[self presentViewController:alert animated:YES completion:nil];
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqualToString:@"embed"]) {
// You might want to check if this is your embed segue here
// in case there are other segues triggered from this view controller.
segue.destinationViewController.view.translatesAutoresizingMaskIntoConstraints = NO;
}
}
#pragma mark Bar
- (IBAction)showAbout:(id)sender {
UINavigationController *navigationController = [[UIStoryboard storyboardWithName:@"About" bundle:nil] instantiateInitialViewController];
if ([sender isKindOfClass:[UIGestureRecognizer class]]) {
UIGestureRecognizer *recognizer = sender;
if (recognizer.state == UIGestureRecognizerStateBegan) {
AboutViewController *aboutViewController = (AboutViewController *) navigationController.topViewController;
aboutViewController.includeDebugPanel = YES;
} else {
return;
}
}
[self presentViewController:navigationController animated:YES completion:nil];
[self.termView resignFirstResponder];
}
- (void)resizeBar {
CGSize screen = UIScreen.mainScreen.bounds.size;
CGSize bar = self.barView.bounds.size;
// set sizing parameters on bar
// numbers stolen from iVim and modified somewhat
if (UIDevice.currentDevice.userInterfaceIdiom == UIUserInterfaceIdiomPhone) {
// phone
[self setBarHorizontalPadding:6 verticalPadding:6 buttonWidth:32];
} else if (bar.width == screen.width || bar.width == screen.height) {
// full-screen ipad
[self setBarHorizontalPadding:15 verticalPadding:8 buttonWidth:43];
} else if (bar.width <= 320) {
// slide over
[self setBarHorizontalPadding:8 verticalPadding:8 buttonWidth:26];
} else {
// split view
[self setBarHorizontalPadding:10 verticalPadding:8 buttonWidth:36];
}
[UIView performWithoutAnimation:^{
[self.barView layoutIfNeeded];
}];
}
- (void)setBarHorizontalPadding:(CGFloat)horizontal verticalPadding:(CGFloat)vertical buttonWidth:(CGFloat)buttonWidth {
self.barLeading.constant = self.barTrailing.constant = horizontal;
self.barTop.constant = self.barBottom.constant = vertical;
self.barButtonWidth.constant = buttonWidth;
}
- (IBAction)pressEscape:(id)sender {
[self pressKey:@"\x1b"];
}
- (IBAction)pressTab:(id)sender {
[self pressKey:@"\t"];
}
- (void)pressKey:(NSString *)key {
[self.termView insertText:key];
}
- (IBAction)pressControl:(id)sender {
self.controlKey.selected = !self.controlKey.selected;
}
- (IBAction)pressArrow:(ArrowBarButton *)sender {
switch (sender.direction) {
case ArrowUp: [self pressKey:[self.terminal arrow:'A']]; break;
case ArrowDown: [self pressKey:[self.terminal arrow:'B']]; break;
case ArrowLeft: [self pressKey:[self.terminal arrow:'D']]; break;
case ArrowRight: [self pressKey:[self.terminal arrow:'C']]; break;
case ArrowNone: break;
}
}
- (void)switchTerminal:(UIKeyCommand *)sender {
unsigned i = (unsigned) sender.input.integerValue;
if (i == 7)
self.terminal = self.sessionTerminal;
else
self.terminal = [Terminal terminalWithType:TTY_CONSOLE_MAJOR number:i];
}
- (void)increaseFontSize:(UIKeyCommand *)command {
self.termView.overrideFontSize = self.termView.effectiveFontSize + 1;
}
- (void)decreaseFontSize:(UIKeyCommand *)command {
self.termView.overrideFontSize = self.termView.effectiveFontSize - 1;
}
- (void)resetFontSize:(UIKeyCommand *)command {
self.termView.overrideFontSize = 0;
}
- (NSArray<UIKeyCommand *> *)keyCommands {
static NSMutableArray<UIKeyCommand *> *commands = nil;
if (commands == nil) {
commands = [NSMutableArray new];
for (unsigned i = 1; i <= 7; i++) {
[commands addObject:
[UIKeyCommand keyCommandWithInput:[NSString stringWithFormat:@"%d", i]
modifierFlags:UIKeyModifierCommand|UIKeyModifierAlternate|UIKeyModifierShift
action:@selector(switchTerminal:)]];
}
[commands addObject:
[UIKeyCommand keyCommandWithInput:@"+"
modifierFlags:UIKeyModifierCommand
action:@selector(increaseFontSize:)
discoverabilityTitle:@"Increase Font Size"]];
[commands addObject:
[UIKeyCommand keyCommandWithInput:@"="
modifierFlags:UIKeyModifierCommand
action:@selector(increaseFontSize:)]];
[commands addObject:
[UIKeyCommand keyCommandWithInput:@"-"
modifierFlags:UIKeyModifierCommand
action:@selector(decreaseFontSize:)
discoverabilityTitle:@"Decrease Font Size"]];
[commands addObject:
[UIKeyCommand keyCommandWithInput:@"0"
modifierFlags:UIKeyModifierCommand
action:@selector(resetFontSize:)
discoverabilityTitle:@"Reset Font Size"]];
[commands addObject:
[UIKeyCommand keyCommandWithInput:@","
modifierFlags:UIKeyModifierCommand
action:@selector(showAbout:)
discoverabilityTitle:@"Settings"]];
}
return commands;
}
- (void)setTerminal:(Terminal *)terminal {
_terminal = terminal;
self.termView.terminal = self.terminal;
}
- (void)setSessionTerminal:(Terminal *)sessionTerminal {
if (_terminal == _sessionTerminal)
self.terminal = sessionTerminal;
_sessionTerminal = sessionTerminal;
}
@end
@interface BarView : UIInputView
@property (weak) IBOutlet TerminalViewController *terminalViewController;
@end
@implementation BarView
- (void)layoutSubviews {
[self.terminalViewController resizeBar];
}
@end