-
Notifications
You must be signed in to change notification settings - Fork 577
/
AppDelegate.m
391 lines (316 loc) · 13.1 KB
/
AppDelegate.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
////////////////////////////////////////////////////////////////////////////////
//
// 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 "AppDelegate.h"
#import "BKiCloudSyncHandler.h"
#import <BlinkConfig/BlinkPaths.h>
#import "BLKDefaults.h"
#import <BlinkConfig/BKHosts.h>
#import <BlinkConfig/BKPubKey.h>
#import <ios_system/ios_system.h>
#import <UserNotifications/UserNotifications.h>
#include <libssh/callbacks.h>
#include "xcall.h"
#include "Blink-Swift.h"
#ifdef BLINK_BUILD_ENABLED
extern void build_auto_start_wg_ports(void);
extern void rebind_ports(void);
#endif
@import CloudKit;
@interface AppDelegate () <UNUserNotificationCenterDelegate>
@end
@implementation AppDelegate {
NSTimer *_suspendTimer;
UIBackgroundTaskIdentifier _suspendTaskId;
BOOL _suspendedMode;
BOOL _enforceSuspension;
}
void __on_pipebroken_signal(int signum){
NSLog(@"PIPE is broken");
}
void __setupProcessEnv(void) {
NSBundle *mainBundle = [NSBundle mainBundle];
int forceOverwrite = 1;
NSString *SSL_CERT_FILE = [mainBundle pathForResource:@"cacert" ofType:@"pem"];
setenv("SSL_CERT_FILE", SSL_CERT_FILE.UTF8String, forceOverwrite);
NSString *locales_path = [mainBundle pathForResource:@"locales" ofType:@"bundle"];
setenv("PATH_LOCALE", locales_path.UTF8String, forceOverwrite);
setlocale(LC_ALL, "UTF-8");
setenv("TERM", "xterm-256color", forceOverwrite);
setenv("LANG", "en_US.UTF-8", forceOverwrite);
setenv("VIMRUNTIME", [[mainBundle resourcePath] stringByAppendingPathComponent:@"/vim"].UTF8String, 1);
ssh_threads_set_callbacks(ssh_threads_get_pthread());
ssh_init();
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[Migrator perform];
[BlinkPaths cleanedSymlinksInHomeDirectory];
[AppDelegate reloadDefaults];
[[UIView appearance] setTintColor:[UIColor blinkTint]];
signal(SIGPIPE, __on_pipebroken_signal);
dispatch_queue_t bgQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0);
dispatch_async(bgQueue, ^{
[BlinkPaths linkDocumentsIfNeeded];
[BlinkPaths linkICloudDriveIfNeeded];
});
sideLoading = false; // Turn off extra commands from iOS system
initializeEnvironment(); // initialize environment variables for iOS system
dispatch_async(bgQueue, ^{
addCommandList([[NSBundle mainBundle] pathForResource:@"blinkCommandsDictionary" ofType:@"plist"]); // Load blink commands to ios_system
__setupProcessEnv(); // we should call this after ios_system initializeEnvironment to override its defaults.
[AppDelegate _loadProfileVars];
});
NSString *homePath = BlinkPaths.homePath;
setenv("HOME", homePath.UTF8String, 1);
setenv("SSH_HOME", homePath.UTF8String, 1);
setenv("CURL_HOME", homePath.UTF8String, 1);
NSNotificationCenter *nc = NSNotificationCenter.defaultCenter;
[nc addObserver:self
selector:@selector(_onSceneDidEnterBackground:)
name:UISceneDidEnterBackgroundNotification object:nil];
[nc addObserver:self
selector:@selector(_onSceneWillEnterForeground:)
name:UISceneWillEnterForegroundNotification object:nil];
[nc addObserver:self
selector:@selector(_onSceneDidActiveNotification:)
name:UISceneDidActivateNotification object:nil];
[nc addObserver:self
selector: @selector(_onScreenConnect)
name:UIScreenDidConnectNotification object:nil];
[UNUserNotificationCenter currentNotificationCenter].delegate = self;
// [nc addObserver:self selector:@selector(_logEvent:) name:nil object:nil];
// [nc addObserver:self selector:@selector(_active) name:@"UIApplicationSystemNavigationActionChangedNotification" object:nil];
[UIApplication sharedApplication].applicationSupportsShakeToEdit = NO;
[_NSFileProviderManager syncWithBKHosts];
[PurchasesUserModelObjc preparePurchasesUserModel];
#ifdef BLINK_BUILD_ENABLED
build_auto_start_wg_ports();
#endif
return YES;
}
//- (void)_active {
// [[SmarterTermInput shared] realBecomeFirstResponder];
//}
//- (void)_logEvent:(NSNotification *)n {
// NSLog(@"event, %@, %@", n.name, n.userInfo);
// if ([n.name isEqualToString:@"UIApplicationSystemNavigationActionChangedNotification"]) {
// [[SmarterTermInput shared] realBecomeFirstResponder];
// }
//
//}
+ (void)reloadDefaults {
[BLKDefaults loadDefaults];
[BKPubKey loadIDS];
[BKHosts loadHosts];
[AppDelegate _loadProfileVars];
}
+ (void)_loadProfileVars {
NSCharacterSet *whiteSpace = [NSCharacterSet whitespaceCharacterSet];
NSString *profile = [NSString stringWithContentsOfFile:[BlinkPaths blinkProfileFile] encoding:NSUTF8StringEncoding error:nil];
[profile enumerateLinesUsingBlock:^(NSString * _Nonnull line, BOOL * _Nonnull stop) {
NSMutableArray<NSString *> *parts = [[line componentsSeparatedByString:@"="] mutableCopy];
if (parts.count < 2) {
return;
}
NSString *varName = [parts.firstObject stringByTrimmingCharactersInSet:whiteSpace];
if (varName.length == 0) {
return;
}
[parts removeObjectAtIndex:0];
NSString *varValue = [[parts componentsJoinedByString:@"="] stringByTrimmingCharactersInSet:whiteSpace];
if ([varValue hasSuffix:@"\""] || [varValue hasPrefix:@"\""]) {
NSData *data = [varValue dataUsingEncoding:NSUTF8StringEncoding];
varValue = [varValue substringWithRange:NSMakeRange(1, varValue.length - 1)];
if (data) {
id value = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
if ([value isKindOfClass:[NSString class]]) {
varValue = value;
}
}
}
if (varValue.length == 0) {
return;
}
BOOL forceOverwrite = 1;
setenv(varName.UTF8String, varValue.UTF8String, forceOverwrite);
}];
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
[[BKiCloudSyncHandler sharedHandler]checkForReachabilityAndSync:nil];
// TODO: pass completion handler.
}
// MARK: NSUserActivity
- (BOOL)application:(UIApplication *)application willContinueUserActivityWithType:(NSString *)userActivityType
{
return YES;
}
- (BOOL)application:(UIApplication *)application continueUserActivity:(NSUserActivity *)userActivity restorationHandler:(void (^)(NSArray * _Nullable))restorationHandler
{
return YES;
}
- (BOOL)application:(UIApplication *)application shouldAllowExtensionPointIdentifier:(NSString *)extensionPointIdentifier {
if ([extensionPointIdentifier isEqualToString: UIApplicationKeyboardExtensionPointIdentifier]) {
return ![BLKDefaults disableCustomKeyboards];
}
return YES;
}
#pragma mark - State saving and restoring
- (void)applicationProtectedDataWillBecomeUnavailable:(UIApplication *)application
{
// If a scene is not yet in the background, then await for it to suspend
NSArray * scenes = UIApplication.sharedApplication.connectedScenes.allObjects;
for (UIScene *scene in scenes) {
if (scene.activationState == UISceneActivationStateForegroundActive || scene.activationState == UISceneActivationStateForegroundInactive) {
_enforceSuspension = true;
return;
}
}
[self _suspendApplicationOnProtectedDataWillBecomeUnavailable];
}
- (void)applicationWillTerminate:(UIApplication *)application
{
[self _suspendApplicationOnWillTerminate];
}
- (void)_startMonitoringForSuspending
{
if (_suspendedMode) {
return;
}
UIApplication *application = [UIApplication sharedApplication];
[self _cancelApplicationSuspendTask];
_suspendTaskId = [application beginBackgroundTaskWithName:@"Suspend" expirationHandler:^{
[self _suspendApplicationWithExpirationHandler];
}];
NSTimeInterval time = MIN(application.backgroundTimeRemaining * 0.9, 5 * 60);
[_suspendTimer invalidate];
_suspendTimer = [NSTimer scheduledTimerWithTimeInterval:time
target:self
selector:@selector(_suspendApplicationWithSuspendTimer)
userInfo:nil
repeats:NO];
}
- (void)_cancelApplicationSuspendTask {
[_suspendTimer invalidate];
if (_suspendTaskId != UIBackgroundTaskInvalid) {
[[UIApplication sharedApplication] endBackgroundTask:_suspendTaskId];
}
_suspendTaskId = UIBackgroundTaskInvalid;
}
- (void)_cancelApplicationSuspend {
[self _cancelApplicationSuspendTask];
// We can't resume if we don't have access to protected data
if (UIApplication.sharedApplication.isProtectedDataAvailable) {
if (_suspendedMode) {
#ifdef BLINK_BUILD_ENABLED
rebind_ports();
#endif
}
_suspendedMode = NO;
}
}
// Simple wrappers to get the reason of failure from call stack
- (void)_suspendApplicationWithSuspendTimer {
[self _suspendApplication];
}
- (void)_suspendApplicationWithExpirationHandler {
[self _suspendApplication];
}
- (void)_suspendApplicationOnWillTerminate {
[self _suspendApplication];
}
- (void)_suspendApplicationOnProtectedDataWillBecomeUnavailable {
[self _suspendApplication];
}
- (void)_suspendApplication {
[_suspendTimer invalidate];
_enforceSuspension = false;
if (_suspendedMode) {
return;
}
[[SessionRegistry shared] suspend];
_suspendedMode = YES;
[self _cancelApplicationSuspendTask];
}
#pragma mark - Scenes
- (UISceneConfiguration *) application:(UIApplication *)application
configurationForConnectingSceneSession:(UISceneSession *)connectingSceneSession
options:(UISceneConnectionOptions *)options {
for (NSUserActivity * activity in options.userActivities) {
if ([activity.activityType isEqual:@"com.blink.whatsnew"]) {
return [UISceneConfiguration configurationWithName:@"whatsnew"
sessionRole:connectingSceneSession.role];
}
}
return [UISceneConfiguration configurationWithName:@"main"
sessionRole:connectingSceneSession.role];
}
- (void)application:(UIApplication *)application didDiscardSceneSessions:(NSSet<UISceneSession *> *)sceneSessions {
[SpaceController onDidDiscardSceneSessions: sceneSessions];
}
- (void)_onSceneDidEnterBackground:(NSNotification *)notification {
NSArray * scenes = UIApplication.sharedApplication.connectedScenes.allObjects;
for (UIScene *scene in scenes) {
if (scene.activationState == UISceneActivationStateForegroundActive || scene.activationState == UISceneActivationStateForegroundInactive) {
return;
}
}
if (_enforceSuspension) {
[self _suspendApplication];
} else {
[self _startMonitoringForSuspending];
}
}
- (void)_onSceneWillEnterForeground:(NSNotification *)notification {
[self _cancelApplicationSuspend];
}
- (void)_onSceneDidActiveNotification:(NSNotification *)notification {
[self _cancelApplicationSuspend];
}
- (void)_onScreenConnect {
[BLKDefaults applyExternalScreenCompensation:BLKDefaults.overscanCompensation];
}
#pragma mark - UNUserNotificationCenterDelegate
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {
UNNotificationPresentationOptions opts = UNNotificationPresentationOptionSound | UNNotificationPresentationOptionList | UNNotificationPresentationOptionBanner | UNNotificationPresentationOptionBadge;
completionHandler(opts);
}
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler {
SceneDelegate *sceneDelegate = (SceneDelegate *)response.targetScene.delegate;
SpaceController *ctrl = sceneDelegate.spaceController;
[ctrl moveToShellWithKey:response.notification.request.content.threadIdentifier];
completionHandler();
}
#pragma mark - Menu Building
- (void)buildMenuWithBuilder:(id<UIMenuBuilder>)builder {
if (builder.system == UIMenuSystem.mainSystem) {
[MenuController buildMenuWith:builder];
}
}
@end