-
-
Notifications
You must be signed in to change notification settings - Fork 6k
/
ios.js
1461 lines (1360 loc) · 47.1 KB
/
ios.js
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
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"use strict";
var path = require('path')
, rimraf = require('rimraf')
, ncp = require('ncp').ncp
, fs = require('fs')
, _ = require('underscore')
, logger = require('../../server/logger.js').get('appium')
, sock = '/tmp/instruments_sock'
, glob = require('glob')
, exec = require('child_process').exec
, spawn = require('child_process').spawn
, bplistCreate = require('bplist-creator')
, bplistParse = require('bplist-parser')
, xmlplist = require('plist')
, Device = require('../device.js')
, Instruments = require('./instruments.js')
, helpers = require('../../helpers.js')
, checkPreferencesApp = helpers.checkPreferencesApp
, getiOSSDKVersion = helpers.getiOSSDKVersion
, errors = require('../../server/errors.js')
, deviceCommon = require('../common.js')
, iOSLog = require('./ios-log.js')
, iOSCrashLog = require('./ios-crash-log.js')
, status = require("../../server/status.js")
, iDevice = require('node-idevice')
, async = require('async')
, iOSController = require('./ios-controller.js')
, iOSHybrid = require('./ios-hybrid.js')
, settings = require('./settings.js')
, mkdirp = require('mkdirp')
, getSimRoot = settings.getSimRoot
, fruitstrap = path.resolve(__dirname, '../../../build/fruitstrap/fruitstrap')
, prepareBootstrap = require('./uiauto').prepareBootstrap
, CommandProxy = require('./uiauto').CommandProxy
, UnknownError = errors.UnknownError;
// XML Plist library helper
var xmlPlistFile = function (filename, callback) {
try {
var result = xmlplist.parseFileSync(filename);
return callback(null, result);
} catch (ex) {
return callback(ex);
}
};
var IOS = function () {
this.init();
};
_.extend(IOS.prototype, Device.prototype);
IOS.prototype._deviceInit = Device.prototype.init;
IOS.prototype.init = function () {
this._deviceInit();
this.appExt = ".app";
this.capabilities = {
webStorageEnabled: false
, locationContextEnabled: false
, browserName: 'iOS'
, platform: 'MAC'
, javascriptEnabled: true
, databaseEnabled: false
, takesScreenshot: true
};
this.xcodeFolder = null;
this.xcodeVersion = null;
this.iOSSDKVersion = null;
this.iosSimProcess = null;
this.logs = {};
this.instruments = null;
this.commandProxy = null;
this.initQueue();
this.onInstrumentsDie = function () {};
this.stopping = false;
this.cbForCurrentCmd = null;
this.remote = null;
this.curContext = null;
this.curWebFrames = [];
this.selectingNewPage = false;
this.processingRemoteCmd = false;
this.windowHandleCache = [];
this.webElementIds = [];
this.implicitWaitMs = 0;
this.asyncWaitMs = 0;
this.asyncResponseCb = null;
this.returnedFromExecuteAtom = {};
this.executedAtomsCounter = 0;
this.curCoords = null;
this.curWebCoords = null;
this.onPageChangeCb = null;
this.dontDeleteSimApps = false;
this.supportedStrategies = ["name", "xpath", "id", "-ios uiautomation",
"class name", "accessibility id"];
this.landscapeWebCoordsOffset = 0;
this.localizableStrings = {};
this.keepAppToRetainPrefs = false;
};
IOS.prototype._deviceConfigure = Device.prototype.configure;
IOS.prototype.configure = function (args, caps, cb) {
var msg;
this._deviceConfigure(args, caps);
this.setIOSArgs();
if (this.args.locationServicesAuthorized && !this.args.bundleId) {
msg = "You must set the bundleId cap if using locationServicesEnabled";
logger.error(msg);
return cb(new Error(msg));
}
if (this.args.app) {
return this.configureApp(cb);
}
msg = "No app set; either start appium with --app or use 'app' cap";
logger.error(msg);
cb(new Error(msg));
};
IOS.prototype.setIOSArgs = function () {
this.args.withoutDelay = !this.args.nativeInstrumentsLib;
this.args.reset = !this.args.noReset;
this.args.removeTraceDir = !this.args.keepArtifacts;
this.args.deviceName = this.args.deviceName || this.args.platformName;
this.args.initialOrientation = this.capabilities.deviceOrientation ||
this.args.orientation ||
"PORTRAIT";
this.useRobot = this.args.robotPort > 0;
this.args.robotUrl = this.useRobot ?
"http://" + this.args.robotAddress + ":" + this.args.robotPort + "" :
null;
this.curOrientation = this.args.initialOrientation;
};
IOS.prototype.configureApp = function (cb) {
var _cb = cb;
cb = function (err) {
if (err) {
err = new Error("Bad app: " + this.args.app + ". App paths need to be " +
"absolute, or relative to the appium server install " +
"dir, or a URL to compressed file, or a special app " +
"name. cause: " + err);
}
_cb(err);
}.bind(this);
var app = this.appString();
if (app.toLowerCase() === "iwebview") {
this.capabilities.iwebview = true;
this.args.app = path.resolve(__dirname,
"../../../build/WebViewApp/WebViewApp.app");
Device.prototype.configureApp.call(this, cb);
} else if (app.toLowerCase() === "settings") {
this.configurePreferences(cb);
} else if (this.appIsPackageOrBundle(app)) {
// we have a bundle ID
logger.debug("App is an iOS bundle, will attempt to run as pre-existing");
this.args.bundleId = app;
this.args.app = null;
cb();
} else {
Device.prototype.configureApp.call(this, cb);
}
};
IOS.prototype.configurePreferences = function (cb) {
logger.debug("Configuring settings app");
var prefsVer = null;
if (typeof this.args.platformVersion !== "undefined" &&
this.args.platformVersion) {
prefsVer = this.args.platformVersion;
}
var sdkNext = function (prefsVer) {
logger.debug("Trying to use settings app, version " + prefsVer);
checkPreferencesApp(prefsVer, this.args.tmpDir, function (err, attemptedApp, origApp) {
if (err) {
logger.error("Could not prepare settings app with version '" +
prefsVer + "': " + err);
return cb(err);
}
logger.debug("Using settings app at " + attemptedApp);
this.args.app = attemptedApp;
this.args.origAppPath = origApp;
cb();
}.bind(this));
}.bind(this);
if (prefsVer === null) {
getiOSSDKVersion(function (err, prefsVer) {
if (err) return cb(err);
sdkNext(prefsVer);
});
} else {
sdkNext(prefsVer);
}
};
IOS.prototype.preCleanup = function (cb) {
var removeTracedirs = function (innerCb) {
if (this.args.removeTraceDir) {
logger.debug("Cleaning up any tracedirs");
glob("*.trace", {}, function (err, files) {
if (err) {
logger.error("Could not glob for tracedirs: " + err.message);
innerCb(err);
} else {
if (files.length > 0) {
var filesDone = 0;
var onDelete = function () {
filesDone++;
if (filesDone === files.length) {
innerCb();
}
};
_.each(files, function (file) {
file = path.resolve(process.cwd(), file);
rimraf(file, function (err) {
if (err) {
logger.warn("Problem cleaning up file: " + err.message);
} else {
logger.debug("Cleaned up " + file);
}
onDelete();
});
});
} else {
logger.debug("No tracedirs to clean up");
innerCb();
}
}
});
} else {
innerCb();
}
}.bind(this);
var removeSocket = function (innerCb) {
logger.debug("Removing any remaining instruments sockets");
rimraf(sock, function (err) {
if (err) return innerCb(err);
logger.debug("Cleaned up instruments socket " + sock);
innerCb();
});
}.bind(this);
async.series([removeSocket, removeTracedirs], cb);
};
IOS.prototype.getNumericVersion = function () {
return parseFloat(this.args.platformVersion);
};
IOS.prototype.start = function (cb, onDie) {
if (this.instruments !== null) {
var msg = "Trying to start a session but instruments is still around";
logger.error(msg);
return cb(new Error(msg));
}
if (typeof onDie === "function") {
this.onInstrumentsDie = onDie;
}
async.series([
this.preCleanup.bind(this),
this.setXcodeFolder.bind(this),
this.setXcodeVersion.bind(this),
this.setiOSSDKVersion.bind(this),
this.detectTraceTemplate.bind(this),
this.detectUdid.bind(this),
this.parseLocalizableStrings.bind(this),
this.setLocale.bind(this),
this.createInstruments.bind(this),
this.setPreferences.bind(this),
this.startLogCapture.bind(this),
this.setDeviceAndLaunchSimulator.bind(this),
this.installToRealDevice.bind(this),
this.startInstruments.bind(this),
this.onInstrumentsLaunch.bind(this),
this.configureBootstrap.bind(this),
this.setBundleId.bind(this),
this.setInitialOrientation.bind(this),
this.initAutoWebview.bind(this)
], function (err) {
cb(err);
});
};
IOS.prototype.createInstruments = function (cb) {
logger.debug("Creating instruments");
this.commandProxy = new CommandProxy({ sock: sock });
this.makeInstruments(function (err, instruments) {
if (err) return cb(err);
this.instruments = instruments;
cb();
}.bind(this));
};
IOS.prototype.startInstruments = function (cb) {
cb = _.once(cb);
var treatError = function (err, cb) {
if (!_.isEmpty(this.logs)) {
this.logs.syslog.stopCapture();
this.logs = {};
}
this.postCleanup(function () {
cb(err);
});
}.bind(this);
logger.debug("Starting command proxy.");
this.commandProxy.start(
function (err) { // on first connection
// first let instruments know so that it does not restart itself
this.instruments.launchHandler(err);
// then we call the callback
cb(err);
}.bind(this)
//
, function (err) { // regular cb
if (err) return treatError(err, cb);
logger.debug("Starting instruments");
this.instruments.start(
function (err) {
if (err) return treatError(err, cb);
// we don't call cb here, waiting for first connection or error
}.bind(this)
, function (code, tracedir) {
this.onUnexpectedInstrumentsExit(code, tracedir);
}.bind(this)
);
}.bind(this)
);
};
IOS.prototype.makeInstruments = function (cb) {
// at the moment all the logging in uiauto is at debug level
// TODO: be able to use info in appium-uiauto
prepareBootstrap().then(
function (bootstrapPath) {
var instruments = new Instruments({
app: this.args.app || this.args.bundleId
, udid: this.args.udid
, processArguments: this.args.processArguments
, ignoreStartupExit: this.shouldIgnoreInstrumentsExit()
, bootstrap: bootstrapPath
, template: this.args.automationTraceTemplatePath
, withoutDelay: this.args.withoutDelay
, xcodeVersion: this.xcodeVersion
, webSocket: this.args.webSocket
, launchTimeout: this.args.launchTimeout
, flakeyRetries: this.args.backendRetries
, simulatorSdkAndDevice: this.iOSSDKVersion >= 7.1 ? this.getDeviceString() : null
});
cb(null, instruments);
}.bind(this), function (err) { cb(err); }
);
};
IOS.prototype.shouldIgnoreInstrumentsExit = function () {
return false;
};
IOS.prototype.onInstrumentsLaunch = function (cb) {
logger.debug('Instruments launched. Starting poll loop for new commands.');
this.instruments.setDebug(true);
if (this.args.origAppPath) {
logger.debug("Copying app back to its original place");
return ncp(this.args.app, this.args.origAppPath, cb);
}
cb();
};
IOS.prototype.setBundleId = function (cb) {
if (this.args.bundleId) {
cb();
} else {
this.proxy('au.bundleId()', function (err, bId) {
if (err) return cb(err);
logger.debug('Bundle ID for open app is ' + bId.value);
this.args.bundleId = bId.value;
cb();
}.bind(this));
}
};
IOS.prototype.setInitialOrientation = function (cb) {
if (typeof this.args.initialOrientation === "string" &&
_.contains(["LANDSCAPE", "PORTRAIT"],
this.args.initialOrientation.toUpperCase())
) {
logger.debug("Setting initial orientation to " + this.args.initialOrientation);
var command = ["au.setScreenOrientation('",
this.args.initialOrientation.toUpperCase(), "')"].join('');
this.proxy(command, function (err, res) {
if (err || res.status !== status.codes.Success.code) {
logger.warn("Setting initial orientation did not work!");
} else {
this.curOrientation = this.args.initialOrientation;
}
cb();
}.bind(this));
} else {
cb();
}
};
IOS.prototype.configureBootstrap = function (cb) {
logger.debug("Setting bootstrap config keys/values");
var autoAcceptAlerts = !(!this.args.autoAcceptAlerts || this.args.autoAcceptAlerts === 'false');
var isVerbose = logger.appiumLoglevel === 'debug';
var cmd = '';
cmd += 'target = $.target();\n';
cmd += 'au = $;\n';
cmd += '$.isVerbose = ' + isVerbose + ';\n';
cmd += 'autoAcceptAlerts = ' + autoAcceptAlerts + ';\n';
// Not using uiauto grace period because of bug.
// cmd += '$.target().setTimeout(1);\n';
this.proxy(cmd, function (err) {
cb(err);
});
};
IOS.prototype.onUnexpectedInstrumentsExit = function (code, traceDir) {
logger.debug("Instruments exited unexpectedly");
if (typeof this.cbForCurrentCmd === "function") {
// we were in the middle of waiting for a command when it died
// so let's actually respond with something
var error = new UnknownError("Instruments died while responding to " +
"command, please check appium logs");
this.cbForCurrentCmd(error, null);
if (!code) {
code = 1; // this counts as an error even if instruments doesn't think so
}
}
if (this.commandProxy) this.commandProxy.safeShutdown();
this.shutdown(code, traceDir, this.onInstrumentsDie);
};
IOS.prototype.setXcodeFolder = function (cb) {
logger.debug("Setting Xcode folder");
helpers.getXcodeFolder(function (err, xcodeFolder) {
if (err) {
logger.error("Could not determine Xcode folder");
}
this.xcodeFolder = xcodeFolder;
cb();
}.bind(this));
};
IOS.prototype.setXcodeVersion = function (cb) {
logger.debug("Setting Xcode version");
helpers.getXcodeVersion(function (err, versionNumber) {
if (err) {
logger.error("Could not determine Xcode version");
}
this.xcodeVersion = versionNumber;
if (this.xcodeVersion === "5.0.1") {
cb(new Error("Xcode 5.0.1 ships with a broken version of Instruments. " +
"please upgrade to 5.0.2"));
} else {
cb();
}
}.bind(this));
};
IOS.prototype.setiOSSDKVersion = function (cb) {
logger.debug("Setting iOS SDK Version");
helpers.getiOSSDKVersion(function (err, versionNumber) {
if (err) {
logger.error("Could not determine iOS SDK version");
}
this.iOSSDKVersion = versionNumber;
logger.debug("iOS SDK Version set to " + this.iOSSDKVersion);
cb();
}.bind(this));
};
IOS.prototype.setLocale = function (cb) {
var msg;
var setLoc = function (err) {
if (err) return cb(err);
var iosSimLocalePath = path.resolve(__dirname, "../../../build/ios-sim-locale");
if (this.args.fullReset) {
msg = "Cannot set locale information because a full-reset was requested";
logger.error(msg);
return cb(new Error(msg));
}
if (fs.existsSync(iosSimLocalePath)) {
helpers.getiOSSimulatorDirectories(function (err, pathList) {
if (err || typeof pathList === 'undefined' || pathList.length < 1) {
msg = "Cannot set locale information because the iOS Simulator directory could not be determined.";
logger.error(msg);
cb(new Error(msg));
} else {
var localeInfoWasSet = false;
var setLanguageForPath = function (pathIndex) {
if (pathIndex >= pathList.length) {
if (localeInfoWasSet) {
logger.debug("Locale was set");
cb();
} else {
msg = "Appium was unable to set locale info.";
logger.error(msg);
cb(new Error(msg));
}
} else {
var sdkVersion = pathList[pathIndex].split(path.sep).pop();
var cmd = iosSimLocalePath + ' -sdk ' + sdkVersion;
cmd = (this.args.language) ? cmd + ' -language ' + this.args.language : cmd;
cmd = (this.args.locale) ? cmd + ' -locale ' + this.args.locale : cmd;
cmd = (this.args.calendarFormat) ? cmd + ' -calendar ' + this.args.calendarFormat : cmd;
logger.debug("Setting locale with command " + cmd);
exec(cmd, { maxBuffer: 524288 }, function (err) {
if (err === null) {
localeInfoWasSet = true;
}
setLanguageForPath(pathIndex + 1);
});
}
}.bind(this);
setLanguageForPath(0);
}
}.bind(this));
} else {
msg = "Could not set locale information because the ios-sim-locale was not found at " + iosSimLocalePath;
logger.error(msg);
cb(new Error(msg));
}
}.bind(this);
if ((this.args.language || this.args.locale || this.args.calendarFormat) && this.args.udid === null) {
if (!settings.simDirsExist(this.iOSSDKVersion)) {
this.instantLaunchAndQuit(false, setLoc);
} else {
setLoc();
}
} else if (this.args.udid) {
logger.debug("Not setting locale because we're using a real device");
cb();
} else {
logger.debug("Not setting locale");
cb();
}
};
IOS.prototype.setPreferences = function (cb) {
if (this.args.udid !== null) {
logger.debug("Not setting iOS and app preferences since we're on a real " +
"device");
return cb();
}
var settingsCaps = [
'locationServicesEnabled',
'locationServicesAuthorized',
'safariAllowPopups',
'safariIgnoreFraudWarning',
'safariOpenLinksInBackground'
];
var safariSettingsCaps = settingsCaps.slice(2, 5);
var needToSet = false;
var needToSetSafari = false;
_.each(settingsCaps, function (cap) {
if (_.has(this.capabilities, cap)) {
needToSet = true;
if (_.contains(safariSettingsCaps, cap)) {
needToSetSafari = true;
this.keepAppToRetainPrefs = true;
}
}
}.bind(this));
if (!needToSet) {
logger.debug("No iOS / app preferences to set");
return cb();
} else if (this.args.fullReset) {
var msg = "Cannot set preferences because a full-reset was requested";
logger.debug(msg);
logger.error(msg);
return cb(new Error(msg));
}
var setPrefs = function (err) {
if (err) return cb(err);
try {
this.setLocServicesPrefs();
} catch (e) {
logger.error("Error setting location services preferences, prefs will not work");
logger.error(e);
logger.error(e.stack);
}
try {
this.setSafariPrefs();
} catch (e) {
logger.error("Error setting safari preferences, prefs will not work");
logger.error(e);
logger.error(e.stack);
}
cb();
}.bind(this);
logger.debug("Setting iOS and app preferences");
if (!settings.simDirsExist(this.iOSSDKVersion) ||
!settings.locServicesDirsExist(this.iOSSDKVersion) ||
(needToSetSafari && !settings.safari7DirsExist(this.iOSSDKVersion))) {
this.instantLaunchAndQuit(needToSetSafari, setPrefs);
} else {
setPrefs();
}
};
IOS.prototype.instantLaunchAndQuit = function (needSafariDirs, cb) {
logger.debug("Sim files for the " + this.iOSSDKVersion + " SDK do not yet exist, launching the sim " +
"to populate the applications and preference dirs");
var condition = function () {
var simDirsExist = settings.simDirsExist(this.iOSSDKVersion);
var locServicesDirsExist= settings.locServicesDirsExist(this.iOSSDKVersion);
var safariDirsExist = this.iOSSDKVersion < 7.0 ||
settings.safari7DirsExist(this.iOSSDKVersion);
var okToGo = simDirsExist && locServicesDirsExist &&
(!needSafariDirs || safariDirsExist);
if (!okToGo) {
logger.debug("We launched the simulator but the required dirs don't " +
"yet exist. Waiting some more...");
}
return okToGo;
}.bind(this);
this.setDeviceAndLaunchSimulator(function (err) {
if (err) return cb(err);
this.makeInstruments(function (err, instruments) {
instruments.launchAndKill(condition, function (err) {
if (err) return cb(err);
this.endSimulator(cb);
}.bind(this));
}.bind(this));
}.bind(this));
};
IOS.prototype.setLocServicesPrefs = function () {
if (typeof this.capabilities.locationServicesEnabled !== "undefined" ||
this.capabilities.locationServicesAuthorized) {
var locServ = this.capabilities.locationServicesEnabled;
locServ = locServ || this.capabilities.locationServicesAuthorized;
locServ = locServ ? 1 : 0;
logger.debug("Setting location services to " + locServ);
settings.updateSettings(this.iOSSDKVersion, 'locationServices', {
LocationServicesEnabled: locServ,
'LocationServicesEnabledIn7.0': locServ
});
}
if (typeof this.capabilities.locationServicesAuthorized !== "undefined") {
if (!this.args.bundleId) {
var msg = "Can't set location services for app without bundle ID";
logger.error(msg);
throw new Error(msg);
}
var locAuth = !!this.capabilities.locationServicesAuthorized;
if (locAuth) {
logger.debug("Authorizing location services for app");
} else {
logger.debug("De-authorizing location services for app");
}
settings.updateLocationSettings(this.iOSSDKVersion, this.args.bundleId, locAuth);
this.keepAppToRetainPrefs = true;
}
};
IOS.prototype.setSafariPrefs = function () {
var safariSettings = {};
var val;
if (_.has(this.capabilities, 'safariAllowPopups')) {
val = !!this.capabilities.safariAllowPopups;
logger.debug("Setting javascript window opening to " + val);
safariSettings.WebKitJavaScriptCanOpenWindowsAutomatically = val;
}
if (_.has(this.capabilities, 'safariIgnoreFraudWarning')) {
val = !this.capabilities.safariIgnoreFraudWarning;
logger.debug("Setting fraudulent website warning to " + val);
safariSettings.WarnAboutFraudulentWebsites = val;
}
if (_.has(this.capabilities, 'safariOpenLinksInBackground')) {
val = this.capabilities.safariOpenLinksInBackground ? 1 : 0;
logger.debug("Setting opening links in background to " + !!val);
safariSettings.OpenLinksInBackground = val;
}
if (_.size(safariSettings) > 0) {
settings.updateSafariSettings(this.iOSSDKVersion, safariSettings);
this.dontDeleteSimApps = true;
}
};
IOS.prototype.detectTraceTemplate = function (cb) {
logger.debug("Detecting automation tracetemplate");
var msg;
if (!this.args.automationTraceTemplatePath) {
helpers.getXcodeFolder(function (err, xcodeFolderPath) {
if (err) return cb(err);
if (xcodeFolderPath !== null) {
var xcodeTraceTemplatePath = path.resolve(xcodeFolderPath,
"../Applications/Instruments.app/Contents/PlugIns",
"AutomationInstrument.bundle/Contents/Resources",
"Automation.tracetemplate");
if (fs.existsSync(xcodeTraceTemplatePath)) {
this.args.automationTraceTemplatePath = xcodeTraceTemplatePath;
cb();
} else {
msg = "Could not find Automation.tracetemplate in " +
xcodeTraceTemplatePath;
logger.error(msg);
cb(new Error(msg));
}
} else {
msg = "Could not find Automation.tracetemplate because XCode " +
"could not be found. Try setting the path with xcode-select.";
logger.error(msg);
cb(new Error(msg));
}
}.bind(this));
} else {
cb();
}
};
IOS.prototype.detectUdid = function (cb) {
if (this.args.udid !== null && this.args.udid === "auto") {
logger.debug("Auto-detecting iOS udid...");
var udidetectPath = path.resolve(__dirname, "../../../build/udidetect/udidetect");
var udiddetectProc = exec(udidetectPath, { maxBuffer: 524288, timeout: 3000 }, function (err, stdout) {
if (stdout && stdout.length > 2) {
this.args.udid = stdout.replace("\n", "");
logger.debug("Detected udid as " + this.args.udid);
cb();
} else {
logger.error("Could not detect udid.");
cb(new Error("Could not detect udid."));
}
}.bind(this));
udiddetectProc.on('timeout', function () {
logger.error("Timed out trying to detect udid.");
cb(new Error("Timed out trying to detect udid."));
});
} else {
logger.debug("Not auto-detecting udid, running on sim");
cb();
}
};
IOS.prototype.installToRealDevice = function (cb) {
// if user has passed in desiredCaps.autoLaunch = false
// meaning they will manage app install / launching
if (this.args.autoLaunch === false) {
cb();
} else {
if (this.args.udid) {
if (this.args.ipa && this.args.bundleId) {
this.installIpa(cb);
} else if (this.args.ipa) {
var msg = "You specified a UDID and ipa but did not include the bundle " +
"id";
logger.error(msg);
cb(new Error(msg));
} else if (this.args.app) {
try {
this.realDevice = this.getIDeviceObj();
} catch (e) {
return cb(e);
}
this.installApp(this.args.app, cb);
} else {
logger.debug("Real device specified but no ipa or app path, assuming bundle ID is " +
"on device");
cb();
}
} else {
logger.debug("No device id or app, not installing to real device.");
cb();
}
}
};
IOS.prototype.getIDeviceObj = function () {
var idiPath = path.resolve(__dirname, "../../../build/",
"libimobiledevice-macosx/ideviceinstaller");
logger.debug("Creating iDevice object with udid " + this.args.udid);
try {
return iDevice(this.args.udid);
} catch (e1) {
logger.debug("Couldn't find ideviceinstaller, trying built-in at " +
idiPath);
try {
return iDevice(this.args.udid, {cmd: idiPath});
} catch (e2) {
var msg = "Could not initialize ideviceinstaller; make sure it is " +
"installed and works on your system";
logger.error(msg);
throw new Error(msg);
}
}
};
IOS.prototype.installIpa = function (cb) {
logger.debug("Installing ipa found at " + this.args.ipa);
this.realDevice = this.getIDeviceObj();
var d = this.realDevice;
async.waterfall([
function (cb) { d.isInstalled(this.args.bundleId, cb); }.bind(this),
function (installed, cb) {
if (installed) {
logger.debug("Bundle found on device, removing before reinstalling.");
d.remove(this.args.bundleId, cb);
} else {
logger.debug("Nothing found on device, going ahead and installing.");
cb();
}
}.bind(this),
function (cb) { d.installAndWait(this.args.ipa, this.args.bundleId, cb); }.bind(this)
], cb);
};
IOS.prototype.getDeviceString = function () {
var isiPhone = this.args.forceIphone || this.args.forceIpad === null || (this.args.forceIpad !== null && !this.args.forceIpad);
var isTall = isiPhone;
var isRetina = this.xcodeVersion[0] !== '4';
var is64bit = false;
if (this.args.deviceName) {
var device = this.args.deviceName.toLowerCase();
if (device.indexOf("iphone") !== -1) {
isiPhone = true;
} else if (device.indexOf("ipad") !== -1) {
isiPhone = false;
}
if (this.args.deviceName !== this.args.platformName) {
isTall = isiPhone && (device.indexOf("4-inch") !== -1);
isRetina = (device.indexOf("retina") !== -1);
is64bit = (device.indexOf("64-bit") !== -1);
}
}
var iosDeviceString = isiPhone ? "iPhone" : "iPad";
if (this.xcodeVersion[0] === '4') {
if (isiPhone && isRetina) {
iosDeviceString += isTall ? " (Retina 4-inch)" : " (Retina 3.5-inch)";
} else {
iosDeviceString += isRetina ? " (Retina)" : "";
}
} else {
iosDeviceString += isRetina ? " Retina" : "";
if (isiPhone) {
if (isRetina && isTall) {
iosDeviceString += is64bit ? " (4-inch 64-bit)" : " (4-inch)";
} else if (this.args.deviceName.toLowerCase().indexOf("3.5") !== -1) {
iosDeviceString += " (3.5-inch)";
}
} else {
iosDeviceString += is64bit ? " (64-bit)" : "";
}
}
if (this.iOSSDKVersion >= 7.1) {
iosDeviceString += " - Simulator - iOS " +
(this.args.platformVersion || this.iOSSDKVersion);
}
return iosDeviceString;
};
IOS.prototype.setDeviceTypeInInfoPlist = function (deviceTypeCode, cb) {
var plist = path.resolve(this.args.app, "Info.plist");
bplistParse.parseFile(plist, function (err, obj) {
var newPlist;
if (err) {
xmlPlistFile(plist, function (err, obj) {
if (err) {
logger.error("Could not parse plist file at " + plist);
cb(err);
return;
} else {
logger.debug("Parsed app Info.plist");
obj.UIDeviceFamily = [deviceTypeCode];
newPlist = xmlplist.build(obj);
}
});
} else {
logger.debug("Parsed app Info.plist");
obj[0].UIDeviceFamily = [deviceTypeCode];
newPlist = bplistCreate(obj);
}
fs.writeFile(plist, newPlist, function (err) {
if (err) {
logger.error("Could not save new Info.plist");
cb(err);
} else {
logger.debug("Wrote new app Info.plist with device type");
cb();
}
});
});
};
IOS.prototype.checkDeviceAvailable = function (cb) {
if (this.iOSSDKVersion >= 7.1) {
logger.debug("Checking whether instruments supports our device string");
this.instruments.getAvailableDevices(function (err, availDevices) {
var dString = this.getDeviceString();
if (err) return cb(err);
if (!_.contains(availDevices, dString)) {
var msg = "Could not find a device to launch. You requested '" +
dString + "', but the available devices were: " +
JSON.stringify(availDevices);
logger.error(msg);
return cb(new Error(msg));
}
cb();
}.bind(this));
} else {
logger.debug("Instruments v < 7.1, not checking device string support");
cb();
}
};
IOS.prototype.setDeviceAndLaunchSimulator = function (cb) {
var msg;
if (this.args.udid) {
logger.debug("Not setting device type since we're connected to a device");
cb();
} else if (!this.args.app && this.args.bundleId) {
logger.debug("Not setting device type since we're using bundle ID and " +
"assuming app is already installed");
cb(null);
} else if (!this.args.deviceName && this.args.forceIphone === null && this.args.forceIpad === null) {
logger.debug("No device specified, current device in the iOS simulator will be used.");
cb(null);
} else if (this.args.defaultDevice) {
logger.debug("User specified default device, letting instruments launch it");
this.checkDeviceAvailable(function (err) {
if (err) return cb(err);
var iosDeviceString = this.getDeviceString();
var isiPhone = iosDeviceString.toLowerCase().indexOf("ipad") === -1;
this.setDeviceTypeInInfoPlist(isiPhone ? 1 : 2, cb);
}.bind(this));
} else {
var iosSimPath = path.resolve(this.xcodeFolder, "Platforms/iPhoneSimulator.platform/Developer/Applications" +
"/iPhone Simulator.app/Contents/MacOS/iPhone Simulator");
if (!fs.existsSync(iosSimPath)) {
msg = "Could not find ios simulator binary at " + iosSimPath;
logger.error(msg);
cb(new Error(msg));
} else {
var cleanup = function (cb) {
if ((this.args.fullReset || this.args.reset) && this.dontDeleteSimApps) {
logger.debug("Not deleting simulator apps since we need to update " +
"their plists before launch");
return cb();
}
if (this.args.fullReset) {
this.deleteSim(cb);
} else if (this.args.reset) {
this.cleanupAppState(cb);
} else {
cb();
}
}.bind(this);
var setDeviceInfo = function (cb) {
var isiPhone = this.getDeviceString().toLowerCase().indexOf("ipad") === -1;
this.setDeviceTypeInInfoPlist(isiPhone ? 1 : 2, cb);
}.bind(this);
var startSim = function (cb) {
logger.debug("Launching device: " + this.getDeviceString());
var iosSimArgs = ["-SimulateDevice", this.getDeviceString()];
this.iosSimProcess = spawn(iosSimPath, iosSimArgs);
var waitForSimulatorLogs = function (countdown) {
if (countdown <= 0 || (this.logs.syslog && (this.logs.syslog.getAllLogs().length > 0 ||
(this.logs.crashlog && this.logs.crashlog.getAllLogs().length > 0)))) {
logger.debug(countdown > 0 ? "Simulator is now ready." : "Waited 10 seconds for simulator to start.");
cb();
} else {
setTimeout(function () {
waitForSimulatorLogs(countdown - 1);
}, 1000);
}
}.bind(this);
waitForSimulatorLogs(10);
}.bind(this);
if (this.iOSSDKVersion < 7.1) {
async.series([
this.endSimulator.bind(this),
cleanup,
setDeviceInfo,
startSim
], function (err) {