forked from paypal/Illuminator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathExtensions.js
1779 lines (1545 loc) · 64.5 KB
/
Extensions.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
// Extensions.js - Extensions to Apple's UIAutomation library
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Exceptions
//
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Decode a stack trace into something readable
*
* UIAutomation has a decent `.backtrace` property for errors, but ONLY for the `Error` class.
* As of this writing, many attempts to produce that property on user-defined error classes have failed.
* This function decodes the somewhat-readable `.stack` property into something better
*
* Decode the following known types of stack lines:
* - built-in functions in this form: funcName@[native code]
* - anonymous functions in this form: file://<path>/file.js:line:col
* - named functions in this form: funcName@file://<path>/file.js:line:col
* - top-level calls in this form: global code@file://<path>/file.js:line:col
*
* @param trace string returned by the "stack" property of a caught exception
* @return object
* { isOK: boolean, whether any errors at all were encountered
* message: string describing any error encountered
* errorName: string name of the error
* stack: array of trace objects [
* { functionName: string name of function, or undefined if the function was anonymous
* nativeCode: boolean whether the function was defined in UIAutomation binary code
* file: if not native code, the basename of the file containing the function
* line: if not native code, the line where the function is defined
* column: if not native code, the column where the function is defined
* }
* ]
* }
*
*/
function decodeStackTrace(err) {
if ("string" == (typeof err)) {
return {isOK: false, message: "[caught string error, not an error class]", stack: []};
}
if (err.stack === undefined) {
return {isOK: false, message: "[caught an error without a stack]", stack: []};
}
var ret = {isOK: true, stack: []};
if (err.name !== undefined) {
ret.errorName = err.name;
ret.message = "<why are you reading this? there is nothing wrong.>";
} else {
ret.errorName = "<unnamed>";
ret.message = "[Error class was unnamed]";
}
var lines = err.stack.split("\n");
for (var i = 0; i < lines.length; ++i) {
var l = lines[i];
var r = {};
var location;
// extract @ symbol if it exists, which defines whether function is anonymous
var atPos = l.indexOf("@");
if (-1 == atPos) {
location = l;
} else {
r.functionName = l.substring(0, atPos);
location = l.substring(atPos + 1);
}
// check whether the function is built in to UIAutomation
r.nativeCode = ("[native code]" == location);
// extract file, line, and column if not native code
if (!r.nativeCode) {
var tail = location.substring(location.lastIndexOf("/") + 1);
var items = tail.split(":");
r.file = items[0];
r.line = items[1];
r.column = items[2];
}
//string.substring(string.indexOf("_") + 1)
ret.stack.push(r);
}
return ret;
}
/**
* Get a stack trace (this function omitted) from any location in code
*
* @return just the stack property of decodeStackTrace
*/
function getStackTrace() {
try {
throw new Error("base");
} catch (e) {
return decodeStackTrace(e).stack.slice(1);
}
}
/**
* Shortcut to defining simple error classes
*
* @param className string name for the new error class
* @return a function that is used to construct new error instances
*/
function makeErrorClass(className) {
return function (message) {
this.name = className;
this.message = message;
this.toString = function() { return this.name + ": " + this.message; };
};
}
/**
* Shortcut to defining error classes that indicate the function/file/line that triggered them
*
* These are for cases where the errors are expected to be caught by the global error handler
*
* @param fileName string basename of the file where the function is defined (gets stripped out)
* @param className string name for the new error class
* @return a function that is used to construct new error instances
*/
function makeErrorClassWithGlobalLocator(fileName, className) {
var _getCallingFunction = function () {
var stack = getStackTrace();
// start from 2nd position on stack, after _getCallingFunction and makeErrorClassWithGlobalLocator
for (var i = 2; i < stack.length; ++i) {
var l = stack[i];
if (!(l.nativeCode || fileName == l.file)) {
return "In " + l.functionName + " at " + l.file + " line " + l.line + " col " + l.column + ": ";
}
}
return "";
};
return function (message) {
this.name = className;
this.message = _getCallingFunction() + message;
this.toString = function() { return this.name + ": " + this.message; };
};
}
IlluminatorSetupException = makeErrorClass("IlluminatorSetupException");
IlluminatorRuntimeFailureException = makeErrorClass("IlluminatorRuntimeFailureException");
IlluminatorRuntimeVerificationException = makeErrorClass("IlluminatorRuntimeVerificationException");
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// General-purpose functions
//
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* shortcut function to get UIATarget.localTarget(), sets _accessor
*/
function target() {
var ret = UIATarget.localTarget();
ret._accessor = "target()";
return ret;
}
/**
* shortcut function to get UIATarget.localTarget().frontMostApp().mainWindow(), sets _accessor
*/
function mainWindow() {
var ret = UIATarget.localTarget().frontMostApp().mainWindow();
ret._accessor = "mainWindow()";
return ret;
}
/**
* delay for a number of seconds
*
* @param seconds float how long to wait
*/
function delay(seconds) {
target().delay(seconds);
}
/**
* get the current time: seconds since epoch, with decimal for millis
*/
function getTime() {
return (new Date).getTime() / 1000;
}
/**
* EXTENSION PROFILER
*/
(function() {
var root = this,
extensionProfiler = null;
// put extensionProfiler in namespace of importing code
if (typeof exports !== 'undefined') {
extensionProfiler = exports;
} else {
extensionProfiler = root.extensionProfiler = {};
}
/**
* reset the stored criteria costs
*/
extensionProfiler.resetCriteriaCost = function () {
extensionProfiler._criteriaCost = {};
extensionProfiler._criteriaTotalCost = {}
extensionProfiler._criteriaTotalHits = {};
extensionProfiler._bufferCriteria = false;
};
extensionProfiler.resetCriteriaCost(); // initialize it
/**
* sometimes critera are evaluated in a loop because we are waiting for something; don't count that
*
* indicates that we should store ONLY THE MOST RECENT lookup times in an array
*/
extensionProfiler.bufferCriteriaCost = function() {
extensionProfiler._bufferCriteria = true;
};
/**
* sometimes critera are evaluated in a loop because we are waiting for something; don't count that
*
* indicates that we should store ONLY THE MOST RECENT lookup times in an array
*/
extensionProfiler.UnbufferCriteriaCost = function() {
extensionProfiler._bufferCriteria = false;
// replay the most recent values into the totals
for (var c in extensionProfiler._criteriaCost) {
extensionProfiler.recordCriteriaCost(c, extensionProfiler._criteriaCost[c]);
}
extensionProfiler._criteriaCost = {};
};
/**
* keep track of the cumulative time spent looking for criteria
*
* @param criteria the criteria object or object array
* @param time the time spent looking up that criteria
*/
extensionProfiler.recordCriteriaCost = function (criteria, time) {
// criteria can be a string if it comes from our buffered array, so allow it.
var key = (typeof criteria) == "string" ? criteria : JSON.stringify(criteria);
if (extensionProfiler._bufferCriteria) {
extensionProfiler._criteriaCost[key] = time; // only store the most recent one, we'll merge later
} else {
if (undefined === extensionProfiler._criteriaTotalCost[key]) {
extensionProfiler._criteriaTotalCost[key] = 0;
extensionProfiler._criteriaTotalHits[key] = 0;
}
extensionProfiler._criteriaTotalCost[key] += time;
extensionProfiler._criteriaTotalHits[key]++;
}
};
/**
* return an array of objects indicating the cumulative time spent looking for criteria -- high time to low
*
* @return array of {criteria: x, time: y, hits: z} objects
*/
extensionProfiler.getCriteriaCost = function () {
var ret = [];
for (var criteria in extensionProfiler._criteriaTotalCost) {
ret.push({"criteria": criteria,
"time": extensionProfiler._criteriaTotalCost[criteria],
"hits": extensionProfiler._criteriaTotalHits[criteria]});
}
ret.sort(function(a, b) { return b.time - a.time; });
return ret;
};
}).call(this);
/**
* convert a number of seconds to hh:mm:ss.ss
*
* @param seconds the number of seconds (decimal OK)
*/
function secondsToHMS(seconds) {
var s = Math.floor(seconds);
var f = seconds - s;
var h = Math.floor(s / 3600);
s -= h * 3600;
var m = Math.floor(s / 60);
s -= m * 60;
// build strings
h = h > 0 ? (h + ":") : "";
m = (m > 9 ? m.toString() : ("0" + m.toString())) + ":";
s = s > 9 ? s.toString() : ("0" + s.toString());
f = f > 0 ? ("." + Math.round(f * 100).toString()) : "";
return h + m + s + f;
}
/**
* Extend an object prototype with an associative array of properties
*
* @param baseClass a javascript class
* @param properties an associative array of properties to add to the prototype of baseClass
*/
function extendPrototype(baseClass, properties) {
for (var p in properties) {
baseClass.prototype[p] = properties[p];
}
}
/**
* Return true if the element is usable -- not some form of nil
*
* @param elem the element to check
*/
function isNotNilElement(elem) {
if (elem === undefined) return false;
if (elem === null) return false;
if (elem.isNotNil) return elem.isNotNil();
return elem.toString() != "[object UIAElementNil]";
}
/**
* Return true if a selector is "hard" -- referring to one and only one element by nature
*/
function isHardSelector(selector) {
switch (typeof selector) {
case "function": return true;
case "string": return true;
default: return false;
}
}
/**
* "constructor" for UIAElementNil
*
* UIAutomation doesn't give us access to the UIAElementNil constructor, so do it our own way
*/
function newUIAElementNil() {
try {
UIATarget.localTarget().pushTimeout(0);
return UIATarget.localTarget().frontMostApp().windows().firstWithPredicate("name == 'Illuminator' and name == 'newUIAELementNil()'");
} catch(e) {
throw e;
} finally {
UIATarget.localTarget().popTimeout();
}
}
/**
* Wait for a function to return a value (i.e. not throw an exception)
*
* Execute a function repeatedly. If it returns a value, return that value.
* If the timeout is reached, re-raise the exception that the function raised.
* Guaranteed to execute once and only once after timeout has passed, ensuring
* that the function is given its full allotted time (2 runs minimum if only exceptions are thrown)
*
* @param callerName string name of calling function for logging/erroring purposes
* @param timeout the timeout in seconds
* @param functionReturningValue the function to execute. can return anything.
*/
function waitForReturnValue(timeout, callerName, functionReturningValue) {
var myGetTime = function () {
return (new Date).getTime() / 1000;
}
switch (typeof timeout) {
case "number": break;
default: throw new IlluminatorSetupException("waitForReturnValue got a bad timeout type: (" + (typeof timeout) + ") " + timeout);
}
var stopTime = myGetTime() + timeout;
var caught = null;
for (var now = myGetTime(), runsAfterTimeout = 0; now < stopTime || runsAfterTimeout < 1; now = myGetTime()) {
if (now >= stopTime) {
++runsAfterTimeout;
}
try {
return functionReturningValue();
} catch (e) {
caught = e;
}
delay(0.1); // max 10 Hz
}
throw new IlluminatorRuntimeFailureException(callerName + " failed by timeout after " + timeout + " seconds: " + caught);
}
/**
* return unique elements (based on UIAElement.equals()) from a {key: element} object
*
* @param elemObject an object containing UIAElements keyed on strings
*/
function getUniqueElements(elemObject) {
var ret = {};
for (var i in elemObject) {
var elem = elemObject[i];
var found = false;
// add elements to return object if they are not already there (via equality)
for (var j in ret) {
if (ret[j].equals(elem)) {
found = true;
break;
}
}
if (!found) {
ret[i] = elem;
}
}
return ret;
}
/**
* Get one element from a selector result
*/
function getOneCriteriaSearchResult(callerName, elemObject, originalCriteria, allowZero) {
// assert that there is only one element
var uniq = getUniqueElements(elemObject);
var size = Object.keys(elemObject).length;
if (size > 1 || size == 0 && !allowZero) {
var msg = callerName + ": expected 1 element";
if (originalCriteria !== undefined) {
msg += " from selector " + JSON.stringify(originalCriteria);
}
msg += ", received " + size.toString();
if (size > 0) {
msg += " {";
for (var k in elemObject) {
msg += "\n " + k + ": " + elemObject[k].toString();
}
msg += "\n}";
}
throw new IlluminatorRuntimeFailureException(msg);
}
// they're all the same, so return just one
for (var k in elemObject) {
UIALogger.logDebug("Selector found object with canonical name: " + k);
return elemObject[k];
}
return newUIAElementNil();
}
/**
* Resolve an expression to a set of UIAElements
*
* Criteria can be one of the following:
* 1. An object of critera to satisfy UIAElement..find() .
* 2. An array of objects containing UIAElement.find() criteria; elem = UIAElement.find(arr[0])[0..n].find(arr[1])...
*
* @param criteria as described above
* @param parentElem a UIAElement from which the search for elements will begin
* @param elemAccessor string representation of the accessor required to get the parentElem
*/
function getElementsFromCriteria(criteria, parentElem, elemAccessor) {
if (parentElem === undefined) {
parentElem = target();
elemAccessor = parentElem._accessor;
}
if (elemAccessor === undefined) {
elemAccessor = "<root elem>";
}
// search in the appropriate way
if (!(criteria instanceof Array)) {
criteria = [criteria];
}
// perform a find in several stages
var segmentedFind = function (criteriaArray, initialElem, initialAccessor) {
var intermElems = {};
intermElems[initialAccessor] = initialElem; // intermediate elements
// go through all criteria
for (var i = 0; i < criteriaArray.length; ++i) {
var tmp = {};
// expand search on each intermediate element using current criteria
for (var k in intermElems) {
var newFrontier = intermElems[k].find(criteriaArray[i], k);
// merge results with temporary storage
for (var f in newFrontier) {
tmp[f] = newFrontier[f];
}
}
// move unique elements from temporary storage into loop variable
intermElems = getUniqueElements(tmp);
}
return intermElems;
}
var startTime = getTime();
try {
return segmentedFind(criteria, parentElem, elemAccessor);
} catch (e) {
throw e;
} finally {
var cost = getTime() - startTime;
extensionProfiler.recordCriteriaCost(criteria, cost);
}
}
/**
* Resolve a string expression to a UIAElement using Eval
*
* @param selector string
* @param element the element to use as a starting point
*/
function getChildElementFromEval(selector, element) {
// wrapper function for lookups, only return element if element is visible
var visible = function (elem) {
return elem.isVisible() ? elem : newUIAElementNil();
}
try {
return eval(selector);
} catch (e) {
if (e instanceof SyntaxError) {
throw new IlluminatorSetupException("Couldn't evaluate string selector '" + selector + "': " + e);
} else if (e instanceof TypeError) {
throw new IlluminatorSetupException("Evaluating string selector on element " + element + " triggered " + e);
} else {
throw e;
}
}
}
/**
* construct an input method
*/
function newInputMethod(methodName, description, isActiveFn, selector, features) {
var ret = {
name: methodName,
description: description,
isActiveFn: isActiveFn,
selector: selector,
features: {}
};
for (var k in features) {
ret.features[k] = features[k];
}
return ret;
}
var stockKeyboardInputMethod = newInputMethod("defaultKeyboard",
"Any default iOS keyboard, whether numeric or alphanumeric",
function () {
return isNotNilElement(target().frontMostApp().keyboard());
},
function (targ) {
return targ.frontMostApp().keyboard();
},
{});
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Object prototype functions
//
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* set the (custom) input method for an element
*
* @param method the input method
*/
function setInputMethod(method) {
this._inputMethod = method;
}
/**
* Access the custom input method for an element
*/
function customInputMethod() {
if (this._inputMethod === undefined) throw new IlluminatorSetupException("No custom input method defined for element " + this);
var inpMth = this._inputMethod;
// open custom input method
this.checkIsEditable(2);
// assign any feature functions to it
var theInput = target().getOneChildElement(inpMth.selector);
for (var f in inpMth.features) {
theInput[f] = inpMth.features[f];
}
return theInput;
}
/**
* type a string in a given text field
*
* @param text the string to type
* @param clear boolean value of whether to clear the text field first
*/
var typeString = function (text, clear) {
text = text.toString(); // force string argument to actual string
// make sure we can type (side effect: brings up keyboard)
if (!this.checkIsEditable(2)) {
throw new IlluminatorRuntimeFailureException("typeString couldn't get the keyboard to appear for element "
+ this.toString() + " with name '" + this.name() + "'");
}
var kb; // keyboard
var seconds = 2;
var waitTime = 0.25;
var maxAttempts = seconds / waitTime;
var noSuccess = true;
var failMsg = null;
// get whichever keyboard was specified by the user
kb = target().getOneChildElement(this._inputMethod.selector);
// if keyboard doesn't have a typeString (indicating a custom keyboard) then attempt to load that feature
if (kb.typeString === undefined) {
kb.typeString = this._inputMethod.features.typeString;
if (kb.typeString === undefined) {
throw new IlluminatorSetupException("Attempted to use typeString() on a custom keyboard that did not define a 'typeString' feature");
}
}
if (kb.clear === undefined) {
kb.clear = this._inputMethod.features.clear;
if (clear && kb.clear === undefined) {
throw new IlluminatorSetupException("Attempted to use clear() on a custom keyboard that did not define a 'clear' feature");
}
}
// attempt to get a successful keypress several times -- using the first character
// this is a hack for iOS 6.x where the keyboard is sometimes "visible" before usable
while ((clear || noSuccess) && 0 < maxAttempts--) {
try {
// handle clearing
if (clear) {
kb.clear(this);
clear = false; // prevent clear on next iteration
}
if (text.length !== 0) {
kb.typeString(text.charAt(0));
}
noSuccess = false; // here + no error caught means done
}
catch (e) {
failMsg = e;
UIATarget.localTarget().delay(waitTime);
}
}
// report any errors that prevented success
if (0 > maxAttempts && null !== failMsg) throw new IlluminatorRuntimeFailureException("typeString caught error: " + failMsg);
// now type the rest of the string
try {
if (text.length > 0) kb.typeString(text.substr(1));
} catch (e) {
if (-1 == e.toString().indexOf(" failed to tap ")) throw e;
UIALogger.logDebug("Retrying keyboard action, typing slower this time");
this.typeString("", true);
kb.setInterKeyDelay(0.2);
kb.typeString(text);
}
}
/**
* Type a string into a keyboard-like element
*
* Element "this" should have UIAKey elements, and this function will attempt to render the string with the available keys
*
* @todo get really fancy and solve key sequences for keys that have multiple characters on them
* @param text the text to type
*/
function typeStringCustomKeyboard(text) {
var keySet = this.keys();
for (var i = 0; i < text.length; ++i) {
var keyElem = keySet.firstWithName(text[i]);
if (!isNotNilElement(keyElem)) throw new IlluminatorRuntimeFailureException("typeStringCustomKeyboard failed to find key for " + text[i]);
keyElem.tap();
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Object prototype extensions
//
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
extendPrototype(UIAElementNil, {
isNotNil: function () {
return false;
},
isVisible: function () {
return false;
}
});
extendPrototype(UIAElementArray, {
/**
* Same as withName, but takes a regular expression
* @param pattern string regex
*/
withNameRegex: function (pattern) {
var ret = [];
for (var i = 0; i < this.length; ++i) {
var elem = this[i];
if (elem && elem.isNotNil && elem.isNotNil() && elem.name() && elem.name().match(pattern) !== null) {
ret.push(elem);
}
}
return ret;
},
/**
* Same as firstWithName, but takes a regular expression
* @param pattern string regex
*/
firstWithNameRegex: function (pattern) {
for (var i = 0; i < this.length; ++i) {
var elem = this[i];
if (elem && elem.isNotNil && elem.isNotNil() && elem.name()) {
if (elem.name().match(pattern) !== null) return elem;
}
}
return newUIAElementNil();
}
});
extendPrototype(UIASwitch, {
/**
* replacement for setValue on UIASwitch that retries setting value given number of times
*
* @param value boolean value to set on switch
* @param retries integer number of retries to do, defaults to 3
* @param delaySeconds integer delay between retries in seconds, defaults to 1
*/
safeSetValue: function (value, retries, delaySeconds) {
retries = retries || 3;
delaySeconds = delaySeconds || 1;
var exception = null;
for (i = 0; i <= retries; ++i) {
try {
this.setValue(value);
return;
} catch (e) {
exception = e
delay(delaySeconds);
UIALogger.logWarning("Set switch value failed " + i + " times with error " + e);
}
}
if (exception !== null) {
throw exception;
}
},
});
extendPrototype(UIAElement, {
/**
* shortcut function: if UIAutomation creates this element, then it must not be nil
*/
isNotNil: function () {
return true;
},
/*
* A note on what a "selector" is:
*
* It can be one of 4 things.
* 1. A lookup function that takes a base element as an argument and returns another UIAElement.
* 2. A string that contains an expression (starting with "element.") that returns another UIAElement
* 3. An object containing critera to satisfy UIAElement.find() .
* 4. An array of objects containing UIAElement.find() criteria; elem = mainWindow.find(arr[0]).find(arr[1])...
*
* Selector types 1 and 2 are considered "hard" selectors -- they can return at most one element
*/
/**
* get (possibly several) child elements from Criteria, or none
*
* NOTE that this function does not take a selector, just criteria
* @param criteria
*/
getChildElements: function (criteria) {
if (isHardSelector(criteria)) throw new IlluminatorSetupException("getChildElements got a hard selector, which cannot return multiple elements");
criteria = this.preProcessSelector(criteria);
var accessor = this._accessor === undefined ? "<unknown>" : this._accessor;
return getElementsFromCriteria(criteria, this, accessor);
},
/**
* Common behavior for getting one child element from a selector
*
* @param callerName string the name of the calling function, for logging purposes
* @param selector the selector to use
* @param allowZero boolean -- if true, failing selector returns UIAElementNil; if false, throw
*/
_getChildElement: function (callerName, selector, allowZero) {
switch(typeof selector) {
case "function":
return this.preProcessSelector(selector)(this); // TODO: guarantee isNotNil ?
case "object":
return getOneCriteriaSearchResult(callerName, this.getChildElements(selector), selector, allowZero);
case "string":
return getChildElementFromEval(selector, this)
default:
throw new IlluminatorSetupException(caller + " received undefined input type of " + (typeof selector).toString());
}
},
/**
* Get one child element from a selector, or UIAElementNil
* @param selector the selector to use
*/
getChildElement: function (selector) {
return this._getChildElement("getChildElement", selector, true);
},
/**
* Get one and only one child element from a selector, or throw
* @param selector the selector to use
*/
getOneChildElement: function (selector) {
return this._getChildElement("getOneChildElement", selector, false);
},
/**
* Preprocess a selector
*
* This function in the prototype should be overridden by an application-specific function.
* It allows you to rewrite critera or wrap lookup functions to enable additional functionality.
*
* @param selector - a function or set of criteria
* @return selector
*/
preProcessSelector: function (selector) {
return selector;
},
/**
* Equality operator
*
* Properly detects equality of 2 UIAElement objects
* - Can return false positives if 2 elements (and ancestors) have the same name, type, and rect()
* @param elem2 the element to compare to this element
* @param maxRecursion a recursion limit to observe when checking parent element equality (defaults to -1 for infinite)
*/
equals: function (elem2, maxRecursion) {
var sameRect = function (e1, e2) {
var r1 = e1.rect();
var r2 = e2.rect();
return r1.size.width == r2.size.width
&& r1.size.height == r2.size.height
&& r1.origin.x == r2.origin.x
&& r1.origin.y == r2.origin.y;
}
maxRecursion = maxRecursion === undefined ? -1 : maxRecursion;
if (this == elem2) return true; // shortcut when x == x
if (null === elem2) return false; // shortcut when one is null
if (isNotNilElement(this) != isNotNilElement(elem2)) return false; // both nil or neither
if (this.toString() != elem2.toString()) return false; // element type
if (this.name() != elem2.name()) return false;
if (!sameRect(this, elem2)) return false; // possible false positives!
if (this.isVisible() != elem2.isVisible()) return false; // hopefully a way to beat false positives
if (0 == maxRecursion) return true; // stop recursing?
if (-100 == maxRecursion) UIALogger.logWarning("Passed 100 recursions in UIAElement.equals");
return this.parent() === null || this.parent().equals(elem2.parent(), maxRecursion - 1); // check parent elem
},
/**
* General-purpose reduce function
*
* Applies the callback function to each node in the element tree starting from the current element.
*
* Callback function takes (previousValue, currentValue <UIAElement>, accessor_prefix, toplevel <UIAElement>)
* where previousValue is: initialValue (first time), otherwise the previous return from the callback
* currentValue is the UIAElement at the current location in the tree
* accessor_prefix is the code to access this element from the toplevel element
* toplevel is the top-level element on which this reduce function was called
*
* @param callback function
* @param initialValue (any type, dependent on callback)
* @param visibleOnly prunes the search tree to visible elements only
*/
_reduce: function (callback, initialValue, visibleOnly) {
var t0 = getTime();
var currentTimeout = preferences.extensions.reduceTimeout;
var stopTime = t0 + currentTimeout;
var checkTimeout = function (currentOperation) {
if (stopTime < getTime()) {
UIALogger.logDebug("_reduce: " + currentOperation + " hit preferences.extensions.reduceTimeout limit"
+ " of " + currentTimeout + " seconds; terminating with possibly incomplete result");
return true;
}
return false;
};
var reduce_helper = function (elem, acc, prefix) {
var scalars = ["frontMostApp", "mainWindow", "keyboard", "popover"];
var vectors = [];
// iOS 8.1 takes between 3 and 5 milliseconds each (????!?!?!) to evaluate these, so only do it for 7.x
if (isSimVersion(7)) {
vectors = ["activityIndicators", "buttons", "cells", "collectionViews", "images","keys",
"links", "navigationBars", "pageIndicators", "pickers", "progressIndicators",
"scrollViews", "searchBars", "secureTextFields", "segmentedControls", "sliders",
"staticTexts", "switches", "tabBars", "tableViews", "textFields", "textViews",
"toolbars", "webViews", "windows"];
}
// function to visit an element, and add it to an array of what was discovered
var accessed = [];
var visit = function (someElem, accessor, onlyConsiderNew) {
// filter invalid
if (undefined === someElem) return;
if (!someElem.isNotNil()) return;
// filter already visited (in cases where we care)
if (onlyConsiderNew) {
for (var i = 0; i < accessed.length; ++i) {
if (accessed[i].equals(someElem, 0)) return;
}
}
accessed.push(someElem);
// filter based on visibility
if (visibleOnly && !someElem.isVisible()) return;
acc = reduce_helper(someElem, callback(acc, someElem, accessor, this), accessor);
};
// try to access an element by name instead of number
var getNamedIndex = function (someArray, numericIndex) {
var e = someArray[numericIndex];
var name = e.name();
if (name !== null && e.equals(someArray.firstWithName(name), 0)) return '"' + name + '"';
return numericIndex;
}
// visit scalars
for (var i = 0; i < scalars.length; ++i) {
if (undefined === elem[scalars[i]]) continue;
visit(elem[scalars[i]](), prefix + "." + scalars[i] + "()", false);
}
// visit the elements of the vectors
for (var i = 0; i < vectors.length; ++i) {
if (undefined === elem[vectors[i]]) continue;
var elemArray = elem[vectors[i]]();
if (undefined === elemArray) continue;
for (var j = 0; j < elemArray.length; ++j) {
var newElem = elemArray[j];
if (vectors[i] == "windows" && j == 0) continue;
visit(newElem, prefix + "." + vectors[i] + "()[" + getNamedIndex(elemArray, j) + "]", false);
if (checkTimeout("vector loop")) return acc; // respect timeout preference
}
}
// visit any un-visited items
var elemArray = elem.elements();
for (var i = 0; i < elemArray.length; ++i) {
visit(elemArray[i], prefix + ".elements()[" + getNamedIndex(elemArray, i) + "]", true);
if (checkTimeout("element loop")) return acc; // respect timeout preference
}
return acc;
};