-
Notifications
You must be signed in to change notification settings - Fork 182
/
Copy pathFBCustomCommands.m
661 lines (594 loc) · 27.3 KB
/
FBCustomCommands.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
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
#import "FBCustomCommands.h"
#import <XCTest/XCUIDevice.h>
#import <CoreLocation/CoreLocation.h>
#import "FBConfiguration.h"
#import "FBKeyboard.h"
#import "FBNotificationsHelper.h"
#import "FBPasteboard.h"
#import "FBResponsePayload.h"
#import "FBRoute.h"
#import "FBRouteRequest.h"
#import "FBRunLoopSpinner.h"
#import "FBScreen.h"
#import "FBSession.h"
#import "FBXCodeCompatibility.h"
#import "XCUIApplication.h"
#import "XCUIApplication+FBHelpers.h"
#import "XCUIDevice+FBHelpers.h"
#import "XCUIElement.h"
#import "XCUIElement+FBIsVisible.h"
#import "XCUIElementQuery.h"
#import "FBUnattachedAppLauncher.h"
#import "sys/utsname.h"
@implementation FBCustomCommands
+ (NSArray *)routes
{
return
@[
[[FBRoute POST:@"/timeouts"] respondWithTarget:self action:@selector(handleTimeouts:)],
[[FBRoute POST:@"/wda/homescreen"].withoutSession respondWithTarget:self action:@selector(handleHomescreenCommand:)],
[[FBRoute POST:@"/wda/deactivateApp"] respondWithTarget:self action:@selector(handleDeactivateAppCommand:)],
[[FBRoute POST:@"/wda/keyboard/dismiss"] respondWithTarget:self action:@selector(handleDismissKeyboardCommand:)],
[[FBRoute POST:@"/wda/lock"].withoutSession respondWithTarget:self action:@selector(handleLock:)],
[[FBRoute POST:@"/wda/lock"] respondWithTarget:self action:@selector(handleLock:)],
[[FBRoute POST:@"/wda/unlock"].withoutSession respondWithTarget:self action:@selector(handleUnlock:)],
[[FBRoute POST:@"/wda/unlock"] respondWithTarget:self action:@selector(handleUnlock:)],
[[FBRoute GET:@"/wda/locked"].withoutSession respondWithTarget:self action:@selector(handleIsLocked:)],
[[FBRoute GET:@"/wda/locked"] respondWithTarget:self action:@selector(handleIsLocked:)],
[[FBRoute GET:@"/wda/screen"] respondWithTarget:self action:@selector(handleGetScreen:)],
[[FBRoute GET:@"/wda/activeAppInfo"] respondWithTarget:self action:@selector(handleActiveAppInfo:)],
[[FBRoute GET:@"/wda/activeAppInfo"].withoutSession respondWithTarget:self action:@selector(handleActiveAppInfo:)],
#if !TARGET_OS_TV // tvOS does not provide relevant APIs
[[FBRoute POST:@"/wda/setPasteboard"] respondWithTarget:self action:@selector(handleSetPasteboard:)],
[[FBRoute POST:@"/wda/setPasteboard"].withoutSession respondWithTarget:self action:@selector(handleSetPasteboard:)],
[[FBRoute POST:@"/wda/getPasteboard"] respondWithTarget:self action:@selector(handleGetPasteboard:)],
[[FBRoute POST:@"/wda/getPasteboard"].withoutSession respondWithTarget:self action:@selector(handleGetPasteboard:)],
[[FBRoute GET:@"/wda/batteryInfo"] respondWithTarget:self action:@selector(handleGetBatteryInfo:)],
#endif
[[FBRoute POST:@"/wda/pressButton"] respondWithTarget:self action:@selector(handlePressButtonCommand:)],
// modified start tag
[[FBRoute POST:@"/wda/pressButton"].withoutSession respondWithTarget:self action:@selector(handlePressButtonCommand:)],
// end tag
[[FBRoute POST:@"/wda/performIoHidEvent"] respondWithTarget:self action:@selector(handlePeformIOHIDEvent:)],
// modified start tag
[[FBRoute POST:@"/wda/performIoHidEvent"].withoutSession respondWithTarget:self action:@selector(handlePeformIOHIDEvent:)],
[[FBRoute POST:@"/wda/deviceTap"] respondWithTarget:self action:@selector(handleDeviceTap:)],
[[FBRoute POST:@"/wda/deviceTap"].withoutSession respondWithTarget:self action:@selector(handleDeviceTap:)],
[[FBRoute POST:@"/wda/deviceSwipe"] respondWithTarget:self action:@selector(handleDeviceSwipe:)],
[[FBRoute POST:@"/wda/deviceSwipe"].withoutSession respondWithTarget:self action:@selector(handleDeviceSwipe:)],
// end tag
[[FBRoute POST:@"/wda/expectNotification"] respondWithTarget:self action:@selector(handleExpectNotification:)],
[[FBRoute POST:@"/wda/siri/activate"] respondWithTarget:self action:@selector(handleActivateSiri:)],
[[FBRoute POST:@"/wda/apps/launchUnattached"].withoutSession respondWithTarget:self action:@selector(handleLaunchUnattachedApp:)],
[[FBRoute GET:@"/wda/device/info"] respondWithTarget:self action:@selector(handleGetDeviceInfo:)],
[[FBRoute POST:@"/wda/resetAppAuth"] respondWithTarget:self action:@selector(handleResetAppAuth:)],
[[FBRoute GET:@"/wda/device/info"].withoutSession respondWithTarget:self action:@selector(handleGetDeviceInfo:)],
[[FBRoute POST:@"/wda/device/appearance"].withoutSession respondWithTarget:self action:@selector(handleSetDeviceAppearance:)],
[[FBRoute GET:@"/wda/device/location"] respondWithTarget:self action:@selector(handleGetLocation:)],
[[FBRoute GET:@"/wda/device/location"].withoutSession respondWithTarget:self action:@selector(handleGetLocation:)],
#if !TARGET_OS_TV // tvOS does not provide relevant APIs
#if __clang_major__ >= 15
[[FBRoute POST:@"/wda/element/:uuid/keyboardInput"] respondWithTarget:self action:@selector(handleKeyboardInput:)],
#endif
[[FBRoute GET:@"/wda/simulatedLocation"] respondWithTarget:self action:@selector(handleGetSimulatedLocation:)],
[[FBRoute GET:@"/wda/simulatedLocation"].withoutSession respondWithTarget:self action:@selector(handleGetSimulatedLocation:)],
[[FBRoute POST:@"/wda/simulatedLocation"] respondWithTarget:self action:@selector(handleSetSimulatedLocation:)],
[[FBRoute POST:@"/wda/simulatedLocation"].withoutSession respondWithTarget:self action:@selector(handleSetSimulatedLocation:)],
[[FBRoute DELETE:@"/wda/simulatedLocation"] respondWithTarget:self action:@selector(handleClearSimulatedLocation:)],
[[FBRoute DELETE:@"/wda/simulatedLocation"].withoutSession respondWithTarget:self action:@selector(handleClearSimulatedLocation:)],
#endif
[[FBRoute OPTIONS:@"/*"].withoutSession respondWithTarget:self action:@selector(handlePingCommand:)],
];
}
#pragma mark - Commands
+ (id<FBResponsePayload>)handleHomescreenCommand:(FBRouteRequest *)request
{
NSError *error;
if (![[XCUIDevice sharedDevice] fb_goToHomescreenWithError:&error]) {
return FBResponseWithStatus([FBCommandStatus unknownErrorWithMessage:error.description
traceback:nil]);
}
return FBResponseWithOK();
}
+ (id<FBResponsePayload>)handleDeactivateAppCommand:(FBRouteRequest *)request
{
NSNumber *requestedDuration = request.arguments[@"duration"];
NSTimeInterval duration = (requestedDuration ? requestedDuration.doubleValue : 3.);
NSError *error;
if (![request.session.activeApplication fb_deactivateWithDuration:duration error:&error]) {
return FBResponseWithUnknownError(error);
}
return FBResponseWithOK();
}
+ (id<FBResponsePayload>)handleTimeouts:(FBRouteRequest *)request
{
// This method is intentionally not supported.
return FBResponseWithOK();
}
+ (id<FBResponsePayload>)handleDismissKeyboardCommand:(FBRouteRequest *)request
{
NSError *error;
BOOL isDismissed = [request.session.activeApplication fb_dismissKeyboardWithKeyNames:request.arguments[@"keyNames"]
error:&error];
return isDismissed
? FBResponseWithOK()
: FBResponseWithStatus([FBCommandStatus invalidElementStateErrorWithMessage:error.description
traceback:nil]);
}
+ (id<FBResponsePayload>)handlePingCommand:(FBRouteRequest *)request
{
return FBResponseWithOK();
}
#pragma mark - Helpers
+ (id<FBResponsePayload>)handleGetScreen:(FBRouteRequest *)request
{
FBSession *session = request.session;
CGSize statusBarSize = [FBScreen statusBarSizeForApplication:session.activeApplication];
return FBResponseWithObject(
@{
@"statusBarSize": @{@"width": @(statusBarSize.width),
@"height": @(statusBarSize.height),
},
@"scale": @([FBScreen scale]),
});
}
+ (id<FBResponsePayload>)handleLock:(FBRouteRequest *)request
{
NSError *error;
if (![[XCUIDevice sharedDevice] fb_lockScreen:&error]) {
return FBResponseWithUnknownError(error);
}
return FBResponseWithOK();
}
+ (id<FBResponsePayload>)handleIsLocked:(FBRouteRequest *)request
{
BOOL isLocked = [XCUIDevice sharedDevice].fb_isScreenLocked;
return FBResponseWithObject(isLocked ? @YES : @NO);
}
+ (id<FBResponsePayload>)handleUnlock:(FBRouteRequest *)request
{
NSError *error;
if (![[XCUIDevice sharedDevice] fb_unlockScreen:&error]) {
return FBResponseWithUnknownError(error);
}
return FBResponseWithOK();
}
+ (id<FBResponsePayload>)handleActiveAppInfo:(FBRouteRequest *)request
{
XCUIApplication *app = request.session.activeApplication ?: XCUIApplication.fb_activeApplication;
return FBResponseWithObject(@{
@"pid": @(app.processID),
@"bundleId": app.bundleID,
@"name": app.identifier,
@"processArguments": [self processArguments:app],
});
}
/**
* Returns current active app and its arguments of active session
*
* @return The dictionary of current active bundleId and its process/environment argumens
*
* @example
*
* [self currentActiveApplication]
* //=> {
* // "processArguments" : {
* // "env" : {
* // "HAPPY" : "testing"
* // },
* // "args" : [
* // "happy",
* // "tseting"
* // ]
* // }
*
* [self currentActiveApplication]
* //=> {}
*/
+ (NSDictionary *)processArguments:(XCUIApplication *)app
{
// Can be nil if no active activation is defined by XCTest
if (app == nil) {
return @{};
}
return
@{
@"args": app.launchArguments,
@"env": app.launchEnvironment
};
}
#if !TARGET_OS_TV
+ (id<FBResponsePayload>)handleSetPasteboard:(FBRouteRequest *)request
{
NSString *contentType = request.arguments[@"contentType"] ?: @"plaintext";
NSData *content = [[NSData alloc] initWithBase64EncodedString:(NSString *)request.arguments[@"content"]
options:NSDataBase64DecodingIgnoreUnknownCharacters];
if (nil == content) {
return FBResponseWithStatus([FBCommandStatus invalidArgumentErrorWithMessage:@"Cannot decode the pasteboard content from base64" traceback:nil]);
}
NSError *error;
if (![FBPasteboard setData:content forType:contentType error:&error]) {
return FBResponseWithUnknownError(error);
}
return FBResponseWithOK();
}
+ (id<FBResponsePayload>)handleGetPasteboard:(FBRouteRequest *)request
{
NSString *contentType = request.arguments[@"contentType"] ?: @"plaintext";
NSError *error;
id result = [FBPasteboard dataForType:contentType error:&error];
if (nil == result) {
return FBResponseWithUnknownError(error);
}
return FBResponseWithObject([result base64EncodedStringWithOptions:0]);
}
+ (id<FBResponsePayload>)handleGetBatteryInfo:(FBRouteRequest *)request
{
if (![[UIDevice currentDevice] isBatteryMonitoringEnabled]) {
[[UIDevice currentDevice] setBatteryMonitoringEnabled:YES];
}
return FBResponseWithObject(@{
@"level": @([UIDevice currentDevice].batteryLevel),
@"state": @([UIDevice currentDevice].batteryState)
});
}
#endif
+ (id<FBResponsePayload>)handlePressButtonCommand:(FBRouteRequest *)request
{
NSError *error;
if (![XCUIDevice.sharedDevice fb_pressButton:(id)request.arguments[@"name"]
forDuration:(NSNumber *)request.arguments[@"duration"]
error:&error]) {
return FBResponseWithUnknownError(error);
}
return FBResponseWithOK();
}
+ (id<FBResponsePayload>)handleActivateSiri:(FBRouteRequest *)request
{
NSError *error;
if (![XCUIDevice.sharedDevice fb_activateSiriVoiceRecognitionWithText:(id)request.arguments[@"text"] error:&error]) {
return FBResponseWithUnknownError(error);
}
return FBResponseWithOK();
}
+ (id <FBResponsePayload>)handlePeformIOHIDEvent:(FBRouteRequest *)request
{
NSNumber *page = request.arguments[@"page"];
NSNumber *usage = request.arguments[@"usage"];
NSNumber *duration = request.arguments[@"duration"];
NSError *error;
if (![XCUIDevice.sharedDevice fb_performIOHIDEventWithPage:page.unsignedIntValue
usage:usage.unsignedIntValue
duration:duration.doubleValue
error:&error]) {
return FBResponseWithStatus([FBCommandStatus unknownErrorWithMessage:error.description
traceback:nil]);
}
return FBResponseWithOK();
}
// modified start tag
+ (id <FBResponsePayload>)handleDeviceTap:(FBRouteRequest *)request
{
CGFloat x = [request.arguments[@"x"] doubleValue];
CGFloat y = [request.arguments[@"y"] doubleValue];
CGFloat duration = [request.arguments[@"duration"] doubleValue];
[XCUIDevice.sharedDevice
fb_synthTapWithX:x
y:y duration:duration];
return FBResponseWithOK();
}
+ (id <FBResponsePayload>)handleDeviceSwipe:(FBRouteRequest *)request
{
CGFloat fromX = [request.arguments[@"fromX"] doubleValue];
CGFloat fromY = [request.arguments[@"fromY"] doubleValue];
CGFloat toX = [request.arguments[@"toX"] doubleValue];
CGFloat toY = [request.arguments[@"toY"] doubleValue];
CGFloat delay = [request.arguments[@"delay"] doubleValue];
[XCUIDevice.sharedDevice
fb_synthSwipe:fromX
fromY:fromY toX:toX toY:toY delay:delay];
return FBResponseWithOK();
}
// modified end tag
+ (id <FBResponsePayload>)handleLaunchUnattachedApp:(FBRouteRequest *)request
{
NSString *bundle = (NSString *)request.arguments[@"bundleId"];
if ([FBUnattachedAppLauncher launchAppWithBundleId:bundle]) {
return FBResponseWithOK();
}
return FBResponseWithStatus([FBCommandStatus unknownErrorWithMessage:@"LSApplicationWorkspace failed to launch app" traceback:nil]);
}
+ (id <FBResponsePayload>)handleResetAppAuth:(FBRouteRequest *)request
{
NSNumber *resource = request.arguments[@"resource"];
if (nil == resource) {
NSString *errMsg = @"The 'resource' argument must be set to a valid resource identifier (numeric value). See https://developer.apple.com/documentation/xctest/xcuiprotectedresource?language=objc";
return FBResponseWithStatus([FBCommandStatus invalidArgumentErrorWithMessage:errMsg traceback:nil]);
}
[request.session.activeApplication resetAuthorizationStatusForResource:(XCUIProtectedResource)resource.longLongValue];
return FBResponseWithOK();
}
/**
Returns device location data.
It requires to configure location access permission by manual.
The response of 'latitude', 'longitude' and 'altitude' are always zero (0) without authorization.
'authorizationStatus' indicates current authorization status. '3' is 'Always'.
https://developer.apple.com/documentation/corelocation/clauthorizationstatus
Settings -> Privacy -> Location Service -> WebDriverAgent-Runner -> Always
The return value could be zero even if the permission is set to 'Always'
since the location service needs some time to update the location data.
*/
+ (id<FBResponsePayload>)handleGetLocation:(FBRouteRequest *)request
{
#if TARGET_OS_TV
return FBResponseWithStatus([FBCommandStatus unsupportedOperationErrorWithMessage:@"unsupported"
traceback:nil]);
#else
CLLocationManager *locationManager = [[CLLocationManager alloc] init];
[locationManager setDistanceFilter:kCLHeadingFilterNone];
// Always return the best acurate location data
[locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
[locationManager setPausesLocationUpdatesAutomatically:NO];
[locationManager startUpdatingLocation];
CLAuthorizationStatus authStatus;
if ([locationManager respondsToSelector:@selector(authorizationStatus)]) {
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[[locationManager class]
instanceMethodSignatureForSelector:@selector(authorizationStatus)]];
[invocation setSelector:@selector(authorizationStatus)];
[invocation setTarget:locationManager];
[invocation invoke];
[invocation getReturnValue:&authStatus];
} else {
authStatus = [CLLocationManager authorizationStatus];
}
return FBResponseWithObject(@{
@"authorizationStatus": @(authStatus),
@"latitude": @(locationManager.location.coordinate.latitude),
@"longitude": @(locationManager.location.coordinate.longitude),
@"altitude": @(locationManager.location.altitude),
});
#endif
}
+ (id<FBResponsePayload>)handleExpectNotification:(FBRouteRequest *)request
{
NSString *name = request.arguments[@"name"];
if (nil == name) {
NSString *message = @"Notification name argument must be provided";
return FBResponseWithStatus([FBCommandStatus invalidArgumentErrorWithMessage:message traceback:nil]);
}
NSNumber *timeout = request.arguments[@"timeout"] ?: @60;
NSString *type = request.arguments[@"type"] ?: @"plain";
XCTWaiterResult result;
if ([type isEqualToString:@"plain"]) {
result = [FBNotificationsHelper waitForNotificationWithName:name timeout:timeout.doubleValue];
} else if ([type isEqualToString:@"darwin"]) {
result = [FBNotificationsHelper waitForDarwinNotificationWithName:name timeout:timeout.doubleValue];
} else {
NSString *message = [NSString stringWithFormat:@"Notification type could only be 'plain' or 'darwin'. Got '%@' instead", type];
return FBResponseWithStatus([FBCommandStatus invalidArgumentErrorWithMessage:message traceback:nil]);
}
if (result != XCTWaiterResultCompleted) {
NSString *message = [NSString stringWithFormat:@"Did not receive any expected %@ notifications within %@s",
name, timeout];
return FBResponseWithStatus([FBCommandStatus timeoutErrorWithMessage:message traceback:nil]);
}
return FBResponseWithOK();
}
+ (id<FBResponsePayload>)handleSetDeviceAppearance:(FBRouteRequest *)request
{
NSString *name = [request.arguments[@"name"] lowercaseString];
if (nil == name || !([name isEqualToString:@"light"] || [name isEqualToString:@"dark"])) {
NSString *message = @"The appearance name must be either 'light' or 'dark'";
return FBResponseWithStatus([FBCommandStatus invalidArgumentErrorWithMessage:message traceback:nil]);
}
FBUIInterfaceAppearance appearance = [name isEqualToString:@"light"]
? FBUIInterfaceAppearanceLight
: FBUIInterfaceAppearanceDark;
NSError *error;
if (![XCUIDevice.sharedDevice fb_setAppearance:appearance error:&error]) {
return FBResponseWithStatus([FBCommandStatus unknownErrorWithMessage:error.description
traceback:nil]);
}
return FBResponseWithOK();
}
+ (id<FBResponsePayload>)handleGetDeviceInfo:(FBRouteRequest *)request
{
// Returns locale like ja_EN and zh-Hant_US. The format depends on OS
// Developers should use this locale by default
// https://developer.apple.com/documentation/foundation/nslocale/1414388-autoupdatingcurrentlocale
NSString *currentLocale = [[NSLocale autoupdatingCurrentLocale] localeIdentifier];
NSMutableDictionary *deviceInfo = [NSMutableDictionary dictionaryWithDictionary:
@{
@"currentLocale": currentLocale,
@"timeZone": self.timeZone,
@"name": UIDevice.currentDevice.name,
@"model": UIDevice.currentDevice.model,
@"uuid": [UIDevice.currentDevice.identifierForVendor UUIDString] ?: @"unknown",
// https://developer.apple.com/documentation/uikit/uiuserinterfaceidiom?language=objc
@"userInterfaceIdiom": @(UIDevice.currentDevice.userInterfaceIdiom),
@"userInterfaceStyle": self.userInterfaceStyle,
#if TARGET_OS_SIMULATOR
@"isSimulator": @(YES),
#else
@"isSimulator": @(NO),
#endif
}];
// https://developer.apple.com/documentation/foundation/nsprocessinfothermalstate
deviceInfo[@"thermalState"] = @(NSProcessInfo.processInfo.thermalState);
return FBResponseWithObject(deviceInfo);
}
/**
* @return Current user interface style as a string
*/
+ (NSString *)userInterfaceStyle
{
if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"15.0")) {
// Only iOS 15+ simulators/devices return correct data while
// the api itself works in iOS 13 and 14 that has style preference.
NSNumber *appearance = [XCUIDevice.sharedDevice fb_getAppearance];
if (appearance != nil) {
return [self getAppearanceName:appearance];
}
}
static id userInterfaceStyle = nil;
static dispatch_once_t styleOnceToken;
dispatch_once(&styleOnceToken, ^{
if ([UITraitCollection respondsToSelector:NSSelectorFromString(@"currentTraitCollection")]) {
id currentTraitCollection = [UITraitCollection performSelector:NSSelectorFromString(@"currentTraitCollection")];
if (nil != currentTraitCollection) {
userInterfaceStyle = [currentTraitCollection valueForKey:@"userInterfaceStyle"];
}
}
});
if (nil == userInterfaceStyle) {
return @"unsupported";
}
return [self getAppearanceName:userInterfaceStyle];
}
+ (NSString *)getAppearanceName:(NSNumber *)appearance
{
switch ([appearance longLongValue]) {
case FBUIInterfaceAppearanceUnspecified:
return @"automatic";
case FBUIInterfaceAppearanceLight:
return @"light";
case FBUIInterfaceAppearanceDark:
return @"dark";
default:
return @"unknown";
}
}
/**
* @return The string of TimeZone. Returns TZ timezone id by default. Returns TimeZone name by Apple if TZ timezone id is not available.
*/
+ (NSString *)timeZone
{
NSTimeZone *localTimeZone = [NSTimeZone localTimeZone];
// Apple timezone name like "US/New_York"
NSString *timeZoneAbb = [localTimeZone abbreviation];
if (timeZoneAbb == nil) {
return [localTimeZone name];
}
// Convert timezone name to ids like "America/New_York" as TZ database Time Zones format
// https://developer.apple.com/documentation/foundation/nstimezone
NSString *timeZoneId = [[NSTimeZone timeZoneWithAbbreviation:timeZoneAbb] name];
if (timeZoneId != nil) {
return timeZoneId;
}
return [localTimeZone name];
}
#if !TARGET_OS_TV // tvOS does not provide relevant APIs
+ (id<FBResponsePayload>)handleGetSimulatedLocation:(FBRouteRequest *)request
{
NSError *error;
CLLocation *location = [XCUIDevice.sharedDevice fb_getSimulatedLocation:&error];
if (nil != error) {
return FBResponseWithStatus([FBCommandStatus unknownErrorWithMessage:error.description
traceback:nil]);
}
return FBResponseWithObject(@{
@"latitude": location ? @(location.coordinate.latitude) : NSNull.null,
@"longitude": location ? @(location.coordinate.longitude) : NSNull.null,
@"altitude": location ? @(location.altitude) : NSNull.null,
});
}
+ (id<FBResponsePayload>)handleSetSimulatedLocation:(FBRouteRequest *)request
{
NSNumber *longitude = request.arguments[@"longitude"];
NSNumber *latitude = request.arguments[@"latitude"];
if (nil == longitude || nil == latitude) {
return FBResponseWithStatus([FBCommandStatus invalidArgumentErrorWithMessage:@"Both latitude and longitude must be provided"
traceback:nil]);
}
NSError *error;
CLLocation *location = [[CLLocation alloc] initWithLatitude:latitude.doubleValue
longitude:longitude.doubleValue];
if (![XCUIDevice.sharedDevice fb_setSimulatedLocation:location error:&error]) {
return FBResponseWithStatus([FBCommandStatus unknownErrorWithMessage:error.description
traceback:nil]);
}
return FBResponseWithOK();
}
+ (id<FBResponsePayload>)handleClearSimulatedLocation:(FBRouteRequest *)request
{
NSError *error;
if (![XCUIDevice.sharedDevice fb_clearSimulatedLocation:&error]) {
return FBResponseWithStatus([FBCommandStatus unknownErrorWithMessage:error.description
traceback:nil]);
}
return FBResponseWithOK();
}
#if __clang_major__ >= 15
+ (id<FBResponsePayload>)handleKeyboardInput:(FBRouteRequest *)request
{
FBElementCache *elementCache = request.session.elementCache;
BOOL hasElement = ![request.parameters[@"uuid"] isEqual:@"0"];
XCUIElement *destination = hasElement
? [elementCache elementForUUID:(NSString *)request.parameters[@"uuid"]]
: request.session.activeApplication;
id keys = request.arguments[@"keys"];
if (![destination respondsToSelector:@selector(typeKey:modifierFlags:)]) {
NSString *message = @"typeKey API is only supported since Xcode15 and iPadOS 17";
return FBResponseWithStatus([FBCommandStatus unsupportedOperationErrorWithMessage:message
traceback:nil]);
}
if (![keys isKindOfClass:NSArray.class]) {
NSString *message = @"The 'keys' argument must be an array";
return FBResponseWithStatus([FBCommandStatus invalidArgumentErrorWithMessage:message
traceback:nil]);
}
for (id item in (NSArray *)keys) {
if ([item isKindOfClass:NSString.class]) {
NSString *keyValue = [FBKeyboard keyValueForName:item] ?: item;
[destination typeKey:keyValue modifierFlags:XCUIKeyModifierNone];
} else if ([item isKindOfClass:NSDictionary.class]) {
id key = [(NSDictionary *)item objectForKey:@"key"];
if (![key isKindOfClass:NSString.class]) {
NSString *message = [NSString stringWithFormat:@"All dictionaries of 'keys' array must have the 'key' item of type string. Got '%@' instead in the item %@", key, item];
return FBResponseWithStatus([FBCommandStatus invalidArgumentErrorWithMessage:message
traceback:nil]);
}
id modifiers = [(NSDictionary *)item objectForKey:@"modifierFlags"];
NSUInteger modifierFlags = XCUIKeyModifierNone;
if ([modifiers isKindOfClass:NSNumber.class]) {
modifierFlags = [(NSNumber *)modifiers unsignedIntValue];
}
NSString *keyValue = [FBKeyboard keyValueForName:item] ?: key;
[destination typeKey:keyValue modifierFlags:modifierFlags];
} else {
NSString *message = @"All items of the 'keys' array must be either dictionaries or strings";
return FBResponseWithStatus([FBCommandStatus invalidArgumentErrorWithMessage:message
traceback:nil]);
}
}
return FBResponseWithOK();
}
#endif
#endif
+ (id<FBResponsePayload>)handlePerformAccessibilityAudit:(FBRouteRequest *)request
{
NSError *error;
NSArray *requestedTypes = request.arguments[@"auditTypes"];
NSMutableSet *typesSet = [NSMutableSet set];
if (nil == requestedTypes || 0 == [requestedTypes count]) {
[typesSet addObject:@"XCUIAccessibilityAuditTypeAll"];
} else {
[typesSet addObjectsFromArray:requestedTypes];
}
NSArray *result = [request.session.activeApplication fb_performAccessibilityAuditWithAuditTypesSet:typesSet.copy
error:&error];
if (nil == result) {
return FBResponseWithStatus([FBCommandStatus unknownErrorWithMessage:error.description
traceback:nil]);
}
return FBResponseWithObject(result);
}
@end