summaryrefslogtreecommitdiff
path: root/tests/autofillservice/src/android/autofillservice/cts/testcore/UiBot.java
blob: e10c9c2207236ba6eceeb71fabf10909f6ab64c8 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
/*
 * Copyright (C) 2017 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package android.autofillservice.cts.testcore;

import static android.autofillservice.cts.testcore.Timeouts.DATASET_PICKER_NOT_SHOWN_NAPTIME_MS;
import static android.autofillservice.cts.testcore.Timeouts.LONG_PRESS_MS;
import static android.autofillservice.cts.testcore.Timeouts.SAVE_NOT_SHOWN_NAPTIME_MS;
import static android.autofillservice.cts.testcore.Timeouts.SAVE_TIMEOUT;
import static android.autofillservice.cts.testcore.Timeouts.UI_DATASET_PICKER_TIMEOUT;
import static android.autofillservice.cts.testcore.Timeouts.UI_SCREEN_ORIENTATION_TIMEOUT;
import static android.autofillservice.cts.testcore.Timeouts.UI_TIMEOUT;
import static android.service.autofill.SaveInfo.SAVE_DATA_TYPE_ADDRESS;
import static android.service.autofill.SaveInfo.SAVE_DATA_TYPE_CREDIT_CARD;
import static android.service.autofill.SaveInfo.SAVE_DATA_TYPE_DEBIT_CARD;
import static android.service.autofill.SaveInfo.SAVE_DATA_TYPE_EMAIL_ADDRESS;
import static android.service.autofill.SaveInfo.SAVE_DATA_TYPE_GENERIC;
import static android.service.autofill.SaveInfo.SAVE_DATA_TYPE_GENERIC_CARD;
import static android.service.autofill.SaveInfo.SAVE_DATA_TYPE_PASSWORD;
import static android.service.autofill.SaveInfo.SAVE_DATA_TYPE_PAYMENT_CARD;
import static android.service.autofill.SaveInfo.SAVE_DATA_TYPE_USERNAME;

import static com.android.compatibility.common.util.ShellUtils.runShellCommand;

import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assertWithMessage;

import static org.junit.Assume.assumeTrue;

import android.app.Activity;
import android.app.Instrumentation;
import android.app.UiAutomation;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.graphics.Rect;
import android.hardware.display.DisplayManager;
import android.os.SystemClock;
import android.service.autofill.SaveInfo;
import android.text.Html;
import android.text.Spanned;
import android.text.style.URLSpan;
import android.util.Log;
import android.view.Display;
import android.view.InputDevice;
import android.view.MotionEvent;
import android.view.Surface;
import android.view.View;
import android.view.WindowInsets;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;
import android.view.accessibility.AccessibilityWindowInfo;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.test.platform.app.InstrumentationRegistry;
import androidx.test.uiautomator.By;
import androidx.test.uiautomator.BySelector;
import androidx.test.uiautomator.Configurator;
import androidx.test.uiautomator.Direction;
import androidx.test.uiautomator.SearchCondition;
import androidx.test.uiautomator.StaleObjectException;
import androidx.test.uiautomator.UiDevice;
import androidx.test.uiautomator.UiObject2;
import androidx.test.uiautomator.UiObjectNotFoundException;
import androidx.test.uiautomator.UiScrollable;
import androidx.test.uiautomator.UiSelector;
import androidx.test.uiautomator.Until;

import com.android.compatibility.common.util.RetryableException;
import com.android.compatibility.common.util.Timeout;
import com.android.compatibility.common.util.UserHelper;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeoutException;

/**
 * Helper for UI-related needs.
 */
public class UiBot {

    private static final String TAG = "AutoFillCtsUiBot";

    private static final String RESOURCE_ID_DATASET_PICKER = "autofill_dataset_picker";
    private static final String RESOURCE_ID_DATASET_HEADER = "autofill_dataset_header";
    private static final String RESOURCE_ID_SAVE_SNACKBAR = "autofill_save";
    private static final String RESOURCE_ID_SAVE_ICON = "autofill_save_icon";
    private static final String RESOURCE_ID_SAVE_TITLE = "autofill_save_title";
    private static final String RESOURCE_ID_CONTEXT_MENUITEM = "floating_toolbar_menu_item_text";
    private static final String RESOURCE_ID_SAVE_BUTTON_NO = "autofill_save_no";
    private static final String RESOURCE_ID_SAVE_BUTTON_YES = "autofill_save_yes";
    private static final String RESOURCE_ID_OVERFLOW = "overflow";

    private static final String RESOURCE_STRING_SAVE_TITLE = "autofill_save_title";
    private static final String RESOURCE_STRING_SAVE_TITLE_WITH_TYPE =
            "autofill_save_title_with_type";
    private static final String RESOURCE_STRING_SAVE_TYPE_PASSWORD = "autofill_save_type_password";
    private static final String RESOURCE_STRING_SAVE_TYPE_ADDRESS = "autofill_save_type_address";
    private static final String RESOURCE_STRING_SAVE_TYPE_CREDIT_CARD =
            "autofill_save_type_credit_card";
    private static final String RESOURCE_STRING_SAVE_TYPE_USERNAME = "autofill_save_type_username";
    private static final String RESOURCE_STRING_SAVE_TYPE_EMAIL_ADDRESS =
            "autofill_save_type_email_address";
    private static final String RESOURCE_STRING_SAVE_TYPE_DEBIT_CARD =
            "autofill_save_type_debit_card";
    private static final String RESOURCE_STRING_SAVE_TYPE_PAYMENT_CARD =
            "autofill_save_type_payment_card";
    private static final String RESOURCE_STRING_SAVE_TYPE_GENERIC_CARD =
            "autofill_save_type_generic_card";
    private static final String RESOURCE_STRING_SAVE_BUTTON_NEVER = "autofill_save_never";
    private static final String RESOURCE_STRING_SAVE_BUTTON_NOT_NOW = "autofill_save_notnow";
    private static final String RESOURCE_STRING_SAVE_BUTTON_NO_THANKS = "autofill_save_no";
    private static final String RESOURCE_STRING_SAVE_BUTTON_YES = "autofill_save_yes";
    private static final String RESOURCE_STRING_UPDATE_BUTTON_YES = "autofill_update_yes";
    private static final String RESOURCE_STRING_CONTINUE_BUTTON_YES = "autofill_continue_yes";
    private static final String RESOURCE_STRING_UPDATE_TITLE = "autofill_update_title";
    private static final String RESOURCE_STRING_UPDATE_TITLE_WITH_TYPE =
            "autofill_update_title_with_type";

    private static final String RESOURCE_STRING_AUTOFILL = "autofill";
    private static final String RESOURCE_STRING_DATASET_PICKER_ACCESSIBILITY_TITLE =
            "autofill_picker_accessibility_title";
    private static final String RESOURCE_STRING_SAVE_SNACKBAR_ACCESSIBILITY_TITLE =
            "autofill_save_accessibility_title";

    private static final String RESOURCE_ID_FILL_DIALOG_PICKER = "autofill_dialog_picker";
    private static final String RESOURCE_ID_FILL_DIALOG_HEADER = "autofill_dialog_header";
    private static final String RESOURCE_ID_FILL_DIALOG_DATASET = "autofill_dialog_list";
    private static final String RESOURCE_ID_FILL_DIALOG_BUTTON_NO = "autofill_dialog_no";
    private static final String RESOURCE_ID_FILL_DIALOG_BUTTON_YES = "autofill_dialog_yes";

    static final BySelector DATASET_PICKER_SELECTOR = By.res("android", RESOURCE_ID_DATASET_PICKER);
    private static final BySelector SAVE_UI_SELECTOR = By.res("android", RESOURCE_ID_SAVE_SNACKBAR);
    private static final BySelector DATASET_HEADER_SELECTOR =
            By.res("android", RESOURCE_ID_DATASET_HEADER);
    private static final BySelector FILL_DIALOG_SELECTOR =
            By.res("android", RESOURCE_ID_FILL_DIALOG_PICKER);
    private static final BySelector FILL_DIALOG_HEADER_SELECTOR =
            By.res("android", RESOURCE_ID_FILL_DIALOG_HEADER);
    private static final BySelector FILL_DIALOG_DATASET_SELECTOR =
            By.res("android", RESOURCE_ID_FILL_DIALOG_DATASET);


    // TODO: figure out a more reliable solution that does not depend on SystemUI resources.
    private static final String SPLIT_WINDOW_DIVIDER_ID =
            "com.android.systemui:id/docked_divider_background";

    private static final boolean DUMP_ON_ERROR = true;

    private static final int MAX_UIOBJECT_RETRY_COUNT = 3;

    /**
     * Pass to {@link #setScreenOrientation(int)} to change the display to portrait mode.
     * This is an alias of Surface.ROTATION_0 though it's named as PORTRAIT for historical reasons.
     */
    public static final int PORTRAIT = Surface.ROTATION_0;

    /**
     * Pass to {@link #setScreenOrientation(int)} to change the display to landscape mode.
     * This is an alias of Surface.ROTATION_90 though it's named as LANDSCAPE for historical
     * reasons.
     */
    public static final int LANDSCAPE = Surface.ROTATION_90;

    private final UiDevice mDevice;
    private final Context mContext;
    private final UserHelper mUserHelper;
    private final String mPackageName;
    private final UiAutomation mAutoman;
    private final Timeout mDefaultTimeout;

    private boolean mOkToCallAssertNoDatasets;

    public UiBot() {
        this(UI_TIMEOUT);
    }

    public UiBot(Timeout defaultTimeout) {
        mDefaultTimeout = defaultTimeout;
        final Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
        mDevice = UiDevice.getInstance(instrumentation);
        mContext = instrumentation.getContext();
        mUserHelper = new UserHelper(mContext);
        mPackageName = mContext.getPackageName();
        mAutoman = instrumentation.getUiAutomation();
    }

    public void waitForIdle() {
        final long before = SystemClock.elapsedRealtimeNanos();
        mDevice.waitForIdle();
        final float delta = ((float) (SystemClock.elapsedRealtimeNanos() - before)) / 1_000_000;
        Log.v(TAG, "device idle in " + delta + "ms");
    }

    public void waitForIdleSync() {
        final long before = SystemClock.elapsedRealtimeNanos();
        InstrumentationRegistry.getInstrumentation().waitForIdleSync();
        final float delta = ((float) (SystemClock.elapsedRealtimeNanos() - before)) / 1_000_000;
        Log.v(TAG, "device idle sync in " + delta + "ms");
    }

    public void reset() {
        mOkToCallAssertNoDatasets = false;
    }

    /**
     * Assumes the device has a minimum height and width of {@code minSize}, throwing a
     * {@code AssumptionViolatedException} if it doesn't (so the test is skiped by the JUnit
     * Runner).
     */
    public void assumeMinimumResolution(int minSize) {
        final int width = mDevice.getDisplayWidth();
        final int heigth = mDevice.getDisplayHeight();
        final int min = Math.min(width, heigth);
        assumeTrue("Screen size is too small (" + width + "x" + heigth + ")", min >= minSize);
        Log.d(TAG, "assumeMinimumResolution(" + minSize + ") passed: screen size is "
                + width + "x" + heigth);
    }

    /**
     * Sets the screen resolution in a way that the IME doesn't interfere with the Autofill UI
     * when the device is rotated to landscape.
     *
     * When called, test must call <p>{@link #resetScreenResolution()} in a {@code finally} block.
     *
     * @deprecated this method should not be necessarily anymore as we're using a MockIme.
     */
    @Deprecated
    // TODO: remove once we're sure no more OEM is getting failure due to screen size
    public void setScreenResolution() {
        if (false) {
            Log.w(TAG, "setScreenResolution(): ignored");
            return;
        }
        assumeMinimumResolution(500);

        runShellCommand("wm size 1080x1920");
        runShellCommand("wm density 320");
    }

    /**
     * Resets the screen resolution.
     *
     * <p>Should always be called after {@link #setScreenResolution()}.
     *
     * @deprecated this method should not be necessarily anymore as we're using a MockIme.
     */
    @Deprecated
    // TODO: remove once we're sure no more OEM is getting failure due to screen size
    public void resetScreenResolution() {
        if (false) {
            Log.w(TAG, "resetScreenResolution(): ignored");
            return;
        }
        runShellCommand("wm density reset");
        runShellCommand("wm size reset");
    }

    /**
     * Asserts the dataset picker is not shown anymore.
     *
     * @throws IllegalStateException if called *before* an assertion was made to make sure the
     * dataset picker is shown - if that's not the case, call
     * {@link #assertNoDatasetsEver()} instead.
     */
    public void assertNoDatasets() throws Exception {
        if (!mOkToCallAssertNoDatasets) {
            throw new IllegalStateException(
                    "Cannot call assertNoDatasets() without calling assertDatasets first");
        }
        mDevice.wait(Until.gone(DATASET_PICKER_SELECTOR), UI_DATASET_PICKER_TIMEOUT.ms());
        mOkToCallAssertNoDatasets = false;
    }

    /**
     * Asserts the dataset picker was never shown.
     *
     * <p>This method is slower than {@link #assertNoDatasets()} and should only be called in the
     * cases where the dataset picker was not previous shown.
     */
    public void assertNoDatasetsEver() throws Exception {
        assertNeverShown("dataset picker", DATASET_PICKER_SELECTOR,
                DATASET_PICKER_NOT_SHOWN_NAPTIME_MS);
    }

    /**
     * Asserts the dataset chooser is shown and contains exactly the given datasets.
     *
     * @return the dataset picker object.
     */
    public UiObject2 assertDatasets(String...names) throws Exception {
        final UiObject2 picker = findDatasetPicker(UI_DATASET_PICKER_TIMEOUT);
        return assertDatasets(picker, names);
    }

    protected UiObject2 assertDatasets(UiObject2 picker, String...names) {
        assertWithMessage("wrong dataset names").that(getChildrenAsText(picker))
                .containsExactlyElementsIn(Arrays.asList(names)).inOrder();
        return picker;
    }

    /**
     * Asserts the dataset chooser is shown and contains the given datasets.
     *
     * @return the dataset picker object.
     */
    public UiObject2 assertDatasetsContains(String...names) throws Exception {
        final UiObject2 picker = findDatasetPicker(UI_DATASET_PICKER_TIMEOUT);
        assertWithMessage("wrong dataset names").that(getChildrenAsText(picker))
                .containsAtLeastElementsIn(Arrays.asList(names)).inOrder();
        return picker;
    }

    /**
     * Asserts the dataset chooser is shown and contains the given datasets, header, and footer.
     * <p>In fullscreen, header view is not under R.id.autofill_dataset_picker.
     *
     * @return the dataset picker object.
     */
    public UiObject2 assertDatasetsWithBorders(String header, String footer, String...names)
            throws Exception {
        final UiObject2 picker = findDatasetPicker(UI_DATASET_PICKER_TIMEOUT);
        final List<String> expectedChild = new ArrayList<>();
        if (header != null) {
            if (Helper.isAutofillWindowFullScreen(mContext)) {
                final UiObject2 headerView = waitForObject(DATASET_HEADER_SELECTOR,
                        UI_DATASET_PICKER_TIMEOUT);
                assertWithMessage("fullscreen wrong dataset header")
                        .that(getChildrenAsText(headerView))
                        .containsExactlyElementsIn(Arrays.asList(header)).inOrder();
            } else {
                expectedChild.add(header);
            }
        }
        expectedChild.addAll(Arrays.asList(names));
        if (footer != null) {
            expectedChild.add(footer);
        }
        assertWithMessage("wrong elements on dataset picker").that(getChildrenAsText(picker))
                .containsExactlyElementsIn(expectedChild).inOrder();
        return picker;
    }

    /**
     * Gets the text of this object children.
     */
    public List<String> getChildrenAsText(UiObject2 object) {
        final List<String> list = new ArrayList<>();
        getChildrenAsText(object, list);
        return list;
    }

    private static void getChildrenAsText(UiObject2 object, List<String> children) {
        final String text = object.getText();
        if (text != null) {
            children.add(text);
        }
        for (UiObject2 child : object.getChildren()) {
            getChildrenAsText(child, children);
        }
    }

    /**
     * Selects a dataset that should be visible in the floating UI and does not need to wait for
     * application become idle.
     */
    public void selectDataset(String name) throws Exception {
        final UiObject2 picker = findDatasetPicker(UI_DATASET_PICKER_TIMEOUT);
        selectDataset(picker, name);
    }

    /**
     * Selects a dataset that should be visible in the floating UI and waits for application become
     * idle if needed.
     */
    public void selectDatasetSync(String name) throws Exception {
        final UiObject2 picker = findDatasetPicker(UI_DATASET_PICKER_TIMEOUT);
        selectDataset(picker, name);
        mDevice.waitForIdle();
    }

    /**
     * Selects a dataset that should be visible in the floating UI.
     */
    public void selectDataset(UiObject2 picker, String name) {
        final UiObject2 dataset = picker.findObject(By.text(name));
        if (dataset == null) {
            throw new AssertionError("no dataset " + name + " in " + getChildrenAsText(picker));
        }
        dataset.click();
    }

    /**
     * Finds the suggestion by name and perform long click on suggestion to trigger attribution
     * intent.
     */
    public void longPressSuggestion(String name) throws Exception {
        throw new UnsupportedOperationException();
    }

    /**
     * Asserts the suggestion chooser is shown in the suggestion view.
     */
    public void assertSuggestion(String name) throws Exception {
        throw new UnsupportedOperationException();
    }

    /**
     * Asserts the suggestion chooser is not shown in the suggestion view.
     */
    public void assertNoSuggestion(String name) throws Exception {
        throw new UnsupportedOperationException();
    }

    /**
     * Scrolls the suggestion view.
     *
     * @param direction The direction to scroll.
     * @param speed The speed to scroll per second.
     */
    public void scrollSuggestionView(Direction direction, int speed) throws Exception {
        throw new UnsupportedOperationException();
    }

    /**
     * Selects a view by text.
     *
     * <p><b>NOTE:</b> when selecting an option in dataset picker is shown, prefer
     * {@link #selectDataset(String)}.
     */
    public void selectByText(String name) throws Exception {
        Log.v(TAG, "selectByText(): " + name);

        final UiObject2 object = waitForObject(By.text(name));
        object.click();
    }

    /**
     * Asserts a text is shown.
     *
     * <p><b>NOTE:</b> when asserting the dataset picker is shown, prefer
     * {@link #assertDatasets(String...)}.
     */
    public UiObject2 assertShownByText(String text) throws Exception {
        return assertShownByText(text, mDefaultTimeout);
    }

    public UiObject2 assertShownByText(String text, Timeout timeout) throws Exception {
        final UiObject2 object = waitForObject(By.text(text), timeout);
        assertWithMessage("No node with text '%s'", text).that(object).isNotNull();
        return object;
    }

    /**
     * Finds a node by text, without waiting for it to be shown (but failing if it isn't).
     */
    @NonNull
    public UiObject2 findRightAwayByText(@NonNull String text) throws Exception {
        final UiObject2 object = mDevice.findObject(By.text(text));
        assertWithMessage("no UIObject for text '%s'", text).that(object).isNotNull();
        return object;
    }

    /**
     * Asserts that the text is not showing for sure in the screen "as is", i.e., without waiting
     * for it.
     *
     * <p>Typically called after another assertion that waits for a condition to be shown.
     */
    public void assertNotShowingForSure(String text) throws Exception {
        final UiObject2 object = mDevice.findObject(By.text(text));
        assertWithMessage("Found node with text '%s'", text).that(object).isNull();
    }

    /**
     * Asserts a node with the given content description is shown.
     *
     */
    public UiObject2 assertShownByContentDescription(String contentDescription) throws Exception {
        final UiObject2 object = waitForObject(By.desc(contentDescription));
        assertWithMessage("No node with content description '%s'", contentDescription).that(object)
                .isNotNull();
        return object;
    }

    /**
     * Checks if a View with a certain text exists.
     */
    public boolean hasViewWithText(String name) {
        Log.v(TAG, "hasViewWithText(): " + name);

        return mDevice.findObject(By.text(name)) != null;
    }

    /**
     * Selects a view by id.
     */
    public UiObject2 selectByRelativeId(String id) throws Exception {
        Log.v(TAG, "selectByRelativeId(): " + id);
        UiObject2 object = waitForObject(By.res(mPackageName, id));
        object.click();
        return object;
    }

    /**
     * Asserts the id is shown on the screen.
     */
    public UiObject2 assertShownById(String id) throws Exception {
        final UiObject2 object = waitForObject(By.res(id));
        assertThat(object).isNotNull();
        return object;
    }

    /**
     * Asserts the id is shown on the screen, using a resource id from the test package.
     */
    public UiObject2 assertShownByRelativeId(String id) throws Exception {
        return assertShownByRelativeId(id, mDefaultTimeout);
    }

    public UiObject2 assertShownByRelativeId(String id, Timeout timeout) throws Exception {
        final UiObject2 obj = waitForObject(By.res(mPackageName, id), timeout);
        assertThat(obj).isNotNull();
        return obj;
    }

    /**
     * Asserts the id is not shown on the screen anymore, using a resource id from the test package.
     *
     * <p><b>Note:</b> this method should only called AFTER the id was previously shown, otherwise
     * it might pass without really asserting anything.
     */
    public void assertGoneByRelativeId(@NonNull String id, @NonNull Timeout timeout) {
        assertGoneByRelativeId(/* parent = */ null, id, timeout);
    }

    public void assertGoneByRelativeId(int resId, @NonNull Timeout timeout) {
        assertGoneByRelativeId(/* parent = */ null, getIdName(resId), timeout);
    }

    private String getIdName(int resId) {
        return mContext.getResources().getResourceEntryName(resId);
    }

    /**
     * Asserts the id is not shown on the parent anymore, using a resource id from the test package.
     *
     * <p><b>Note:</b> this method should only called AFTER the id was previously shown, otherwise
     * it might pass without really asserting anything.
     */
    public void assertGoneByRelativeId(@Nullable UiObject2 parent, @NonNull String id,
            @NonNull Timeout timeout) {
        final SearchCondition<Boolean> condition = Until.gone(By.res(mPackageName, id));
        final boolean gone = parent != null
                ? parent.wait(condition, timeout.ms())
                : mDevice.wait(condition, timeout.ms());
        if (!gone) {
            final String message = "Object with id '" + id + "' should be gone after "
                    + timeout + " ms";
            dumpScreen(message);
            throw new RetryableException(message);
        }
    }

    public UiObject2 assertShownByRelativeId(int resId) throws Exception {
        return assertShownByRelativeId(getIdName(resId));
    }

    public void assertNeverShownByRelativeId(@NonNull String description, int resId, long timeout)
            throws Exception {
        final BySelector selector = By.res(Helper.MY_PACKAGE, getIdName(resId));
        assertNeverShown(description, selector, timeout);
    }

    /**
     * Asserts that a {@code selector} is not showing after {@code timeout} milliseconds.
     */
    protected void assertNeverShown(String description, BySelector selector, long timeout)
            throws Exception {
        SystemClock.sleep(timeout);
        final UiObject2 object = mDevice.findObject(selector);
        if (object != null) {
            throw new AssertionError(
                    String.format("Should not be showing %s after %dms, but got %s",
                            description, timeout, getChildrenAsText(object)));
        }
    }

    /**
     * Gets the text set on a view.
     */
    public String getTextByRelativeId(String id) throws Exception {
        return waitForObject(By.res(mPackageName, id)).getText();
    }

    /**
     * Focus in the view with the given resource id.
     */
    public void focusByRelativeId(String id) throws Exception {
        waitForObject(By.res(mPackageName, id)).click();
    }

    /**
     * Sets a new text on a view.
     */
    public void setTextByRelativeId(String id, String newText) throws Exception {
        waitForObject(By.res(mPackageName, id)).setText(newText);
    }

    /**
     * Asserts the save snackbar is showing and returns it.
     */
    public UiObject2 assertSaveShowing(int type) throws Exception {
        return assertSaveShowing(SAVE_TIMEOUT, type);
    }

    /**
     * Asserts the save snackbar is showing with a custom service name and returns it.
     */
    public UiObject2 assertSaveShowingWithCustomServiceName(int type, String customServiceName)
            throws Exception {
        return assertSaveOrUpdateShowing(/* update= */ false, SaveInfo.NEGATIVE_BUTTON_STYLE_CANCEL,
                SaveInfo.POSITIVE_BUTTON_STYLE_SAVE, null, SAVE_TIMEOUT, customServiceName, type);
    }

    /**
     * Asserts the save snackbar is showing and returns it.
     */
    public UiObject2 assertSaveShowing(Timeout timeout, int type) throws Exception {
        return assertSaveShowing(null, timeout, type);
    }

    /**
     * Asserts the save snackbar is showing with the Update message and returns it.
     */
    public UiObject2 assertUpdateShowing(int... types) throws Exception {
        return assertSaveOrUpdateShowing(/* update= */ true, SaveInfo.NEGATIVE_BUTTON_STYLE_CANCEL,
                null, SAVE_TIMEOUT, types);
    }

    /**
     * Presses the Back button.
     */
    public void pressBack() {
        Log.d(TAG, "pressBack()");
        mDevice.pressBack();
    }

    /**
     * Presses the Home button.
     */
    public void pressHome() {
        Log.d(TAG, "pressHome()");
        mDevice.pressHome();
    }

    /**
     * Asserts the save snackbar is not showing.
     */
    public void assertSaveNotShowing(int type) throws Exception {
        assertNeverShown("save UI for type " + saveTypeToString(type), SAVE_UI_SELECTOR,
                SAVE_NOT_SHOWN_NAPTIME_MS);
    }

    /**
     * Asserts the save snackbar is not showing, explaining when.
     */
    public void assertSaveNotShowing(int type, @Nullable String when) throws Exception {
        String suffix = when == null ? "" : " when " + when;
        assertNeverShown("save UI for type " + saveTypeToString(type) + suffix, SAVE_UI_SELECTOR,
                SAVE_NOT_SHOWN_NAPTIME_MS);
    }

    public void assertSaveNotShowing() throws Exception {
        assertNeverShown("save UI", SAVE_UI_SELECTOR, SAVE_NOT_SHOWN_NAPTIME_MS);
    }

    private String getSaveTypeString(int type) {
        final String typeResourceName;
        switch (type) {
            case SAVE_DATA_TYPE_PASSWORD:
                typeResourceName = RESOURCE_STRING_SAVE_TYPE_PASSWORD;
                break;
            case SAVE_DATA_TYPE_ADDRESS:
                typeResourceName = RESOURCE_STRING_SAVE_TYPE_ADDRESS;
                break;
            case SAVE_DATA_TYPE_CREDIT_CARD:
                typeResourceName = RESOURCE_STRING_SAVE_TYPE_CREDIT_CARD;
                break;
            case SAVE_DATA_TYPE_USERNAME:
                typeResourceName = RESOURCE_STRING_SAVE_TYPE_USERNAME;
                break;
            case SAVE_DATA_TYPE_EMAIL_ADDRESS:
                typeResourceName = RESOURCE_STRING_SAVE_TYPE_EMAIL_ADDRESS;
                break;
            case SAVE_DATA_TYPE_DEBIT_CARD:
                typeResourceName = RESOURCE_STRING_SAVE_TYPE_DEBIT_CARD;
                break;
            case SAVE_DATA_TYPE_PAYMENT_CARD:
                typeResourceName = RESOURCE_STRING_SAVE_TYPE_PAYMENT_CARD;
                break;
            case SAVE_DATA_TYPE_GENERIC_CARD:
                typeResourceName = RESOURCE_STRING_SAVE_TYPE_GENERIC_CARD;
                break;
            default:
                throw new IllegalArgumentException("Unsupported type: " + type);
        }
        return getString(typeResourceName);
    }

    private String saveTypeToString(int type) {
        // Cannot use DebugUtils, it's @hide
        switch (type) {
            case SAVE_DATA_TYPE_PASSWORD:
                return "PASSWORD";
            case SAVE_DATA_TYPE_ADDRESS:
                return "ADDRESS";
            case SAVE_DATA_TYPE_CREDIT_CARD:
                return "CREDIT_CARD";
            case SAVE_DATA_TYPE_USERNAME:
                return "USERNAME";
            case SAVE_DATA_TYPE_EMAIL_ADDRESS:
                return "EMAIL_ADDRESS";
            case SAVE_DATA_TYPE_DEBIT_CARD:
                return "DEBIT_CARD";
            case SAVE_DATA_TYPE_PAYMENT_CARD:
                return "PAYMENT_CARD";
            case SAVE_DATA_TYPE_GENERIC_CARD:
                return "GENERIC_CARD";
            default:
                return "UNSUPPORT_TYPE_" + type;
        }
    }

    public UiObject2 assertSaveShowing(String description, int... types) throws Exception {
        return assertSaveOrUpdateShowing(/* update= */ false, SaveInfo.NEGATIVE_BUTTON_STYLE_CANCEL,
                description, SAVE_TIMEOUT, types);
    }

    public UiObject2 assertSaveShowing(String description, Timeout timeout, int... types)
            throws Exception {
        return assertSaveOrUpdateShowing(/* update= */ false, SaveInfo.NEGATIVE_BUTTON_STYLE_CANCEL,
                description, timeout, types);
    }

    public UiObject2 assertSaveShowing(int negativeButtonStyle, String description,
            int... types) throws Exception {
        return assertSaveOrUpdateShowing(/* update= */ false, negativeButtonStyle, description,
                SAVE_TIMEOUT, types);
    }

    public UiObject2 assertSaveShowing(int positiveButtonStyle, int... types) throws Exception {
        return assertSaveOrUpdateShowing(/* update= */ false, SaveInfo.NEGATIVE_BUTTON_STYLE_CANCEL,
                positiveButtonStyle, /* description= */ null, SAVE_TIMEOUT, types);
    }

    public UiObject2 assertSaveOrUpdateShowing(boolean update, int negativeButtonStyle,
            String description, Timeout timeout, int... types) throws Exception {
        return assertSaveOrUpdateShowing(update, negativeButtonStyle,
                SaveInfo.POSITIVE_BUTTON_STYLE_SAVE, description, timeout, types);
    }

    public UiObject2 assertSaveOrUpdateShowing(boolean update, int negativeButtonStyle,
            int positiveButtonStyle, String description, Timeout timeout, int... types)
            throws Exception {
        return assertSaveOrUpdateShowing(update, negativeButtonStyle, positiveButtonStyle,
            description, timeout, InstrumentedAutoFillService.getServiceLabel(), types);
    }

    public UiObject2 assertSaveOrUpdateShowing(boolean update, int negativeButtonStyle,
            int positiveButtonStyle, String description, Timeout timeout, String serviceLabel,
            int... types) throws Exception {

        final UiObject2 snackbar = waitForObject(SAVE_UI_SELECTOR, timeout);

        final UiObject2 titleView =
                waitForObject(snackbar, By.res("android", RESOURCE_ID_SAVE_TITLE), timeout);
        assertWithMessage("save title (%s) is not shown", RESOURCE_ID_SAVE_TITLE).that(titleView)
                .isNotNull();

        final UiObject2 iconView =
                waitForObject(snackbar, By.res("android", RESOURCE_ID_SAVE_ICON), timeout);
        assertWithMessage("save icon (%s) is not shown", RESOURCE_ID_SAVE_ICON).that(iconView)
                .isNotNull();

        final String actualTitle = titleView.getText();
        Log.d(TAG, "save title: " + actualTitle);

        final String titleId, titleWithTypeId;
        if (update) {
            titleId = RESOURCE_STRING_UPDATE_TITLE;
            titleWithTypeId = RESOURCE_STRING_UPDATE_TITLE_WITH_TYPE;
        } else {
            titleId = RESOURCE_STRING_SAVE_TITLE;
            titleWithTypeId = RESOURCE_STRING_SAVE_TITLE_WITH_TYPE;
        }

        switch (types.length) {
            case 1:
                final String expectedTitle = (types[0] == SAVE_DATA_TYPE_GENERIC)
                        ? Html.fromHtml(getString(titleId, serviceLabel), 0).toString()
                        : Html.fromHtml(getString(titleWithTypeId,
                                getSaveTypeString(types[0]), serviceLabel), 0).toString();
                assertThat(actualTitle).isEqualTo(expectedTitle);
                break;
            case 2:
                // We cannot predict the order...
                assertThat(actualTitle).contains(getSaveTypeString(types[0]));
                assertThat(actualTitle).contains(getSaveTypeString(types[1]));
                break;
            case 3:
                // We cannot predict the order...
                assertThat(actualTitle).contains(getSaveTypeString(types[0]));
                assertThat(actualTitle).contains(getSaveTypeString(types[1]));
                assertThat(actualTitle).contains(getSaveTypeString(types[2]));
                break;
            default:
                throw new IllegalArgumentException("Invalid types: " + Arrays.toString(types));
        }

        if (description != null) {
            final UiObject2 saveSubTitle = snackbar.findObject(By.text(description));
            assertWithMessage("save subtitle(%s)", description).that(saveSubTitle).isNotNull();
        }

        final String positiveButtonStringId;
        switch (positiveButtonStyle) {
            case SaveInfo.POSITIVE_BUTTON_STYLE_CONTINUE:
                positiveButtonStringId = RESOURCE_STRING_CONTINUE_BUTTON_YES;
                break;
            default:
                positiveButtonStringId = update ? RESOURCE_STRING_UPDATE_BUTTON_YES
                        : RESOURCE_STRING_SAVE_BUTTON_YES;
        }
        final String expectedPositiveButtonText = getString(positiveButtonStringId).toUpperCase();
        final UiObject2 positiveButton = waitForObject(snackbar,
                By.res("android", RESOURCE_ID_SAVE_BUTTON_YES), timeout);
        assertWithMessage("wrong text on positive button")
                .that(positiveButton.getText().toUpperCase()).isEqualTo(expectedPositiveButtonText);

        final String negativeButtonStringId;
        if (negativeButtonStyle == SaveInfo.NEGATIVE_BUTTON_STYLE_REJECT) {
            negativeButtonStringId = RESOURCE_STRING_SAVE_BUTTON_NOT_NOW;
        } else if (negativeButtonStyle == SaveInfo.NEGATIVE_BUTTON_STYLE_NEVER) {
            negativeButtonStringId = RESOURCE_STRING_SAVE_BUTTON_NEVER;
        } else {
            negativeButtonStringId = RESOURCE_STRING_SAVE_BUTTON_NO_THANKS;
        }
        final String expectedNegativeButtonText = getString(negativeButtonStringId).toUpperCase();
        final UiObject2 negativeButton = waitForObject(snackbar,
                By.res("android", RESOURCE_ID_SAVE_BUTTON_NO), timeout);
        assertWithMessage("wrong text on negative button")
                .that(negativeButton.getText().toUpperCase()).isEqualTo(expectedNegativeButtonText);

        final String expectedAccessibilityTitle =
                getString(RESOURCE_STRING_SAVE_SNACKBAR_ACCESSIBILITY_TITLE);
        timeout.run(
                String.format(
                        "assertAccessibilityTitle(%s, %s)",
                        snackbar,
                        expectedAccessibilityTitle),
                () -> {
                    try {
                        assertAccessibilityTitle(snackbar, expectedAccessibilityTitle);
                    } catch (RetryableException e) {
                        return null;
                    }
                    return true;
                });
        return snackbar;
    }

    /**
     * Taps an option in the save snackbar.
     *
     * @param yesDoIt {@code true} for 'YES', {@code false} for 'NO THANKS'.
     * @param types expected types of save info.
     */
    public void saveForAutofill(boolean yesDoIt, int... types) throws Exception {
        final UiObject2 saveSnackBar = assertSaveShowing(
                SaveInfo.NEGATIVE_BUTTON_STYLE_CANCEL, null, types);
        saveForAutofill(saveSnackBar, yesDoIt);
    }

    public void updateForAutofill(boolean yesDoIt, int... types) throws Exception {
        final UiObject2 saveUi = assertUpdateShowing(types);
        saveForAutofill(saveUi, yesDoIt);
    }

    /**
     * Taps an option in the save snackbar.
     *
     * @param yesDoIt {@code true} for 'YES', {@code false} for 'NO THANKS'.
     * @param types expected types of save info.
     */
    public void saveForAutofill(int negativeButtonStyle, boolean yesDoIt, int... types)
            throws Exception {
        final UiObject2 saveSnackBar = assertSaveShowing(negativeButtonStyle, null, types);
        saveForAutofill(saveSnackBar, yesDoIt);
    }

    /**
     * Taps the positive button in the save snackbar.
     *
     * @param types expected types of save info.
     */
    public void saveForAutofill(int positiveButtonStyle, int... types) throws Exception {
        final UiObject2 saveSnackBar = assertSaveShowing(positiveButtonStyle, types);
        saveForAutofill(saveSnackBar, /* yesDoIt= */ true);
    }

    /**
     * Taps an option in the save snackbar.
     *
     * @param saveSnackBar Save snackbar, typically obtained through
     *            {@link #assertSaveShowing(int)}.
     * @param yesDoIt {@code true} for 'YES', {@code false} for 'NO THANKS'.
     */
    public void saveForAutofill(UiObject2 saveSnackBar, boolean yesDoIt) {
        final String id = yesDoIt ? "autofill_save_yes" : "autofill_save_no";

        final UiObject2 button = saveSnackBar.findObject(By.res("android", id));
        assertWithMessage("save button (%s)", id).that(button).isNotNull();
        button.click();
    }

    /**
     * Gets the AUTOFILL contextual menu by long pressing a text field.
     *
     * <p><b>NOTE:</b> this method should only be called in scenarios where we explicitly want to
     * test the overflow menu. For all other scenarios where we want to test manual autofill, it's
     * better to call {@code AFM.requestAutofill()} directly, because it's less error-prone and
     * faster.
     *
     * @param id resource id of the field.
     */
    public UiObject2 getAutofillMenuOption(String id) throws Exception {
        final UiObject2 field = waitForObject(By.res(mPackageName, id));
        // TODO: figure out why obj.longClick() doesn't always work
        field.click(LONG_PRESS_MS);

        List<UiObject2> menuItems = waitForObjects(
                By.res("android", RESOURCE_ID_CONTEXT_MENUITEM), mDefaultTimeout);
        final String expectedText = getAutofillContextualMenuTitle();

        final StringBuffer menuNames = new StringBuffer();

        // Check first menu for AUTOFILL
        for (UiObject2 menuItem : menuItems) {
            final String menuName = menuItem.getText();
            if (menuName.equalsIgnoreCase(expectedText)) {
                Log.v(TAG, "AUTOFILL found in first menu");
                return menuItem;
            }
            menuNames.append("'").append(menuName).append("' ");
        }

        menuNames.append(";");

        // First menu does not have AUTOFILL, check overflow
        final BySelector overflowSelector = By.res("android", RESOURCE_ID_OVERFLOW);

        // Click overflow menu button.
        final UiObject2 overflowMenu = waitForObject(overflowSelector, mDefaultTimeout);
        overflowMenu.click();

        // Wait for overflow menu to show.
        mDevice.wait(Until.gone(overflowSelector), 1000);

        menuItems = waitForObjects(
                By.res("android", RESOURCE_ID_CONTEXT_MENUITEM), mDefaultTimeout);
        for (UiObject2 menuItem : menuItems) {
            final String menuName = menuItem.getText();
            if (menuName.equalsIgnoreCase(expectedText)) {
                Log.v(TAG, "AUTOFILL found in overflow menu");
                return menuItem;
            }
            menuNames.append("'").append(menuName).append("' ");
        }
        throw new RetryableException("no '%s' on '%s'", expectedText, menuNames);
    }

    String getAutofillContextualMenuTitle() {
        return getString(RESOURCE_STRING_AUTOFILL);
    }

    /**
     * Gets a string from the Android resources.
     */
    private String getString(String id) {
        final Resources resources = mContext.getResources();
        final int stringId = resources.getIdentifier(id, "string", "android");
        try {
            return resources.getString(stringId);
        } catch (Resources.NotFoundException e) {
            throw new IllegalStateException("no internal string for '" + id + "' / res=" + stringId
                    + ": ", e);
        }
    }

    /**
     * Gets a string from the Android resources.
     */
    private String getString(String id, Object... formatArgs) {
        final Resources resources = mContext.getResources();
        final int stringId = resources.getIdentifier(id, "string", "android");
        try {
            return resources.getString(stringId, formatArgs);
        } catch (Resources.NotFoundException e) {
            throw new IllegalStateException("no internal string for '" + id + "' / res=" + stringId
                    + ": ", e);
        }
    }

    /**
     * Waits for and returns an object.
     *
     * @param selector {@link BySelector} that identifies the object.
     */
    private UiObject2 waitForObject(BySelector selector) throws Exception {
        return waitForObject(selector, mDefaultTimeout);
    }

    /**
     * Waits for and returns an object.
     *
     * @param parent where to find the object (or {@code null} to use device's root).
     * @param selector {@link BySelector} that identifies the object.
     * @param timeout timeout in ms.
     * @param dumpOnError whether the window hierarchy should be dumped if the object is not found.
     */
    private UiObject2 waitForObject(UiObject2 parent, BySelector selector, Timeout timeout,
            boolean dumpOnError) throws Exception {
        // NOTE: mDevice.wait does not work for the save snackbar, so we need a polling approach.
        try {
            return timeout.run("waitForObject(" + selector + ")", () -> {
                return parent != null
                        ? parent.findObject(selector)
                        : mDevice.findObject(selector);

            });
        } catch (RetryableException e) {
            if (dumpOnError) {
                dumpScreen("waitForObject() for " + selector + "on "
                        + (parent == null ? "mDevice" : parent) + " failed");
            }
            throw e;
        }
    }

    public UiObject2 waitForObject(@Nullable UiObject2 parent, @NonNull BySelector selector,
            @NonNull Timeout timeout)
            throws Exception {
        return waitForObject(parent, selector, timeout, DUMP_ON_ERROR);
    }

    /**
     * Waits for and returns an object.
     *
     * @param selector {@link BySelector} that identifies the object.
     * @param timeout timeout in ms
     */
    protected UiObject2 waitForObject(@NonNull BySelector selector, @NonNull Timeout timeout)
            throws Exception {
        return waitForObject(/* parent= */ null, selector, timeout);
    }

    /**
     * Waits for and returns a child from a parent {@link UiObject2}.
     */
    public UiObject2 assertChildText(UiObject2 parent, String resourceId, String expectedText)
            throws Exception {
        final UiObject2 child = waitForObject(parent, By.res(mPackageName, resourceId),
                Timeouts.UI_TIMEOUT);
        assertWithMessage("wrong text for view '%s'", resourceId).that(child.getText())
                .isEqualTo(expectedText);
        return child;
    }

    /**
     * Execute a Runnable and wait for {@link AccessibilityEvent#TYPE_WINDOWS_CHANGED} or
     * {@link AccessibilityEvent#TYPE_WINDOW_STATE_CHANGED}.
     */
    public AccessibilityEvent waitForWindowChange(Runnable runnable, long timeoutMillis) {
        try {
            return mAutoman.executeAndWaitForEvent(runnable, (AccessibilityEvent event) -> {
                switch (event.getEventType()) {
                    case AccessibilityEvent.TYPE_WINDOWS_CHANGED:
                    case AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED:
                        return true;
                    default:
                        Log.v(TAG, "waitForWindowChange(): ignoring event " + event);
                }
                return false;
            }, timeoutMillis);
        } catch (TimeoutException e) {
            throw new WindowChangeTimeoutException(e, timeoutMillis);
        }
    }

    public AccessibilityEvent waitForWindowChange(Runnable runnable) {
        return waitForWindowChange(runnable, Timeouts.WINDOW_CHANGE_TIMEOUT_MS);
    }

    /**
     * Waits for and returns a list of objects.
     *
     * @param selector {@link BySelector} that identifies the object.
     * @param timeout timeout in ms
     */
    private List<UiObject2> waitForObjects(BySelector selector, Timeout timeout) throws Exception {
        // NOTE: mDevice.wait does not work for the save snackbar, so we need a polling approach.
        try {
            return timeout.run("waitForObject(" + selector + ")", () -> {
                final List<UiObject2> uiObjects = mDevice.findObjects(selector);
                if (uiObjects != null && !uiObjects.isEmpty()) {
                    return uiObjects;
                }
                return null;

            });

        } catch (RetryableException e) {
            dumpScreen("waitForObjects() for " + selector + "failed");
            throw e;
        }
    }

    private UiObject2 findDatasetPicker(Timeout timeout) throws Exception {
        // The UI element here is flaky. Sometimes the UI automator returns a StateObject.
        // Retry is put in place here to make sure that we catch the object.
        UiObject2 picker = null;
        int retryCount = 0;
        final String expectedTitle = getString(RESOURCE_STRING_DATASET_PICKER_ACCESSIBILITY_TITLE);
        while (retryCount < MAX_UIOBJECT_RETRY_COUNT) {
            try {
                picker = waitForObject(DATASET_PICKER_SELECTOR, timeout);
                assertAccessibilityTitle(picker, expectedTitle);
                break;
            } catch (StaleObjectException e) {
                Log.d(TAG, "Retry grabbing view class");
            }
            retryCount++;
        }
        assertWithMessage(expectedTitle + " not found").that(retryCount).isLessThan(
                MAX_UIOBJECT_RETRY_COUNT);

        if (picker != null) {
            mOkToCallAssertNoDatasets = true;
        }

        return picker;
    }

    /**
     * Asserts a given object has the expected accessibility title.
     */
    private void assertAccessibilityTitle(UiObject2 object, String expectedTitle) {
        // TODO: ideally it should get the AccessibilityWindowInfo from the object, but UiAutomator
        // does not expose that.
        for (AccessibilityWindowInfo window : mAutoman.getWindows()) {
            final CharSequence title = window.getTitle();
            Log.d(TAG, "assertAccessibilityTitle(): found title =" + title + ", expected title="
                    + expectedTitle);
            if (title != null && title.toString().equals(expectedTitle)) {
                return;
            }
        }
        throw new RetryableException("Title '%s' not found for %s", expectedTitle, object);
    }

    /**
     * Sets the screen orientation.
     *
     * @param orientation typically {@link #LANDSCAPE} or {@link #PORTRAIT}.
     *
     * @throws RetryableException if value didn't change.
     */
    public void setScreenOrientation(int orientation) throws Exception {
        // Use the platform API instead of mDevice.getDisplayRotation(), which is slow due to
        // waitForIdle(). waitForIdle() is not needed here because in AutoFillServiceTestCase we
        // always use UiBot#setScreenOrientation() to change the screen rotation, which blocks until
        // new rotation is reflected on the device.
        final int currentRotation = InstrumentationRegistry.getInstrumentation().getContext()
                .getSystemService(DisplayManager.class).getDisplay(Display.DEFAULT_DISPLAY)
                .getRotation();
        mAutoman.setRotation(orientation);

        if (orientation == currentRotation) {
            // Just need to freeze the rotation.
            return;
        }

        UI_SCREEN_ORIENTATION_TIMEOUT.run("setScreenOrientation(" + orientation + ")", () ->
                mDevice.getDisplayRotation() == orientation ? Boolean.TRUE : null);
    }

    /**
     * Gets the value of the screen orientation.
     *
     * @return typically {@link #LANDSCAPE} or {@link #PORTRAIT}.
     */
    public int getScreenOrientation() {
        return mDevice.getDisplayRotation();
    }

    /**
     * Dumps the current view hierarchy and take a screenshot and save both locally so they can be
     * inspected later.
     */
    public void dumpScreen(@NonNull String cause) {
        try {
            final File file = Helper.createTestFile("hierarchy.xml");
            if (file == null) return;
            Log.w(TAG, "Dumping window hierarchy because " + cause + " on " + file);
            try (FileInputStream fis = new FileInputStream(file)) {
                mDevice.dumpWindowHierarchy(file);
            }
        } catch (Exception e) {
            Log.e(TAG, "error dumping screen on " + cause, e);
        } finally {
            takeScreenshotAndSave();
        }
    }

    private Rect cropScreenshotWithoutScreenDecoration(Activity activity) {
        final WindowInsets[] inset = new WindowInsets[1];
        final View[] rootView = new View[1];

        InstrumentationRegistry.getInstrumentation().runOnMainSync(() -> {
            rootView[0] = activity.getWindow().getDecorView();
            inset[0] = rootView[0].getRootWindowInsets();
        });
        final int navBarHeight = inset[0].getStableInsetBottom();
        final int statusBarHeight = inset[0].getStableInsetTop();

        return new Rect(0, statusBarHeight, rootView[0].getWidth(),
                rootView[0].getHeight() - navBarHeight - statusBarHeight);
    }

    // TODO(b/74358143): ideally we should take a screenshot limited by the boundaries of the
    // activity window, so external elements (such as the clock) are filtered out and don't cause
    // test flakiness when the contents are compared.
    public Bitmap takeScreenshot() {
        return takeScreenshotWithRect(null);
    }

    public Bitmap takeScreenshot(@NonNull Activity activity) {
        // crop the screenshot without screen decoration to prevent test flakiness.
        final Rect rect = cropScreenshotWithoutScreenDecoration(activity);
        return takeScreenshotWithRect(rect);
    }

    private Bitmap takeScreenshotWithRect(@Nullable Rect r) {
        final long before = SystemClock.elapsedRealtime();
        final Bitmap bitmap = mAutoman.takeScreenshot();
        final long delta = SystemClock.elapsedRealtime() - before;
        Log.v(TAG, "Screenshot taken in " + delta + "ms");
        if (r == null) {
            return bitmap;
        }
        try {
            return Bitmap.createBitmap(bitmap, r.left, r.top, r.right, r.bottom);
        } finally {
            if (bitmap != null) {
                bitmap.recycle();
            }
        }
    }

    /**
     * Takes a screenshot and save it in the file system for post-mortem analysis.
     */
    public void takeScreenshotAndSave() {
        File file = null;
        try {
            file = Helper.createTestFile("screenshot.png");
            if (file != null) {
                Log.i(TAG, "Taking screenshot on " + file);
                final Bitmap screenshot = takeScreenshot();
                Helper.dumpBitmap(screenshot, file);
            }
        } catch (Exception e) {
            Log.e(TAG, "Error taking screenshot and saving on " + file, e);
        }
    }

    /**
     * Asserts the contents of a child element.
     *
     * @param parent parent object
     * @param childId (relative) resource id of the child
     * @param assertion if {@code null}, asserts the child does not exist; otherwise, asserts the
     * child with it.
     */
    public void assertChild(@NonNull UiObject2 parent, @NonNull String childId,
            @Nullable Visitor<UiObject2> assertion) {
        final UiObject2 child = parent.findObject(By.res(mPackageName, childId));
        try {
            if (assertion != null) {
                assertWithMessage("Didn't find child with id '%s'", childId).that(child)
                        .isNotNull();
                try {
                    assertion.visit(child);
                } catch (Throwable t) {
                    throw new AssertionError("Error on child '" + childId + "'", t);
                }
            } else {
                assertWithMessage("Shouldn't find child with id '%s'", childId).that(child)
                        .isNull();
            }
        } catch (RuntimeException | Error e) {
            dumpScreen("assertChild(" + childId + ") failed: " + e);
            throw e;
        }
    }

    /**
     * Finds the first {@link URLSpan} on the current screen.
     */
    public URLSpan findFirstUrlSpanWithText(String str) throws Exception {
        final List<AccessibilityNodeInfo> list = mAutoman.getRootInActiveWindow()
                .findAccessibilityNodeInfosByText(str);
        if (list.isEmpty()) {
            throw new AssertionError("Didn't found AccessibilityNodeInfo with " + str);
        }

        final AccessibilityNodeInfo text = list.get(0);
        final CharSequence accessibilityTextWithSpan = text.getText();
        if (!(accessibilityTextWithSpan instanceof Spanned)) {
            throw new AssertionError("\"" + text.getViewIdResourceName() + "\" was not a Spanned");
        }

        final URLSpan[] spans = ((Spanned) accessibilityTextWithSpan)
                .getSpans(0, accessibilityTextWithSpan.length(), URLSpan.class);
        return spans[0];
    }

    public boolean scrollToTextObject(String text) {
        UiScrollable scroller = new UiScrollable(new UiSelector().scrollable(true));
        try {
            // Swipe far away from the edges to avoid triggering navigation gestures
            scroller.setSwipeDeadZonePercentage(0.25);
            return scroller.scrollTextIntoView(text);
        } catch (UiObjectNotFoundException e) {
            return false;
        }
    }

    /**
     * Asserts the header in the fill dialog.
     */
    public void assertFillDialogHeader(String expectedHeader) throws Exception {
        final UiObject2 header = findFillDialogHeaderPicker();

        assertWithMessage("wrong header for fill dialog")
                .that(getChildrenAsText(header))
                .containsExactlyElementsIn(Arrays.asList(expectedHeader)).inOrder();
    }

    /**
     * Asserts reject button in the fill dialog.
     */
    public void assertFillDialogRejectButton() throws Exception {
        final UiObject2 picker = findFillDialogPicker();

        // "No thanks" button shown
        final UiObject2 rejectButton = picker.findObject(
                By.res("android", RESOURCE_ID_FILL_DIALOG_BUTTON_NO));
        assertWithMessage("No reject button in fill dialog")
                .that(rejectButton).isNotNull();
        assertWithMessage("wrong text on reject button")
                .that(rejectButton.getText().toUpperCase()).isEqualTo(
                        getString(RESOURCE_STRING_SAVE_BUTTON_NO_THANKS).toUpperCase());
    }

    /**
     * Asserts accept button in the fill dialog.
     */
    public void assertFillDialogAcceptButton() throws Exception {
        final UiObject2 picker = findFillDialogPicker();

        // "Continue" button shown
        final UiObject2 acceptButton = picker.findObject(
                By.res("android", RESOURCE_ID_FILL_DIALOG_BUTTON_YES));
        assertWithMessage("No accept button in fill dialog")
                .that(acceptButton).isNotNull();
        assertWithMessage("wrong text on accept button")
                .that(acceptButton.getText().toUpperCase()).isEqualTo(
                        getString(RESOURCE_STRING_CONTINUE_BUTTON_YES).toUpperCase());
    }

    /**
     * Asserts there is no accept button in the fill dialog.
     */
    public void assertFillDialogNoAcceptButton() throws Exception {
        final UiObject2 picker = findFillDialogPicker();

        // "Continue" button not shown
        final UiObject2 acceptButton = picker.findObject(
                By.res("android", RESOURCE_ID_FILL_DIALOG_BUTTON_YES));
        assertWithMessage("wrong accept button in fill dialog")
                .that(acceptButton).isNull();
    }

    /**
     * Asserts the fill dialog is shown and contains the given datasets.
     *
     * @return the dataset picker object.
     */
    public UiObject2 assertFillDialogDatasets(String... datasets) throws Exception {
        final UiObject2 picker = findFillDialogDatasetPicker();

        assertWithMessage("wrong elements in fill dialog")
                .that(getChildrenAsText(picker))
                .containsExactlyElementsIn(datasets).inOrder();
        return picker;
    }

    /**
     * Asserts the fill dialog is shown and contains the given dataset. And then select the dataset
     */
    public void selectFillDialogDataset(String dataset) throws Exception {
        final UiObject2 picker = assertFillDialogDatasets(dataset);
        selectDataset(picker, dataset);
    }

    /**
     * Touch outside the fill dialog.
     */
    public void touchOutsideDialog() throws Exception {
        Log.v(TAG, "touchOutsideDialog()");
        final UiObject2 picker = findFillDialogPicker();
        assertThat(injectClick(new Point(1, picker.getVisibleBounds().top / 2))).isTrue();
    }

    /**
     * Touch outside the fill dialog.
     */
    public void touchOutsideSaveDialog() throws Exception {
        Log.v(TAG, "touchOutsideSaveDialog()");
        final UiObject2 picker = waitForObject(SAVE_UI_SELECTOR, SAVE_TIMEOUT);
        Log.v(TAG, "got picker: " + picker);
        assertThat(injectClick(new Point(1, picker.getVisibleBounds().top / 2))).isTrue();
    }

    /**
     * click dismiss button the fill dialog.
     */
    public void clickFillDialogDismiss() throws Exception {
        Log.v(TAG, "dismissedFillDialog()");
        final UiObject2 picker = findFillDialogPicker();
        final UiObject2 noButton =
                picker.findObject(By.res("android", RESOURCE_ID_FILL_DIALOG_BUTTON_NO));
        noButton.click();
    }

    private UiObject2 findFillDialogPicker() throws Exception {
        return waitForObject(FILL_DIALOG_SELECTOR, UI_DATASET_PICKER_TIMEOUT);
    }

    public UiObject2 findFillDialogDatasetPicker() throws Exception {
        return waitForObject(FILL_DIALOG_DATASET_SELECTOR, UI_DATASET_PICKER_TIMEOUT);
    }

    public UiObject2 findFillDialogHeaderPicker() throws Exception {
        return waitForObject(FILL_DIALOG_HEADER_SELECTOR, UI_DATASET_PICKER_TIMEOUT);
    }

    /**
     * Asserts the fill dialog is not shown.
     */
    public void assertNoFillDialog() throws Exception {
        assertNeverShown("Fill dialog", FILL_DIALOG_SELECTOR, DATASET_PICKER_NOT_SHOWN_NAPTIME_MS);
    }

    /**
     * Injects a click input event at the given point in the default display.
     * We have this method because {@link UiObject2#click) cannot touch outside the object, and
     * {@link UiDevice#click} is broken in multi windowing mode (b/238254060).
     */
    private boolean injectClick(Point p) {
        final long downTime = SystemClock.uptimeMillis();
        final MotionEvent downEvent = getMotionEvent(downTime, downTime, MotionEvent.ACTION_DOWN,
                p);
        if (!mAutoman.injectInputEvent(downEvent, true)) {
            Log.e(TAG, "Failed to inject down event.");
            return false;
        }

        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            Log.e(TAG, "Interrupted while sleep between click", e);
        }

        final MotionEvent upEvent = getMotionEvent(downTime, SystemClock.uptimeMillis(),
                MotionEvent.ACTION_UP, p);
        return mAutoman.injectInputEvent(upEvent, true);
    }

    private MotionEvent getMotionEvent(long downTime, long eventTime, int action, Point p) {
        final MotionEvent.PointerProperties properties = new MotionEvent.PointerProperties();
        properties.id = 0;
        properties.toolType = Configurator.getInstance().getToolType();
        final MotionEvent.PointerCoords coords = new MotionEvent.PointerCoords();
        coords.pressure = 1.0F;
        coords.size = 1.0F;
        coords.x = p.x;
        coords.y = p.y;
        MotionEvent event = MotionEvent.obtain(downTime, eventTime, action, 1,
                new MotionEvent.PointerProperties[]{properties},
                new MotionEvent.PointerCoords[]{coords}, 0, 0, 1.0F, 1.0F, 0, 0,
                InputDevice.SOURCE_TOUCHSCREEN, 0);
        mUserHelper.injectDisplayIdIfNeeded(event);
        return event;
    }
}