summaryrefslogtreecommitdiff
path: root/libs/deviceutillegacy/src/android/webkit/cts/WebViewOnUiThread.java
blob: d20e1a48ed3c3e9f829ae7597495c9e069ac4da2 (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
/*
 * Copyright (C) 2011 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.webkit.cts;

import com.android.compatibility.common.util.PollingCheck;
import com.android.compatibility.common.util.TestThread;

import android.graphics.Bitmap;
import android.graphics.Picture;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Bundle;
import android.os.Looper;
import android.os.Message;
import android.os.SystemClock;
import android.print.PrintDocumentAdapter;
import android.support.test.rule.ActivityTestRule;
import android.test.InstrumentationTestCase;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.webkit.DownloadListener;
import android.webkit.CookieManager;
import android.webkit.ValueCallback;
import android.webkit.WebBackForwardList;
import android.webkit.WebChromeClient;
import android.webkit.WebMessage;
import android.webkit.WebMessagePort;
import android.webkit.WebSettings;
import android.webkit.WebView.HitTestResult;
import android.webkit.WebView.PictureListener;
import android.webkit.WebView.VisualStateCallback;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import junit.framework.Assert;

import java.io.File;
import java.util.concurrent.Callable;
import java.util.Map;

/**
 * Many tests need to run WebView code in the UI thread. This class
 * wraps a WebView so that calls are ensured to arrive on the UI thread.
 *
 * All methods may be run on either the UI thread or test thread.
 */
public class WebViewOnUiThread {
    /**
     * The maximum time, in milliseconds (10 seconds) to wait for a load
     * to be triggered.
     */
    private static final long LOAD_TIMEOUT = 10000;

    /**
     * Set to true after onPageFinished is called.
     */
    private boolean mLoaded;

    /**
     * Set to true after onNewPicture is called. Reset when onPageStarted
     * is called.
     */
    private boolean mNewPicture;

    /**
     * The progress, in percentage, of the page load. Valid values are between
     * 0 and 100.
     */
    private int mProgress;

    /**
     * The test that this class is being used in. Used for runTestOnUiThread.
     */
    private InstrumentationTestCase mTest;

    /**
     * The test rule that this class is being used in. Used for runTestOnUiThread.
     */
    private ActivityTestRule mActivityTestRule;

    /**
     * The WebView that calls will be made on.
     */
    private WebView mWebView;

    /**
     * Initializes the webView with a WebViewClient, WebChromeClient,
     * and PictureListener to prepare for loadUrlAndWaitForCompletion.
     *
     * A new WebViewOnUiThread should be called during setUp so as to
     * reinitialize between calls.
     *
     * @param test The test in which this is being run.
     * @param webView The webView that the methods should call.
     * @see #loadDataAndWaitForCompletion(String, String, String)
     * @deprecated Use {@link WebViewOnUiThread#WebViewOnUiThread(ActivityTestRule, WebView)}
     */
    @Deprecated
    public WebViewOnUiThread(InstrumentationTestCase test, WebView webView) {
        mTest = test;
        mWebView = webView;
        final WebViewClient webViewClient = new WaitForLoadedClient(this);
        final WebChromeClient webChromeClient = new WaitForProgressClient(this);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mWebView.setWebViewClient(webViewClient);
                mWebView.setWebChromeClient(webChromeClient);
                mWebView.setPictureListener(new WaitForNewPicture());
            }
        });
    }

    /**
     * Initializes the webView with a WebViewClient, WebChromeClient,
     * and PictureListener to prepare for loadUrlAndWaitForCompletion.
     *
     * A new WebViewOnUiThread should be called during setUp so as to
     * reinitialize between calls.
     *
     * @param activityTestRule The test rule in which this is being run.
     * @param webView The webView that the methods should call.
     * @see #loadDataAndWaitForCompletion(String, String, String)
     */
    public WebViewOnUiThread(ActivityTestRule activityTestRule, WebView webView) {
        mActivityTestRule = activityTestRule;
        mWebView = webView;
        final WebViewClient webViewClient = new WaitForLoadedClient(this);
        final WebChromeClient webChromeClient = new WaitForProgressClient(this);
        runOnUiThread(() -> {
            mWebView.setWebViewClient(webViewClient);
            mWebView.setWebChromeClient(webChromeClient);
            mWebView.setPictureListener(new WaitForNewPicture());
        });
    }

    /**
     * Called after a test is complete and the WebView should be disengaged from
     * the tests.
     */
    public void cleanUp() {
        clearHistory();
        clearCache(true);
        setPictureListener(null);
        setWebChromeClient(null);
        setWebViewClient(null);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mWebView.destroy();
            }
        });
    }

    /**
     * Called from WaitForNewPicture, this is used to indicate that
     * the page has been drawn.
     */
    synchronized public void onNewPicture() {
        mNewPicture = true;
        this.notifyAll();
    }

    /**
     * Called from WaitForLoadedClient, this is used to clear the picture
     * draw state so that draws before the URL begins loading don't count.
     */
    synchronized public void onPageStarted() {
        mNewPicture = false; // Earlier paints won't count.
    }

    /**
     * Called from WaitForLoadedClient, this is used to indicate that
     * the page is loaded, but not drawn yet.
     */
    synchronized public void onPageFinished() {
        mLoaded = true;
        this.notifyAll();
    }

    /**
     * Called from the WebChrome client, this sets the current progress
     * for a page.
     * @param progress The progress made so far between 0 and 100.
     */
    synchronized public void onProgressChanged(int progress) {
        mProgress = progress;
        this.notifyAll();
    }

    public void setWebViewClient(final WebViewClient webViewClient) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mWebView.setWebViewClient(webViewClient);
            }
        });
    }

    public void setWebChromeClient(final WebChromeClient webChromeClient) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mWebView.setWebChromeClient(webChromeClient);
            }
        });
    }

    public void setPictureListener(final PictureListener pictureListener) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mWebView.setPictureListener(pictureListener);
            }
        });
    }

    public void setNetworkAvailable(final boolean available) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mWebView.setNetworkAvailable(available);
            }
        });
    }

    public void setDownloadListener(final DownloadListener listener) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mWebView.setDownloadListener(listener);
            }
        });
    }

    public void setBackgroundColor(final int color) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mWebView.setBackgroundColor(color);
            }
        });
    }

    public void clearCache(final boolean includeDiskFiles) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mWebView.clearCache(includeDiskFiles);
            }
        });
    }

    public void clearHistory() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mWebView.clearHistory();
            }
        });
    }

    public void requestFocus() {
        new PollingCheck(LOAD_TIMEOUT) {
            @Override
            protected boolean check() {
                requestFocusOnUiThread();
                return hasFocus();
            }
        }.run();
    }

    private void requestFocusOnUiThread() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mWebView.requestFocus();
            }
        });
    }

    private boolean hasFocus() {
        return getValue(new ValueGetter<Boolean>() {
            @Override
            public Boolean capture() {
                return mWebView.hasFocus();
            }
        });
    }

    public boolean canZoomIn() {
        return getValue(new ValueGetter<Boolean>() {
            @Override
            public Boolean capture() {
                return mWebView.canZoomIn();
            }
        });
    }

    public boolean canZoomOut() {
        return getValue(new ValueGetter<Boolean>() {
            @Override
            public Boolean capture() {
                return mWebView.canZoomOut();
            }
        });
    }

    public boolean zoomIn() {
        return getValue(new ValueGetter<Boolean>() {
            @Override
            public Boolean capture() {
                return mWebView.zoomIn();
            }
        });
    }

    public boolean zoomOut() {
        return getValue(new ValueGetter<Boolean>() {
            @Override
            public Boolean capture() {
                return mWebView.zoomOut();
            }
        });
    }

    public void zoomBy(final float zoomFactor) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mWebView.zoomBy(zoomFactor);
            }
        });
    }

    public void setFindListener(final WebView.FindListener listener) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mWebView.setFindListener(listener);
            }
        });
    }

    public void removeJavascriptInterface(final String interfaceName) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mWebView.removeJavascriptInterface(interfaceName);
            }
        });
    }

    public WebMessagePort[] createWebMessageChannel() {
        return getValue(new ValueGetter<WebMessagePort[]>() {
            @Override
            public WebMessagePort[] capture() {
                return mWebView.createWebMessageChannel();
            }
        });
    }

    public void postWebMessage(final WebMessage message, final Uri targetOrigin) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mWebView.postWebMessage(message, targetOrigin);
            }
        });
    }

    public void addJavascriptInterface(final Object object, final String name) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mWebView.addJavascriptInterface(object, name);
            }
        });
    }

    public void flingScroll(final int vx, final int vy) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mWebView.flingScroll(vx, vy);
            }
        });
    }

    public void requestFocusNodeHref(final Message hrefMsg) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mWebView.requestFocusNodeHref(hrefMsg);
            }
        });
    }

    public void requestImageRef(final Message msg) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mWebView.requestImageRef(msg);
            }
        });
    }

    public void setInitialScale(final int scaleInPercent) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mWebView.setInitialScale(scaleInPercent);
            }
        });
    }

    public void clearSslPreferences() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mWebView.clearSslPreferences();
            }
        });
    }

    public void clearClientCertPreferences(final Runnable onCleared) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                WebView.clearClientCertPreferences(onCleared);
            }
        });
    }

    public void resumeTimers() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mWebView.resumeTimers();
            }
        });
    }

    public void findNext(final boolean forward) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mWebView.findNext(forward);
            }
        });
    }

    public void clearMatches() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mWebView.clearMatches();
            }
        });
    }

    /**
     * Calls loadUrl on the WebView and then waits onPageFinished,
     * onNewPicture and onProgressChange to reach 100.
     * Test fails if the load timeout elapses.
     * @param url The URL to load.
     */
    public void loadUrlAndWaitForCompletion(final String url) {
        callAndWait(new Runnable() {
            @Override
            public void run() {
                mWebView.loadUrl(url);
            }
        });
    }

    /**
     * Calls loadUrl on the WebView and then waits onPageFinished,
     * onNewPicture and onProgressChange to reach 100.
     * Test fails if the load timeout elapses.
     * @param url The URL to load.
     * @param extraHeaders The additional headers to be used in the HTTP request.
     */
    public void loadUrlAndWaitForCompletion(final String url,
            final Map<String, String> extraHeaders) {
        callAndWait(new Runnable() {
            @Override
            public void run() {
                mWebView.loadUrl(url, extraHeaders);
            }
        });
    }

    public void loadUrl(final String url) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mWebView.loadUrl(url);
            }
        });
    }

    public void stopLoading() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mWebView.stopLoading();
            }
        });
    }

    public void postUrlAndWaitForCompletion(final String url, final byte[] postData) {
        callAndWait(new Runnable() {
            @Override
            public void run() {
                mWebView.postUrl(url, postData);
            }
        });
    }

    public void loadDataAndWaitForCompletion(final String data,
            final String mimeType, final String encoding) {
        callAndWait(new Runnable() {
            @Override
            public void run() {
                mWebView.loadData(data, mimeType, encoding);
            }
        });
    }

    public void loadDataWithBaseURLAndWaitForCompletion(final String baseUrl,
            final String data, final String mimeType, final String encoding,
            final String historyUrl) {
        callAndWait(new Runnable() {
            @Override
            public void run() {
                mWebView.loadDataWithBaseURL(baseUrl, data, mimeType, encoding,
                        historyUrl);
            }
        });
    }

    /**
     * Reloads a page and waits for it to complete reloading. Use reload
     * if it is a form resubmission and the onFormResubmission responds
     * by telling WebView not to resubmit it.
     */
    public void reloadAndWaitForCompletion() {
        callAndWait(new Runnable() {
            @Override
            public void run() {
                mWebView.reload();
            }
        });
    }

    /**
     * Reload the previous URL. Use reloadAndWaitForCompletion unless
     * it is a form resubmission and the onFormResubmission responds
     * by telling WebView not to resubmit it.
     */
    public void reload() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mWebView.reload();
            }
        });
    }

    /**
     * Use this only when JavaScript causes a page load to wait for the
     * page load to complete. Otherwise use loadUrlAndWaitForCompletion or
     * similar functions.
     */
    public void waitForLoadCompletion() {
        waitForCriteria(LOAD_TIMEOUT,
                new Callable<Boolean>() {
                    @Override
                    public Boolean call() {
                        return isLoaded();
                    }
                });
        clearLoad();
    }

    private void waitForCriteria(long timeout, Callable<Boolean> doneCriteria) {
        if (isUiThread()) {
            waitOnUiThread(timeout, doneCriteria);
        } else {
            waitOnTestThread(timeout, doneCriteria);
        }
    }

    public String getTitle() {
        return getValue(new ValueGetter<String>() {
            @Override
            public String capture() {
                return mWebView.getTitle();
            }
        });
    }

    public WebSettings getSettings() {
        return getValue(new ValueGetter<WebSettings>() {
            @Override
            public WebSettings capture() {
                return mWebView.getSettings();
            }
        });
    }

    public WebBackForwardList copyBackForwardList() {
        return getValue(new ValueGetter<WebBackForwardList>() {
            @Override
            public WebBackForwardList capture() {
                return mWebView.copyBackForwardList();
            }
        });
    }

    public Bitmap getFavicon() {
        return getValue(new ValueGetter<Bitmap>() {
            @Override
            public Bitmap capture() {
                return mWebView.getFavicon();
            }
        });
    }

    public String getUrl() {
        return getValue(new ValueGetter<String>() {
            @Override
            public String capture() {
                return mWebView.getUrl();
            }
        });
    }

    public int getProgress() {
        return getValue(new ValueGetter<Integer>() {
            @Override
            public Integer capture() {
                return mWebView.getProgress();
            }
        });
    }

    public int getHeight() {
        return getValue(new ValueGetter<Integer>() {
            @Override
            public Integer capture() {
                return mWebView.getHeight();
            }
        });
    }

    public int getContentHeight() {
        return getValue(new ValueGetter<Integer>() {
            @Override
            public Integer capture() {
                return mWebView.getContentHeight();
            }
        });
    }

    public boolean pageUp(final boolean top) {
        return getValue(new ValueGetter<Boolean>() {
            @Override
            public Boolean capture() {
                return mWebView.pageUp(top);
            }
        });
    }

    public boolean pageDown(final boolean bottom) {
        return getValue(new ValueGetter<Boolean>() {
            @Override
            public Boolean capture() {
                return mWebView.pageDown(bottom);
            }
        });
    }

    public void postVisualStateCallback(final long requestId, final VisualStateCallback callback) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mWebView.postVisualStateCallback(requestId, callback);
            }
        });
    }

    public int[] getLocationOnScreen() {
        final int[] location = new int[2];
        return getValue(new ValueGetter<int[]>() {
            @Override
            public int[] capture() {
                mWebView.getLocationOnScreen(location);
                return location;
            }
        });
    }

    public float getScale() {
        return getValue(new ValueGetter<Float>() {
            @Override
            public Float capture() {
                return mWebView.getScale();
            }
        });
    }

    public boolean requestFocus(final int direction,
            final Rect previouslyFocusedRect) {
        return getValue(new ValueGetter<Boolean>() {
            @Override
            public Boolean capture() {
                return mWebView.requestFocus(direction, previouslyFocusedRect);
            }
        });
    }

    public HitTestResult getHitTestResult() {
        return getValue(new ValueGetter<HitTestResult>() {
            @Override
            public HitTestResult capture() {
                return mWebView.getHitTestResult();
            }
        });
    }

    public int getScrollX() {
        return getValue(new ValueGetter<Integer>() {
            @Override
            public Integer capture() {
                return mWebView.getScrollX();
            }
        });
    }

    public int getScrollY() {
        return getValue(new ValueGetter<Integer>() {
            @Override
            public Integer capture() {
                return mWebView.getScrollY();
            }
        });
    }

    public final DisplayMetrics getDisplayMetrics() {
        return getValue(new ValueGetter<DisplayMetrics>() {
            @Override
            public DisplayMetrics capture() {
                return mWebView.getContext().getResources().getDisplayMetrics();
            }
        });
    }

    public boolean requestChildRectangleOnScreen(final View child,
            final Rect rect,
            final boolean immediate) {
        return getValue(new ValueGetter<Boolean>() {
            @Override
            public Boolean capture() {
                return mWebView.requestChildRectangleOnScreen(child, rect,
                        immediate);
            }
        });
    }

    public int findAll(final String find) {
        return getValue(new ValueGetter<Integer>() {
            @Override
            public Integer capture() {
                return mWebView.findAll(find);
            }
        });
    }

    public Picture capturePicture() {
        return getValue(new ValueGetter<Picture>() {
            @Override
            public Picture capture() {
                return mWebView.capturePicture();
            }
        });
    }

    public void evaluateJavascript(final String script, final ValueCallback<String> result) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mWebView.evaluateJavascript(script, result);
            }
        });
    }

    public void saveWebArchive(final String basename, final boolean autoname,
                               final ValueCallback<String> callback) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mWebView.saveWebArchive(basename, autoname, callback);
            }
        });
    }

    public WebView createWebView() {
        return getValue(new ValueGetter<WebView>() {
            @Override
            public WebView capture() {
                return new WebView(mWebView.getContext());
            }
        });
    }

    public PrintDocumentAdapter createPrintDocumentAdapter() {
        return getValue(new ValueGetter<PrintDocumentAdapter>() {
            @Override
            public PrintDocumentAdapter capture() {
                return mWebView.createPrintDocumentAdapter();
            }
        });
    }

    public void setLayoutHeightToMatchParent() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                ViewParent parent = mWebView.getParent();
                if (parent instanceof ViewGroup) {
                    ((ViewGroup) parent).getLayoutParams().height =
                        ViewGroup.LayoutParams.MATCH_PARENT;
                }
                mWebView.getLayoutParams().height = ViewGroup.LayoutParams.MATCH_PARENT;
                mWebView.requestLayout();
            }
        });
    }

    public void setLayoutToMatchParent() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                setMatchParent((View) mWebView.getParent());
                setMatchParent(mWebView);
                mWebView.requestLayout();
            }
        });
    }

    public void setAcceptThirdPartyCookies(final boolean accept) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                CookieManager.getInstance().setAcceptThirdPartyCookies(mWebView, accept);
            }
        });
    }

    public boolean acceptThirdPartyCookies() {
        return getValue(new ValueGetter<Boolean>() {
            @Override
            public Boolean capture() {
                return CookieManager.getInstance().acceptThirdPartyCookies(mWebView);
            }
        });
    }

    /**
     * Helper for running code on the UI thread where an exception is
     * a test failure. If this is already the UI thread then it runs
     * the code immediately.
     *
     * @see InstrumentationTestCase#runTestOnUiThread(Runnable)
     * @see ActivityTestRule#runOnUiThread(Runnable)
     * @param r The code to run in the UI thread
     */
    public void runOnUiThread(Runnable r) {
        try {
            if (isUiThread()) {
                r.run();
            } else {
                if (mActivityTestRule != null) {
                    mActivityTestRule.runOnUiThread(r);
                } else {
                    mTest.runTestOnUiThread(r);
                }
            }
        } catch (Throwable t) {
            Assert.fail("Unexpected error while running on UI thread: "
                    + t.getMessage());
        }
    }

    /**
     * Accessor for underlying WebView.
     * @return The WebView being wrapped by this class.
     */
    public WebView getWebView() {
        return mWebView;
    }

    private<T> T getValue(ValueGetter<T> getter) {
        runOnUiThread(getter);
        return getter.getValue();
    }

    private abstract class ValueGetter<T> implements Runnable {
        private T mValue;

        @Override
        public void run() {
            mValue = capture();
        }

        protected abstract T capture();

        public T getValue() {
           return mValue;
        }
    }

    /**
     * Returns true if the current thread is the UI thread based on the
     * Looper.
     */
    private static boolean isUiThread() {
        return (Looper.myLooper() == Looper.getMainLooper());
    }

    /**
     * @return Whether or not the load has finished.
     */
    private synchronized boolean isLoaded() {
        return mLoaded && mNewPicture && mProgress == 100;
    }

    /**
     * Makes a WebView call, waits for completion and then resets the
     * load state in preparation for the next load call.
     * @param call The call to make on the UI thread prior to waiting.
     */
    private void callAndWait(Runnable call) {
        Assert.assertTrue("WebViewOnUiThread.load*AndWaitForCompletion calls "
                + "may not be mixed with load* calls directly on WebView "
                + "without calling waitForLoadCompletion after the load",
                !isLoaded());
        clearLoad(); // clear any extraneous signals from a previous load.
        runOnUiThread(call);
        waitForLoadCompletion();
    }

    /**
     * Called whenever a load has been completed so that a subsequent call to
     * waitForLoadCompletion doesn't return immediately.
     */
    synchronized private void clearLoad() {
        mLoaded = false;
        mNewPicture = false;
        mProgress = 0;
    }

    /**
     * Uses a polling mechanism, while pumping messages to check when the
     * criteria is met.
     */
    private void waitOnUiThread(long timeout, final Callable<Boolean> doneCriteria) {
        new PollingCheck(timeout) {
            @Override
            protected boolean check() {
                pumpMessages();
                try {
                    return doneCriteria.call();
                } catch (Exception e) {
                    Assert.fail("Unexpected error while checking the criteria: "
                            + e.getMessage());
                    return true;
                }
            }
        }.run();
    }

    /**
     * Uses a wait/notify to check when the criteria is met.
     */
    private synchronized void waitOnTestThread(long timeout, Callable<Boolean> doneCriteria) {
        try {
            long waitEnd = SystemClock.uptimeMillis() + timeout;
            long timeRemaining = timeout;
            while (!doneCriteria.call() && timeRemaining > 0) {
                this.wait(timeRemaining);
                timeRemaining = waitEnd - SystemClock.uptimeMillis();
            }
            Assert.assertTrue("Action failed to complete before timeout", doneCriteria.call());
        } catch (InterruptedException e) {
            // We'll just drop out of the loop and fail
        } catch (Exception e) {
            Assert.fail("Unexpected error while checking the criteria: "
                    + e.getMessage());
        }
    }

    /**
     * Pumps all currently-queued messages in the UI thread and then exits.
     * This is useful to force processing while running tests in the UI thread.
     */
    private void pumpMessages() {
        class ExitLoopException extends RuntimeException {
        }

        // Force loop to exit when processing this. Loop.quit() doesn't
        // work because this is the main Loop.
        mWebView.getHandler().post(new Runnable() {
            @Override
            public void run() {
                throw new ExitLoopException(); // exit loop!
            }
        });
        try {
            // Pump messages until our message gets through.
            Looper.loop();
        } catch (ExitLoopException e) {
        }
    }

    /**
     * Set LayoutParams to MATCH_PARENT.
     *
     * @param view Target view
     */
    private void setMatchParent(View view) {
        ViewGroup.LayoutParams params = view.getLayoutParams();
        params.height = ViewGroup.LayoutParams.MATCH_PARENT;
        params.width = ViewGroup.LayoutParams.MATCH_PARENT;
        view.setLayoutParams(params);
    }

    /**
     * A WebChromeClient used to capture the onProgressChanged for use
     * in waitFor functions. If a test must override the WebChromeClient,
     * it can derive from this class or call onProgressChanged
     * directly.
     */
    public static class WaitForProgressClient extends WebChromeClient {
        private WebViewOnUiThread mOnUiThread;

        public WaitForProgressClient(WebViewOnUiThread onUiThread) {
            mOnUiThread = onUiThread;
        }

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);
            mOnUiThread.onProgressChanged(newProgress);
        }
    }

    /**
     * A WebViewClient that captures the onPageFinished for use in
     * waitFor functions. Using initializeWebView sets the WaitForLoadedClient
     * into the WebView. If a test needs to set a specific WebViewClient and
     * needs the waitForCompletion capability then it should derive from
     * WaitForLoadedClient or call WebViewOnUiThread.onPageFinished.
     */
    public static class WaitForLoadedClient extends WebViewClient {
        private WebViewOnUiThread mOnUiThread;

        public WaitForLoadedClient(WebViewOnUiThread onUiThread) {
            mOnUiThread = onUiThread;
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            mOnUiThread.onPageFinished();
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            mOnUiThread.onPageStarted();
        }
    }

    /**
     * A PictureListener that captures the onNewPicture for use in
     * waitForLoadCompletion. Using initializeWebView sets the PictureListener
     * into the WebView. If a test needs to set a specific PictureListener and
     * needs the waitForCompletion capability then it should call
     * WebViewOnUiThread.onNewPicture.
     */
    private class WaitForNewPicture implements PictureListener {
        @Override
        public void onNewPicture(WebView view, Picture picture) {
            WebViewOnUiThread.this.onNewPicture();
        }
    }
}