summaryrefslogtreecommitdiff
path: root/apps/CtsVerifier/src/com/android/cts/verifier/PassFailButtons.java
blob: 7b993eefc5889a58dc6e9e2724d525d471aecc27 (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
/*
 * Copyright (C) 2010 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 com.android.cts.verifier;

import static com.android.cts.verifier.TestListActivity.sCurrentDisplayMode;
import static com.android.cts.verifier.TestListAdapter.setTestNameSuffix;

import android.app.ActionBar;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.os.Bundle;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.Toast;

import com.android.compatibility.common.util.ReportLog;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * {@link Activity}s to handle clicks to the pass and fail buttons of the pass fail buttons layout.
 *
 * <ol>
 *     <li>Include the pass fail buttons layout in your layout:
 *         <pre><include layout="@layout/pass_fail_buttons" /></pre>
 *     </li>
 *     <li>Extend one of the activities and call setPassFailButtonClickListeners after
 *         setting your content view.</li>
 *     <li>Make sure to call setResult(RESULT_CANCEL) in your Activity initially.</li>
 *     <li>Optionally call setInfoTextResources to add an info button that will show a
 *         dialog with instructional text.</li>
 * </ol>
 */
public class PassFailButtons {
    private static final String TAG = PassFailButtons.class.getSimpleName();

    private static final int INFO_DIALOG_ID = 1337;

    private static final String INFO_DIALOG_VIEW_ID = "infoDialogViewId";
    private static final String INFO_DIALOG_TITLE_ID = "infoDialogTitleId";
    private static final String INFO_DIALOG_MESSAGE_ID = "infoDialogMessageId";

    // ReportLog file for CTS-Verifier. The "stream" name gets mapped to the test class name.
    public static final String GENERAL_TESTS_REPORT_LOG_NAME = "CtsVerifierGeneralTestCases";
    public static final String AUDIO_TESTS_REPORT_LOG_NAME = "CtsVerifierAudioTestCases";

    private static final String SECTION_UNDEFINED = "undefined_section_name";

    // Interface mostly for making documentation and refactoring easier...
    public interface PassFailActivity {

        /**
         * Hooks up the pass and fail buttons to click listeners that will record the test results.
         * <p>
         * Call from {@link Activity#onCreate} after {@link Activity #setContentView(int)}.
         */
        void setPassFailButtonClickListeners();

        /**
         * Adds an initial informational dialog that appears when entering the test activity for
         * the first time. Also enables the visibility of an "Info" button between the "Pass" and
         * "Fail" buttons that can be clicked to show the information dialog again.
         * <p>
         * Call from {@link Activity#onCreate} after {@link Activity #setContentView(int)}.
         *
         * @param titleId for the text shown in the dialog title area
         * @param messageId for the text shown in the dialog's body area
         */
        void setInfoResources(int titleId, int messageId, int viewId);

        View getPassButton();

        /**
         * Returns a unique identifier for the test.  Usually, this is just the class name.
         */
        String getTestId();

        /** @return null or details about the test run. */
        String getTestDetails();

        /**
         * Set the result of the test and finish the activity.
         *
         * @param passed Whether or not the test passed.
         */
        void setTestResultAndFinish(boolean passed);

        /**
         * @return The name of the file to store the (suite of) ReportLog information.
         */
        public String getReportFileName();

        /**
         * @return A unique name to serve as a section header in the CtsVerifierReportLog file.
         * Tests need to conform to the underscore_delineated_name standard for use with
         * the protobuff/json ReportLog parsing in Google3
         */
        public String getReportSectionName();

        /**
         * Test subclasses can override this to record their CtsVerifierReportLogs.
         * This is called when the test is exited
         */
        void recordTestResults();

        /** @return A {@link ReportLog} that is used to record test metric data. */
        CtsVerifierReportLog getReportLog();

        /**
         * @return A {@link TestResultHistoryCollection} that is used to record test execution time.
         */
        TestResultHistoryCollection getHistoryCollection();
    }   /* class PassFailButtons.PassFailActivity */

    public static class Activity extends android.app.Activity implements PassFailActivity {
        private WakeLock mWakeLock;
        private final CtsVerifierReportLog mReportLog;
        private final TestResultHistoryCollection mHistoryCollection;

        protected boolean mRequireReportLogToPass;

        public Activity() {
            this.mReportLog = new CtsVerifierReportLog(getReportFileName(), getReportSectionName());
            this.mHistoryCollection = new TestResultHistoryCollection();
        }

        @Override
        protected void onResume() {
            super.onResume();
            if (getPackageManager().hasSystemFeature(PackageManager.FEATURE_WATCH)) {
                mWakeLock = ((PowerManager) getSystemService(Context.POWER_SERVICE))
                        .newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "PassFailButtons");
                mWakeLock.acquire();
            }

            if (!this.mReportLog.isOpen()) {
                showReportLogWarningDialog(this);
            }
        }

        @Override
        protected void onPause() {
            super.onPause();
            if (getPackageManager().hasSystemFeature(PackageManager.FEATURE_WATCH)) {
                mWakeLock.release();
            }
        }

        @Override
        public void setPassFailButtonClickListeners() {
            setPassFailClickListeners(this);
        }

        @Override
        public void setInfoResources(int titleId, int messageId, int viewId) {
            setInfo(this, titleId, messageId, viewId);
        }

        @Override
        public View getPassButton() {
            return getPassButtonView(this);
        }

        @Override
        public Dialog onCreateDialog(int id, Bundle args) {
            return createDialog(this, id, args);
        }

        @Override
        public String getTestId() {
            return setTestNameSuffix(sCurrentDisplayMode, getClass().getName());
        }

        @Override
        public String getTestDetails() {
            return null;
        }

        @Override
        public void setTestResultAndFinish(boolean passed) {
            PassFailButtons.setTestResultAndFinishHelper(
                    this, getTestId(), getTestDetails(), passed, getReportLog(),
                    getHistoryCollection());
        }

        @Override
        public CtsVerifierReportLog getReportLog() {
            return mReportLog;
        }

        /**
         * A mechanism to block tests from passing if no ReportLog data has been collected.
         * @return true if the ReportLog is open OR if the test does not require that.
         */
        public boolean isReportLogOkToPass() {
            return !mRequireReportLogToPass || mReportLog.isOpen();
        }

        /**
         * @return The name of the file to store the (suite of) ReportLog information.
         */
        @Override
        public String getReportFileName() { return GENERAL_TESTS_REPORT_LOG_NAME; }

        @Override
        public String getReportSectionName() {
            return setTestNameSuffix(sCurrentDisplayMode, SECTION_UNDEFINED);
        }

        @Override
        public TestResultHistoryCollection getHistoryCollection() { return mHistoryCollection; }

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            ActionBar actBar = getActionBar();
            if (actBar != null) {
                actBar.setDisplayHomeAsUpEnabled(true);
            }
        }

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            if (item.getItemId() == android.R.id.home) {
                onBackPressed();
                return true;
            }
            return super.onOptionsItemSelected(item);
        }

        @Override
        public void recordTestResults() {
            // default - NOP
        }
    }   /* class PassFailButtons.Activity */

    public static class ListActivity extends android.app.ListActivity implements PassFailActivity {

        private final CtsVerifierReportLog mReportLog;
        private final TestResultHistoryCollection mHistoryCollection;

        public ListActivity() {
            this.mReportLog = new CtsVerifierReportLog(getReportFileName(), getReportSectionName());
            this.mHistoryCollection = new TestResultHistoryCollection();
        }

        @Override
        public void setPassFailButtonClickListeners() {
            setPassFailClickListeners(this);
        }

        @Override
        public void setInfoResources(int titleId, int messageId, int viewId) {
            setInfo(this, titleId, messageId, viewId);
        }

        @Override
        public View getPassButton() {
            return getPassButtonView(this);
        }

        @Override
        public Dialog onCreateDialog(int id, Bundle args) {
            return createDialog(this, id, args);
        }

        @Override
        public String getTestId() {
            return setTestNameSuffix(sCurrentDisplayMode, getClass().getName());
        }

        @Override
        public String getTestDetails() {
            return null;
        }

        @Override
        public void setTestResultAndFinish(boolean passed) {
            PassFailButtons.setTestResultAndFinishHelper(
                    this, getTestId(), getTestDetails(), passed, getReportLog(),
                    getHistoryCollection());
        }

        @Override
        public CtsVerifierReportLog getReportLog() {
            return mReportLog;
        }

        /**
         * @return The name of the file to store the (suite of) ReportLog information.
         */
        @Override
        public String getReportFileName() { return GENERAL_TESTS_REPORT_LOG_NAME; }

        @Override
        public String getReportSectionName() {
            return setTestNameSuffix(sCurrentDisplayMode, SECTION_UNDEFINED);
        }

        @Override
        public TestResultHistoryCollection getHistoryCollection() { return mHistoryCollection; }

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            ActionBar actBar = getActionBar();
            if (actBar != null) {
                actBar.setDisplayHomeAsUpEnabled(true);
            }
        }

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            if (item.getItemId() == android.R.id.home) {
                onBackPressed();
                return true;
            }
            return super.onOptionsItemSelected(item);
        }

        @Override
        public void recordTestResults() {
            // default - NOP
        }
    } // class PassFailButtons.ListActivity

    public static class TestListActivity extends AbstractTestListActivity
            implements PassFailActivity {

        private final CtsVerifierReportLog mReportLog;

        public TestListActivity() {
            // TODO(b/186555602): temporary hack^H^H^H^H workaround to fix crash
            // This DOES NOT in fact fix that bug.
            // if (true) this.mReportLog = new CtsVerifierReportLog(b/186555602, "42"); else

            this.mReportLog = new CtsVerifierReportLog(getReportFileName(), getReportSectionName());
        }

        @Override
        public void setPassFailButtonClickListeners() {
            setPassFailClickListeners(this);
        }

        @Override
        public void setInfoResources(int titleId, int messageId, int viewId) {
            setInfo(this, titleId, messageId, viewId);
        }

        @Override
        public View getPassButton() {
            return getPassButtonView(this);
        }

        @Override
        public Dialog onCreateDialog(int id, Bundle args) {
            return createDialog(this, id, args);
        }

        @Override
        public String getTestId() {
            return setTestNameSuffix(sCurrentDisplayMode, getClass().getName());
        }

        @Override
        public String getTestDetails() {
            return null;
        }

        @Override
        public void setTestResultAndFinish(boolean passed) {
            PassFailButtons.setTestResultAndFinishHelper(
                    this, getTestId(), getTestDetails(), passed, getReportLog(),
                    getHistoryCollection());
        }

        @Override
        public CtsVerifierReportLog getReportLog() {
            return mReportLog;
        }

        /**
         * @return The name of the file to store the (suite of) ReportLog information.
         */
        @Override
        public String getReportFileName() { return GENERAL_TESTS_REPORT_LOG_NAME; }

        @Override
        public String getReportSectionName() {
            return setTestNameSuffix(sCurrentDisplayMode, SECTION_UNDEFINED);
        }


        /**
         * Get existing test history to aggregate.
         */
        @Override
        public TestResultHistoryCollection getHistoryCollection() {
            List<TestResultHistoryCollection> histories =
                IntStream.range(0, mAdapter.getCount())
                .mapToObj(mAdapter::getHistoryCollection)
                .collect(Collectors.toList());
            TestResultHistoryCollection historyCollection = new TestResultHistoryCollection();
            historyCollection.merge(getTestId(), histories);
            return historyCollection;
        }

        public void updatePassButton() {
            getPassButton().setEnabled(mAdapter.allTestsPassed());
        }

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            ActionBar actBar = getActionBar();
            if (actBar != null) {
                actBar.setDisplayHomeAsUpEnabled(true);
            }
        }

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            if (item.getItemId() == android.R.id.home) {
                onBackPressed();
                return true;
            }
            return super.onOptionsItemSelected(item);
        }

        @Override
        public void recordTestResults() {
            // default - NOP
        }
    } // class PassFailButtons.TestListActivity

    protected static <T extends android.app.Activity & PassFailActivity>
            void setPassFailClickListeners(final T activity) {
        View.OnClickListener clickListener = new View.OnClickListener() {
            @Override
            public void onClick(View target) {
                setTestResultAndFinish(activity, activity.getTestId(), activity.getTestDetails(),
                        activity.getReportLog(), activity.getHistoryCollection(), target);
            }
        };

        View passButton = activity.findViewById(R.id.pass_button);
        passButton.setOnClickListener(clickListener);
        passButton.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                Toast.makeText(activity, R.string.pass_button_text, Toast.LENGTH_SHORT).show();
                return true;
            }
        });

        View failButton = activity.findViewById(R.id.fail_button);
        failButton.setOnClickListener(clickListener);
        failButton.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                Toast.makeText(activity, R.string.fail_button_text, Toast.LENGTH_SHORT).show();
                return true;
            }
        });
    } // class PassFailButtons.<T extends android.app.Activity & PassFailActivity>

    protected static void setInfo(final android.app.Activity activity, final int titleId,
            final int messageId, final int viewId) {
        // Show the middle "info" button and make it show the info dialog when clicked.
        View infoButton = activity.findViewById(R.id.info_button);
        infoButton.setVisibility(View.VISIBLE);
        infoButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                showInfoDialog(activity, titleId, messageId, viewId);
            }
        });
        infoButton.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                Toast.makeText(activity, R.string.info_button_text, Toast.LENGTH_SHORT).show();
                return true;
            }
        });

        // Show the info dialog if the user has never seen it before.
        if (!hasSeenInfoDialog(activity)) {
            showInfoDialog(activity, titleId, messageId, viewId);
        }
    }

    protected static boolean hasSeenInfoDialog(android.app.Activity activity) {
        ContentResolver resolver = activity.getContentResolver();
        Cursor cursor = null;
        try {
            cursor = resolver.query(TestResultsProvider.getTestNameUri(activity),
                    new String[] {TestResultsProvider.COLUMN_TEST_INFO_SEEN}, null, null, null);
            return cursor.moveToFirst() && cursor.getInt(0) > 0;
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
    }

    protected static void showInfoDialog(final android.app.Activity activity, int titleId,
            int messageId, int viewId) {
        Bundle args = new Bundle();
        args.putInt(INFO_DIALOG_TITLE_ID, titleId);
        args.putInt(INFO_DIALOG_MESSAGE_ID, messageId);
        args.putInt(INFO_DIALOG_VIEW_ID, viewId);
        activity.showDialog(INFO_DIALOG_ID, args);
    }

    protected static void showReportLogWarningDialog(final android.app.Activity activity) {
        showInfoDialog(activity,
                R.string.reportlog_warning_title, R.string.reportlog_warning_body, -1);
    }


    protected static Dialog createDialog(final android.app.Activity activity, int id, Bundle args) {
        switch (id) {
            case INFO_DIALOG_ID:
                return createInfoDialog(activity, id, args);
            default:
                throw new IllegalArgumentException("Bad dialog id: " + id);
        }
    }

    protected static Dialog createInfoDialog(final android.app.Activity activity, int id,
            Bundle args) {
        int viewId = args.getInt(INFO_DIALOG_VIEW_ID);
        int titleId = args.getInt(INFO_DIALOG_TITLE_ID);
        int messageId = args.getInt(INFO_DIALOG_MESSAGE_ID);

        AlertDialog.Builder builder = new AlertDialog.Builder(activity).setIcon(
                android.R.drawable.ic_dialog_info).setTitle(titleId);
        if (viewId > 0) {
            LayoutInflater inflater = (LayoutInflater) activity
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            builder.setView(inflater.inflate(viewId, null));
        } else {
            builder.setMessage(messageId);
        }
        builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                markSeenInfoDialog(activity);
            }
        }).setOnCancelListener(new OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                markSeenInfoDialog(activity);
            }
        });
        return builder.create();
    }

    protected static void markSeenInfoDialog(android.app.Activity activity) {
        ContentResolver resolver = activity.getContentResolver();
        ContentValues values = new ContentValues(2);
        String activityName = setTestNameSuffix(sCurrentDisplayMode, activity.getClass().getName());
        values.put(TestResultsProvider.COLUMN_TEST_NAME, activityName);
        values.put(TestResultsProvider.COLUMN_TEST_INFO_SEEN, 1);
        int numUpdated = resolver.update(
                TestResultsProvider.getTestNameUri(activity), values, null, null);
        if (numUpdated == 0) {
            resolver.insert(TestResultsProvider.getResultContentUri(activity), values);
        }
    }

    /** Set the test result corresponding to the button clicked and finish the activity. */
    protected static void setTestResultAndFinish(android.app.Activity activity, String testId,
            String testDetails, ReportLog reportLog, TestResultHistoryCollection historyCollection,
            View target) {

        boolean passed;
        if (target.getId() == R.id.pass_button) {
            passed = true;
        } else if (target.getId() == R.id.fail_button) {
            passed = false;
        } else {
            throw new IllegalArgumentException("Unknown id: " + target.getId());
        }

        // Let test classes record their CTSVerifierReportLogs
        ((PassFailActivity) activity).recordTestResults();

        setTestResultAndFinishHelper(activity, testId, testDetails, passed, reportLog, historyCollection);
    }

    /** Set the test result and finish the activity. */
    protected static void setTestResultAndFinishHelper(android.app.Activity activity, String testId,
            String testDetails, boolean passed, ReportLog reportLog,
            TestResultHistoryCollection historyCollection) {
        if (passed) {
            TestResult.setPassedResult(activity, testId, testDetails, reportLog, historyCollection);
        } else {
            TestResult.setFailedResult(activity, testId, testDetails, reportLog, historyCollection);
        }

        activity.finish();
    }

    protected static ImageButton getPassButtonView(android.app.Activity activity) {
        return (ImageButton) activity.findViewById(R.id.pass_button);
    }

} // class PassFailButtons