summaryrefslogtreecommitdiffstats
path: root/core/java/android/webkit/WebViewClassic.java
blob: d68511c453350c55b31eec9293f67209667cf1ca (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
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
/*
 * Copyright (C) 2012 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;

import android.accessibilityservice.AccessibilityServiceInfo;
import android.animation.ObjectAnimator;
import android.annotation.Widget;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ComponentCallbacks2;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.database.DataSetObserver;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.DrawFilter;
import android.graphics.Paint;
import android.graphics.PaintFlagsDrawFilter;
import android.graphics.Picture;
import android.graphics.Point;
import android.graphics.PointF;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Region;
import android.graphics.RegionIterator;
import android.graphics.Shader;
import android.graphics.drawable.Drawable;
import android.net.Proxy;
import android.net.ProxyProperties;
import android.net.Uri;
import android.net.http.SslCertificate;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.SystemClock;
import android.security.KeyChain;
import android.text.Editable;
import android.text.InputType;
import android.text.Selection;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.EventLog;
import android.util.Log;
import android.view.Gravity;
import android.view.HapticFeedbackConstants;
import android.view.HardwareCanvas;
import android.view.InputDevice;
import android.view.KeyCharacterMap;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.SoundEffectConstants;
import android.view.VelocityTracker;
import android.view.View;
import android.view.View.MeasureSpec;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.ViewRootImpl;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityManager;
import android.view.accessibility.AccessibilityNodeInfo;
import android.view.inputmethod.BaseInputConnection;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputConnection;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebView.HitTestResult;
import android.webkit.WebView.PictureListener;
import android.webkit.WebViewCore.DrawData;
import android.webkit.WebViewCore.EventHub;
import android.webkit.WebViewCore.TextFieldInitData;
import android.webkit.WebViewCore.TextSelectionData;
import android.webkit.WebViewCore.WebKitHitTest;
import android.widget.AbsoluteLayout;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.CheckedTextView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.OverScroller;
import android.widget.PopupWindow;
import android.widget.Scroller;
import android.widget.TextView;
import android.widget.Toast;

import junit.framework.Assert;

import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.Vector;

/**
 * Implements a backend provider for the {@link WebView} public API.
 * @hide
 */
// TODO: Check if any WebView published API methods are called from within here, and if so
// we should bounce the call out via the proxy to enable any sub-class to override it.
@Widget
@SuppressWarnings("deprecation")
public final class WebViewClassic implements WebViewProvider, WebViewProvider.ScrollDelegate,
        WebViewProvider.ViewDelegate {
    /**
     * InputConnection used for ContentEditable. This captures changes
     * to the text and sends them either as key strokes or text changes.
     */
    class WebViewInputConnection extends BaseInputConnection {
        // Used for mapping characters to keys typed.
        private KeyCharacterMap mKeyCharacterMap;
        private boolean mIsKeySentByMe;
        private int mInputType;
        private int mImeOptions;
        private String mHint;
        private int mMaxLength;
        private boolean mIsAutoFillable;
        private boolean mIsAutoCompleteEnabled;
        private String mName;
        private int mBatchLevel;

        public WebViewInputConnection() {
            super(mWebView, true);
        }

        public void setAutoFillable(int queryId) {
            mIsAutoFillable = getSettings().getAutoFillEnabled()
                    && (queryId != WebTextView.FORM_NOT_AUTOFILLABLE);
            int variation = mInputType & EditorInfo.TYPE_MASK_VARIATION;
            if (variation != EditorInfo.TYPE_TEXT_VARIATION_WEB_PASSWORD
                    && (mIsAutoFillable || mIsAutoCompleteEnabled)) {
                if (mName != null && mName.length() > 0) {
                    requestFormData(mName, mFieldPointer, mIsAutoFillable,
                            mIsAutoCompleteEnabled);
                }
            }
        }

        @Override
        public boolean beginBatchEdit() {
            if (mBatchLevel == 0) {
                beginTextBatch();
            }
            mBatchLevel++;
            return false;
        }

        @Override
        public boolean endBatchEdit() {
            mBatchLevel--;
            if (mBatchLevel == 0) {
                commitTextBatch();
            }
            return false;
        }

        public boolean getIsAutoFillable() {
            return mIsAutoFillable;
        }

        @Override
        public boolean sendKeyEvent(KeyEvent event) {
            // Some IMEs send key events directly using sendKeyEvents.
            // WebViewInputConnection should treat these as text changes.
            if (!mIsKeySentByMe) {
                if (event.getAction() == KeyEvent.ACTION_UP) {
                    if (event.getKeyCode() == KeyEvent.KEYCODE_DEL) {
                        return deleteSurroundingText(1, 0);
                    } else if (event.getKeyCode() == KeyEvent.KEYCODE_FORWARD_DEL) {
                        return deleteSurroundingText(0, 1);
                    } else if (event.getUnicodeChar() != 0){
                        String newComposingText =
                                Character.toString((char)event.getUnicodeChar());
                        return commitText(newComposingText, 1);
                    }
                } else if (event.getAction() == KeyEvent.ACTION_DOWN &&
                        (event.getKeyCode() == KeyEvent.KEYCODE_DEL
                        || event.getKeyCode() == KeyEvent.KEYCODE_FORWARD_DEL
                        || event.getUnicodeChar() != 0)) {
                    return true; // only act on action_down
                }
            }
            return super.sendKeyEvent(event);
        }

        public void setTextAndKeepSelection(CharSequence text) {
            Editable editable = getEditable();
            int selectionStart = Selection.getSelectionStart(editable);
            int selectionEnd = Selection.getSelectionEnd(editable);
            text = limitReplaceTextByMaxLength(text, editable.length());
            editable.replace(0, editable.length(), text);
            restartInput();
            // Keep the previous selection.
            selectionStart = Math.min(selectionStart, editable.length());
            selectionEnd = Math.min(selectionEnd, editable.length());
            setSelection(selectionStart, selectionEnd);
            finishComposingText();
        }

        public void replaceSelection(CharSequence text) {
            Editable editable = getEditable();
            int selectionStart = Selection.getSelectionStart(editable);
            int selectionEnd = Selection.getSelectionEnd(editable);
            text = limitReplaceTextByMaxLength(text, selectionEnd - selectionStart);
            setNewText(selectionStart, selectionEnd, text);
            editable.replace(selectionStart, selectionEnd, text);
            restartInput();
            // Move caret to the end of the new text
            int newCaret = selectionStart + text.length();
            setSelection(newCaret, newCaret);
        }

        @Override
        public boolean setComposingText(CharSequence text, int newCursorPosition) {
            Editable editable = getEditable();
            int start = getComposingSpanStart(editable);
            int end = getComposingSpanEnd(editable);
            if (start < 0 || end < 0) {
                start = Selection.getSelectionStart(editable);
                end = Selection.getSelectionEnd(editable);
            }
            if (end < start) {
                int temp = end;
                end = start;
                start = temp;
            }
            CharSequence limitedText = limitReplaceTextByMaxLength(text, end - start);
            setNewText(start, end, limitedText);
            if (limitedText != text) {
                newCursorPosition -= text.length() - limitedText.length();
            }
            super.setComposingText(limitedText, newCursorPosition);
            updateSelection();
            if (limitedText != text) {
                int lastCaret = start + limitedText.length();
                finishComposingText();
                setSelection(lastCaret, lastCaret);
            }
            return true;
        }

        @Override
        public boolean commitText(CharSequence text, int newCursorPosition) {
            setComposingText(text, newCursorPosition);
            finishComposingText();
            return true;
        }

        @Override
        public boolean deleteSurroundingText(int leftLength, int rightLength) {
            // This code is from BaseInputConnection#deleteSurroundText.
            // We have to delete the same text in webkit.
            Editable content = getEditable();
            int a = Selection.getSelectionStart(content);
            int b = Selection.getSelectionEnd(content);

            if (a > b) {
                int tmp = a;
                a = b;
                b = tmp;
            }

            int ca = getComposingSpanStart(content);
            int cb = getComposingSpanEnd(content);
            if (cb < ca) {
                int tmp = ca;
                ca = cb;
                cb = tmp;
            }
            if (ca != -1 && cb != -1) {
                if (ca < a) a = ca;
                if (cb > b) b = cb;
            }

            int endDelete = Math.min(content.length(), b + rightLength);
            if (endDelete > b) {
                setNewText(b, endDelete, "");
            }
            int startDelete = Math.max(0, a - leftLength);
            if (startDelete < a) {
                setNewText(startDelete, a, "");
            }
            return super.deleteSurroundingText(leftLength, rightLength);
        }

        @Override
        public boolean performEditorAction(int editorAction) {

            boolean handled = true;
            switch (editorAction) {
            case EditorInfo.IME_ACTION_NEXT:
                mWebView.requestFocus(View.FOCUS_FORWARD);
                break;
            case EditorInfo.IME_ACTION_PREVIOUS:
                mWebView.requestFocus(View.FOCUS_BACKWARD);
                break;
            case EditorInfo.IME_ACTION_DONE:
                WebViewClassic.this.hideSoftKeyboard();
                break;
            case EditorInfo.IME_ACTION_GO:
            case EditorInfo.IME_ACTION_SEARCH:
                WebViewClassic.this.hideSoftKeyboard();
                String text = getEditable().toString();
                passToJavaScript(text, new KeyEvent(KeyEvent.ACTION_DOWN,
                        KeyEvent.KEYCODE_ENTER));
                passToJavaScript(text, new KeyEvent(KeyEvent.ACTION_UP,
                        KeyEvent.KEYCODE_ENTER));
                break;

            default:
                handled = super.performEditorAction(editorAction);
                break;
            }

            return handled;
        }

        public void initEditorInfo(WebViewCore.TextFieldInitData initData) {
            int type = initData.mType;
            int inputType = InputType.TYPE_CLASS_TEXT
                    | InputType.TYPE_TEXT_VARIATION_WEB_EDIT_TEXT;
            int imeOptions = EditorInfo.IME_FLAG_NO_EXTRACT_UI
                    | EditorInfo.IME_FLAG_NO_FULLSCREEN;
            if (!initData.mIsSpellCheckEnabled) {
                inputType |= InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS;
            }
            if (WebTextView.TEXT_AREA != type) {
                if (initData.mIsTextFieldNext) {
                    imeOptions |= EditorInfo.IME_FLAG_NAVIGATE_NEXT;
                }
                if (initData.mIsTextFieldPrev) {
                    imeOptions |= EditorInfo.IME_FLAG_NAVIGATE_PREVIOUS;
                }
            }
            int action = EditorInfo.IME_ACTION_GO;
            switch (type) {
                case WebTextView.NORMAL_TEXT_FIELD:
                    break;
                case WebTextView.TEXT_AREA:
                    inputType |= InputType.TYPE_TEXT_FLAG_MULTI_LINE
                            | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES
                            | InputType.TYPE_TEXT_FLAG_AUTO_CORRECT;
                    action = EditorInfo.IME_ACTION_NONE;
                    break;
                case WebTextView.PASSWORD:
                    inputType |= EditorInfo.TYPE_TEXT_VARIATION_WEB_PASSWORD;
                    break;
                case WebTextView.SEARCH:
                    action = EditorInfo.IME_ACTION_SEARCH;
                    break;
                case WebTextView.EMAIL:
                    // inputType needs to be overwritten because of the different text variation.
                    inputType = InputType.TYPE_CLASS_TEXT
                            | InputType.TYPE_TEXT_VARIATION_WEB_EMAIL_ADDRESS;
                    break;
                case WebTextView.NUMBER:
                    // inputType needs to be overwritten because of the different class.
                    inputType = InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_VARIATION_NORMAL
                            | InputType.TYPE_NUMBER_FLAG_SIGNED | InputType.TYPE_NUMBER_FLAG_DECIMAL;
                    // Number and telephone do not have both a Tab key and an
                    // action, so set the action to NEXT
                    break;
                case WebTextView.TELEPHONE:
                    // inputType needs to be overwritten because of the different class.
                    inputType = InputType.TYPE_CLASS_PHONE;
                    break;
                case WebTextView.URL:
                    // TYPE_TEXT_VARIATION_URI prevents Tab key from showing, so
                    // exclude it for now.
                    inputType |= InputType.TYPE_TEXT_VARIATION_URI;
                    break;
                default:
                    break;
            }
            imeOptions |= action;
            mHint = initData.mLabel;
            mInputType = inputType;
            mImeOptions = imeOptions;
            mMaxLength = initData.mMaxLength;
            mIsAutoCompleteEnabled = initData.mIsAutoCompleteEnabled;
            mName = initData.mName;
            mAutoCompletePopup.clearAdapter();
        }

        public void setupEditorInfo(EditorInfo outAttrs) {
            outAttrs.inputType = mInputType;
            outAttrs.imeOptions = mImeOptions;
            outAttrs.hintText = mHint;
            outAttrs.initialCapsMode = getCursorCapsMode(InputType.TYPE_CLASS_TEXT);

            Editable editable = getEditable();
            int selectionStart = Selection.getSelectionStart(editable);
            int selectionEnd = Selection.getSelectionEnd(editable);
            if (selectionStart < 0 || selectionEnd < 0) {
                selectionStart = editable.length();
                selectionEnd = selectionStart;
            }
            outAttrs.initialSelStart = selectionStart;
            outAttrs.initialSelEnd = selectionEnd;
        }

        @Override
        public boolean setSelection(int start, int end) {
            boolean result = super.setSelection(start, end);
            updateSelection();
            return result;
        }

        @Override
        public boolean setComposingRegion(int start, int end) {
            boolean result = super.setComposingRegion(start, end);
            updateSelection();
            return result;
        }

        /**
         * Send the selection and composing spans to the IME.
         */
        private void updateSelection() {
            Editable editable = getEditable();
            int selectionStart = Selection.getSelectionStart(editable);
            int selectionEnd = Selection.getSelectionEnd(editable);
            int composingStart = getComposingSpanStart(editable);
            int composingEnd = getComposingSpanEnd(editable);
            InputMethodManager imm = InputMethodManager.peekInstance();
            if (imm != null) {
                imm.updateSelection(mWebView, selectionStart, selectionEnd,
                        composingStart, composingEnd);
            }
        }

        /**
         * Sends a text change to webkit indirectly. If it is a single-
         * character add or delete, it sends it as a key stroke. If it cannot
         * be represented as a key stroke, it sends it as a field change.
         * @param start The start offset (inclusive) of the text being changed.
         * @param end The end offset (exclusive) of the text being changed.
         * @param text The new text to replace the changed text.
         */
        private void setNewText(int start, int end, CharSequence text) {
            mIsKeySentByMe = true;
            Editable editable = getEditable();
            CharSequence original = editable.subSequence(start, end);
            boolean isCharacterAdd = false;
            boolean isCharacterDelete = false;
            int textLength = text.length();
            int originalLength = original.length();
            int selectionStart = Selection.getSelectionStart(editable);
            int selectionEnd = Selection.getSelectionEnd(editable);
            if (selectionStart == selectionEnd) {
                if (textLength > originalLength) {
                    isCharacterAdd = (textLength == originalLength + 1)
                            && TextUtils.regionMatches(text, 0, original, 0,
                                    originalLength);
                } else if (originalLength > textLength) {
                    isCharacterDelete = (textLength == originalLength - 1)
                            && TextUtils.regionMatches(text, 0, original, 0,
                                    textLength);
                }
            }
            if (isCharacterAdd) {
                sendCharacter(text.charAt(textLength - 1));
            } else if (isCharacterDelete) {
                sendKey(KeyEvent.KEYCODE_DEL);
            } else if ((textLength != originalLength) ||
                    !TextUtils.regionMatches(text, 0, original, 0,
                            textLength)) {
                // Send a message so that key strokes and text replacement
                // do not come out of order.
                Message replaceMessage = mPrivateHandler.obtainMessage(
                        REPLACE_TEXT, start,  end, text.toString());
                mPrivateHandler.sendMessage(replaceMessage);
            }
            if (mAutoCompletePopup != null) {
                StringBuilder newText = new StringBuilder();
                newText.append(editable.subSequence(0, start));
                newText.append(text);
                newText.append(editable.subSequence(end, editable.length()));
                mAutoCompletePopup.setText(newText.toString());
            }
            mIsKeySentByMe = false;
        }

        /**
         * Send a single character to the WebView as a key down and up event.
         * @param c The character to be sent.
         */
        private void sendCharacter(char c) {
            if (mKeyCharacterMap == null) {
                mKeyCharacterMap = KeyCharacterMap.load(KeyCharacterMap.VIRTUAL_KEYBOARD);
            }
            char[] chars = new char[1];
            chars[0] = c;
            KeyEvent[] events = mKeyCharacterMap.getEvents(chars);
            if (events != null) {
                for (KeyEvent event : events) {
                    sendKeyEvent(event);
                }
            } else {
                Message msg = mPrivateHandler.obtainMessage(KEY_PRESS, (int) c, 0);
                mPrivateHandler.sendMessage(msg);
            }
        }

        /**
         * Send a key event for a specific key code, not a standard
         * unicode character.
         * @param keyCode The key code to send.
         */
        private void sendKey(int keyCode) {
            long eventTime = SystemClock.uptimeMillis();
            sendKeyEvent(new KeyEvent(eventTime, eventTime,
                    KeyEvent.ACTION_DOWN, keyCode, 0, 0,
                    KeyCharacterMap.VIRTUAL_KEYBOARD, 0,
                    KeyEvent.FLAG_SOFT_KEYBOARD));
            sendKeyEvent(new KeyEvent(SystemClock.uptimeMillis(), eventTime,
                    KeyEvent.ACTION_UP, keyCode, 0, 0,
                    KeyCharacterMap.VIRTUAL_KEYBOARD, 0,
                    KeyEvent.FLAG_SOFT_KEYBOARD));
        }

        private CharSequence limitReplaceTextByMaxLength(CharSequence text,
                int numReplaced) {
            if (mMaxLength > 0) {
                Editable editable = getEditable();
                int maxReplace = mMaxLength - editable.length() + numReplaced;
                if (maxReplace < text.length()) {
                    maxReplace = Math.max(maxReplace, 0);
                    // New length is greater than the maximum. trim it down.
                    text = text.subSequence(0, maxReplace);
                }
            }
            return text;
        }

        private void restartInput() {
            InputMethodManager imm = InputMethodManager.peekInstance();
            if (imm != null) {
                // Since the text has changed, do not allow the IME to replace the
                // existing text as though it were a completion.
                imm.restartInput(mWebView);
            }
        }
    }

    private class PastePopupWindow extends PopupWindow implements View.OnClickListener {
        private ViewGroup mContentView;
        private TextView mPasteTextView;

        public PastePopupWindow() {
            super(mContext, null,
                    com.android.internal.R.attr.textSelectHandleWindowStyle);
            setClippingEnabled(true);
            LinearLayout linearLayout = new LinearLayout(mContext);
            linearLayout.setOrientation(LinearLayout.HORIZONTAL);
            mContentView = linearLayout;
            mContentView.setBackgroundResource(
                    com.android.internal.R.drawable.text_edit_paste_window);

            LayoutInflater inflater = (LayoutInflater)mContext.
                    getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            ViewGroup.LayoutParams wrapContent = new ViewGroup.LayoutParams(
                    ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);

            mPasteTextView = (TextView) inflater.inflate(
                    com.android.internal.R.layout.text_edit_action_popup_text, null);
            mPasteTextView.setLayoutParams(wrapContent);
            mContentView.addView(mPasteTextView);
            mPasteTextView.setText(com.android.internal.R.string.paste);
            mPasteTextView.setOnClickListener(this);
            this.setContentView(mContentView);
        }

        public void show(Point cursorBottom, Point cursorTop,
                int windowLeft, int windowTop) {
            measureContent();

            int width = mContentView.getMeasuredWidth();
            int height = mContentView.getMeasuredHeight();
            int y = cursorTop.y - height;
            int x = cursorTop.x - (width / 2);
            if (y < windowTop) {
                // There's not enough room vertically, move it below the
                // handle.
                ensureSelectionHandles();
                y = cursorBottom.y + mSelectHandleCenter.getIntrinsicHeight();
                x = cursorBottom.x - (width / 2);
            }
            if (x < windowLeft) {
                x = windowLeft;
            }
            if (!isShowing()) {
                showAtLocation(mWebView, Gravity.NO_GRAVITY, x, y);
            }
            update(x, y, width, height);
        }

        public void hide() {
            dismiss();
        }

        @Override
        public void onClick(View view) {
            pasteFromClipboard();
            selectionDone();
        }

        protected void measureContent() {
            final DisplayMetrics displayMetrics = mContext.getResources().getDisplayMetrics();
            mContentView.measure(
                    View.MeasureSpec.makeMeasureSpec(displayMetrics.widthPixels,
                            View.MeasureSpec.AT_MOST),
                    View.MeasureSpec.makeMeasureSpec(displayMetrics.heightPixels,
                            View.MeasureSpec.AT_MOST));
        }
    }

    // if AUTO_REDRAW_HACK is true, then the CALL key will toggle redrawing
    // the screen all-the-time. Good for profiling our drawing code
    static private final boolean AUTO_REDRAW_HACK = false;

    // The rate at which edit text is scrolled in content pixels per millisecond
    static private final float TEXT_SCROLL_RATE = 0.01f;

    // The presumed scroll rate for the first scroll of edit text
    static private final long TEXT_SCROLL_FIRST_SCROLL_MS = 16;

    // Buffer pixels of the caret rectangle when moving edit text into view
    // after resize.
    static private final int EDIT_RECT_BUFFER = 10;

    static private final long SELECTION_HANDLE_ANIMATION_MS = 150;

    // true means redraw the screen all-the-time. Only with AUTO_REDRAW_HACK
    private boolean mAutoRedraw;

    // Reference to the AlertDialog displayed by InvokeListBox.
    // It's used to dismiss the dialog in destroy if not done before.
    private AlertDialog mListBoxDialog = null;

    // Reference to the save password dialog so it can be dimissed in
    // destroy if not done before.
    private AlertDialog mSavePasswordDialog = null;

    static final String LOGTAG = "webview";

    private ZoomManager mZoomManager;

    private final Rect mInvScreenRect = new Rect();
    private final Rect mScreenRect = new Rect();
    private final RectF mVisibleContentRect = new RectF();
    private boolean mIsWebViewVisible = true;
    WebViewInputConnection mInputConnection = null;
    private int mFieldPointer;
    private PastePopupWindow mPasteWindow;
    private AutoCompletePopup mAutoCompletePopup;
    Rect mEditTextContentBounds = new Rect();
    Rect mEditTextContent = new Rect();
    int mEditTextLayerId;
    boolean mIsEditingText = false;
    ArrayList<Message> mBatchedTextChanges = new ArrayList<Message>();
    boolean mIsBatchingTextChanges = false;
    private long mLastEditScroll = 0;

    private static class OnTrimMemoryListener implements ComponentCallbacks2 {
        private static OnTrimMemoryListener sInstance = null;

        static void init(Context c) {
            if (sInstance == null) {
                sInstance = new OnTrimMemoryListener(c.getApplicationContext());
            }
        }

        private OnTrimMemoryListener(Context c) {
            c.registerComponentCallbacks(this);
        }

        @Override
        public void onConfigurationChanged(Configuration newConfig) {
            // Ignore
        }

        @Override
        public void onLowMemory() {
            // Ignore
        }

        @Override
        public void onTrimMemory(int level) {
            if (DebugFlags.WEB_VIEW) {
                Log.d("WebView", "onTrimMemory: " + level);
            }
            // When framework reset EGL context during high memory pressure, all
            // the existing GL resources for the html5 video will be destroyed
            // at native side.
            // Here we just need to clean up the Surface Texture which is static.
            if (level > TRIM_MEMORY_UI_HIDDEN) {
                HTML5VideoInline.cleanupSurfaceTexture();
                HTML5VideoView.release();
            }
            WebViewClassic.nativeOnTrimMemory(level);
        }
    }

    // A final CallbackProxy shared by WebViewCore and BrowserFrame.
    private CallbackProxy mCallbackProxy;

    private WebViewDatabaseClassic mDatabase;

    // SSL certificate for the main top-level page (if secure)
    private SslCertificate mCertificate;

    // Native WebView pointer that is 0 until the native object has been
    // created.
    private int mNativeClass;
    // This would be final but it needs to be set to null when the WebView is
    // destroyed.
    private WebViewCore mWebViewCore;
    // Handler for dispatching UI messages.
    /* package */ final Handler mPrivateHandler = new PrivateHandler();
    // Used to ignore changes to webkit text that arrives to the UI side after
    // more key events.
    private int mTextGeneration;

    /* package */ void incrementTextGeneration() { mTextGeneration++; }

    // Used by WebViewCore to create child views.
    /* package */ ViewManager mViewManager;

    // Used to display in full screen mode
    PluginFullScreenHolder mFullScreenHolder;

    /**
     * Position of the last touch event in pixels.
     * Use integer to prevent loss of dragging delta calculation accuracy;
     * which was done in float and converted to integer, and resulted in gradual
     * and compounding touch position and view dragging mismatch.
     */
    private int mLastTouchX;
    private int mLastTouchY;
    private int mStartTouchX;
    private int mStartTouchY;
    private float mAverageAngle;

    /**
     * Time of the last touch event.
     */
    private long mLastTouchTime;

    /**
     * Time of the last time sending touch event to WebViewCore
     */
    private long mLastSentTouchTime;

    /**
     * The minimum elapsed time before sending another ACTION_MOVE event to
     * WebViewCore. This really should be tuned for each type of the devices.
     * For example in Google Map api test case, it takes Dream device at least
     * 150ms to do a full cycle in the WebViewCore by processing a touch event,
     * triggering the layout and drawing the picture. While the same process
     * takes 60+ms on the current high speed device. If we make
     * TOUCH_SENT_INTERVAL too small, there will be multiple touch events sent
     * to WebViewCore queue and the real layout and draw events will be pushed
     * to further, which slows down the refresh rate. Choose 50 to favor the
     * current high speed devices. For Dream like devices, 100 is a better
     * choice. Maybe make this in the buildspec later.
     * (Update 12/14/2010: changed to 0 since current device should be able to
     * handle the raw events and Map team voted to have the raw events too.
     */
    private static final int TOUCH_SENT_INTERVAL = 0;
    private int mCurrentTouchInterval = TOUCH_SENT_INTERVAL;

    /**
     * Helper class to get velocity for fling
     */
    VelocityTracker mVelocityTracker;
    private int mMaximumFling;
    private float mLastVelocity;
    private float mLastVelX;
    private float mLastVelY;

    // The id of the native layer being scrolled.
    private int mCurrentScrollingLayerId;
    private Rect mScrollingLayerRect = new Rect();

    // only trigger accelerated fling if the new velocity is at least
    // MINIMUM_VELOCITY_RATIO_FOR_ACCELERATION times of the previous velocity
    private static final float MINIMUM_VELOCITY_RATIO_FOR_ACCELERATION = 0.2f;

    /**
     * Touch mode
     * TODO: Some of this is now unnecessary as it is handled by
     * WebInputTouchDispatcher (such as click, long press, and double tap).
     */
    private int mTouchMode = TOUCH_DONE_MODE;
    private static final int TOUCH_INIT_MODE = 1;
    private static final int TOUCH_DRAG_START_MODE = 2;
    private static final int TOUCH_DRAG_MODE = 3;
    private static final int TOUCH_SHORTPRESS_START_MODE = 4;
    private static final int TOUCH_SHORTPRESS_MODE = 5;
    private static final int TOUCH_DOUBLE_TAP_MODE = 6;
    private static final int TOUCH_DONE_MODE = 7;
    private static final int TOUCH_PINCH_DRAG = 8;
    private static final int TOUCH_DRAG_LAYER_MODE = 9;
    private static final int TOUCH_DRAG_TEXT_MODE = 10;

    // true when the touch movement exceeds the slop
    private boolean mConfirmMove;
    private boolean mTouchInEditText;

    // Whether or not to draw the cursor ring.
    private boolean mDrawCursorRing = true;

    // true if onPause has been called (and not onResume)
    private boolean mIsPaused;

    private HitTestResult mInitialHitTestResult;
    private WebKitHitTest mFocusedNode;

    /**
     * Customizable constant
     */
    // pre-computed square of ViewConfiguration.getScaledTouchSlop()
    private int mTouchSlopSquare;
    // pre-computed square of ViewConfiguration.getScaledDoubleTapSlop()
    private int mDoubleTapSlopSquare;
    // pre-computed density adjusted navigation slop
    private int mNavSlop;
    // This should be ViewConfiguration.getTapTimeout()
    // But system time out is 100ms, which is too short for the browser.
    // In the browser, if it switches out of tap too soon, jump tap won't work.
    // In addition, a double tap on a trackpad will always have a duration of
    // 300ms, so this value must be at least that (otherwise we will timeout the
    // first tap and convert it to a long press).
    private static final int TAP_TIMEOUT = 300;
    // This should be ViewConfiguration.getLongPressTimeout()
    // But system time out is 500ms, which is too short for the browser.
    // With a short timeout, it's difficult to treat trigger a short press.
    private static final int LONG_PRESS_TIMEOUT = 1000;
    // needed to avoid flinging after a pause of no movement
    private static final int MIN_FLING_TIME = 250;
    // draw unfiltered after drag is held without movement
    private static final int MOTIONLESS_TIME = 100;
    // The amount of content to overlap between two screens when going through
    // pages with the space bar, in pixels.
    private static final int PAGE_SCROLL_OVERLAP = 24;

    /**
     * These prevent calling requestLayout if either dimension is fixed. This
     * depends on the layout parameters and the measure specs.
     */
    boolean mWidthCanMeasure;
    boolean mHeightCanMeasure;

    // Remember the last dimensions we sent to the native side so we can avoid
    // sending the same dimensions more than once.
    int mLastWidthSent;
    int mLastHeightSent;
    // Since view height sent to webkit could be fixed to avoid relayout, this
    // value records the last sent actual view height.
    int mLastActualHeightSent;

    private int mContentWidth;   // cache of value from WebViewCore
    private int mContentHeight;  // cache of value from WebViewCore

    // Need to have the separate control for horizontal and vertical scrollbar
    // style than the View's single scrollbar style
    private boolean mOverlayHorizontalScrollbar = true;
    private boolean mOverlayVerticalScrollbar = false;

    // our standard speed. this way small distances will be traversed in less
    // time than large distances, but we cap the duration, so that very large
    // distances won't take too long to get there.
    private static final int STD_SPEED = 480;  // pixels per second
    // time for the longest scroll animation
    private static final int MAX_DURATION = 750;   // milliseconds

    // Used by OverScrollGlow
    OverScroller mScroller;
    Scroller mEditTextScroller;

    private boolean mInOverScrollMode = false;
    private static Paint mOverScrollBackground;
    private static Paint mOverScrollBorder;

    private boolean mWrapContent;
    private static final int MOTIONLESS_FALSE           = 0;
    private static final int MOTIONLESS_PENDING         = 1;
    private static final int MOTIONLESS_TRUE            = 2;
    private static final int MOTIONLESS_IGNORE          = 3;
    private int mHeldMotionless;

    // Lazily-instantiated instance for injecting accessibility.
    private AccessibilityInjector mAccessibilityInjector;

    /**
     * How long the caret handle will last without being touched.
     */
    private static final long CARET_HANDLE_STAMINA_MS = 3000;

    private Drawable mSelectHandleLeft;
    private Drawable mSelectHandleRight;
    private Drawable mSelectHandleCenter;
    private Point mSelectOffset;
    private Point mSelectCursorBase = new Point();
    private Rect mSelectHandleBaseBounds = new Rect();
    private int mSelectCursorBaseLayerId;
    private QuadF mSelectCursorBaseTextQuad = new QuadF();
    private Point mSelectCursorExtent = new Point();
    private Rect mSelectHandleExtentBounds = new Rect();
    private int mSelectCursorExtentLayerId;
    private QuadF mSelectCursorExtentTextQuad = new QuadF();
    private Point mSelectDraggingCursor;
    private QuadF mSelectDraggingTextQuad;
    private boolean mIsCaretSelection;
    static final int HANDLE_ID_BASE = 0;
    static final int HANDLE_ID_EXTENT = 1;

    // the color used to highlight the touch rectangles
    static final int HIGHLIGHT_COLOR = 0x6633b5e5;
    // the region indicating where the user touched on the screen
    private Region mTouchHighlightRegion = new Region();
    // the paint for the touch highlight
    private Paint mTouchHightlightPaint = new Paint();
    // debug only
    private static final boolean DEBUG_TOUCH_HIGHLIGHT = true;
    private static final int TOUCH_HIGHLIGHT_ELAPSE_TIME = 2000;
    private Paint mTouchCrossHairColor;
    private int mTouchHighlightX;
    private int mTouchHighlightY;
    private boolean mShowTapHighlight;

    // Basically this proxy is used to tell the Video to update layer tree at
    // SetBaseLayer time and to pause when WebView paused.
    private HTML5VideoViewProxy mHTML5VideoViewProxy;

    // If we are using a set picture, don't send view updates to webkit
    private boolean mBlockWebkitViewMessages = false;

    // cached value used to determine if we need to switch drawing models
    private boolean mHardwareAccelSkia = false;

    /*
     * Private message ids
     */
    private static final int REMEMBER_PASSWORD          = 1;
    private static final int NEVER_REMEMBER_PASSWORD    = 2;
    private static final int SWITCH_TO_SHORTPRESS       = 3;
    private static final int SWITCH_TO_LONGPRESS        = 4;
    private static final int RELEASE_SINGLE_TAP         = 5;
    private static final int REQUEST_FORM_DATA          = 6;
    private static final int DRAG_HELD_MOTIONLESS       = 8;
    private static final int PREVENT_DEFAULT_TIMEOUT    = 10;
    private static final int SCROLL_SELECT_TEXT         = 11;


    private static final int FIRST_PRIVATE_MSG_ID = REMEMBER_PASSWORD;
    private static final int LAST_PRIVATE_MSG_ID = SCROLL_SELECT_TEXT;

    /*
     * Package message ids
     */
    static final int SCROLL_TO_MSG_ID                   = 101;
    static final int NEW_PICTURE_MSG_ID                 = 105;
    static final int WEBCORE_INITIALIZED_MSG_ID         = 107;
    static final int UPDATE_TEXTFIELD_TEXT_MSG_ID       = 108;
    static final int UPDATE_ZOOM_RANGE                  = 109;
    static final int TAKE_FOCUS                         = 110;
    static final int CLEAR_TEXT_ENTRY                   = 111;
    static final int UPDATE_TEXT_SELECTION_MSG_ID       = 112;
    static final int SHOW_RECT_MSG_ID                   = 113;
    static final int LONG_PRESS_CENTER                  = 114;
    static final int PREVENT_TOUCH_ID                   = 115;
    static final int WEBCORE_NEED_TOUCH_EVENTS          = 116;
    // obj=Rect in doc coordinates
    static final int INVAL_RECT_MSG_ID                  = 117;
    static final int REQUEST_KEYBOARD                   = 118;
    static final int SHOW_FULLSCREEN                    = 120;
    static final int HIDE_FULLSCREEN                    = 121;
    static final int UPDATE_MATCH_COUNT                 = 126;
    static final int CENTER_FIT_RECT                    = 127;
    static final int SET_SCROLLBAR_MODES                = 129;
    static final int SELECTION_STRING_CHANGED           = 130;
    static final int HIT_TEST_RESULT                    = 131;
    static final int SAVE_WEBARCHIVE_FINISHED           = 132;

    static final int SET_AUTOFILLABLE                   = 133;
    static final int AUTOFILL_COMPLETE                  = 134;

    static final int SCREEN_ON                          = 136;
    static final int UPDATE_ZOOM_DENSITY                = 139;
    static final int EXIT_FULLSCREEN_VIDEO              = 140;

    static final int COPY_TO_CLIPBOARD                  = 141;
    static final int INIT_EDIT_FIELD                    = 142;
    static final int REPLACE_TEXT                       = 143;
    static final int CLEAR_CARET_HANDLE                 = 144;
    static final int KEY_PRESS                          = 145;
    static final int RELOCATE_AUTO_COMPLETE_POPUP       = 146;
    static final int FOCUS_NODE_CHANGED                 = 147;
    static final int AUTOFILL_FORM                      = 148;
    static final int SCROLL_EDIT_TEXT                   = 149;
    static final int EDIT_TEXT_SIZE_CHANGED             = 150;
    static final int SHOW_CARET_HANDLE                  = 151;
    static final int UPDATE_CONTENT_BOUNDS              = 152;
    static final int SCROLL_HANDLE_INTO_VIEW            = 153;

    private static final int FIRST_PACKAGE_MSG_ID = SCROLL_TO_MSG_ID;
    private static final int LAST_PACKAGE_MSG_ID = HIT_TEST_RESULT;

    static final String[] HandlerPrivateDebugString = {
        "REMEMBER_PASSWORD", //              = 1;
        "NEVER_REMEMBER_PASSWORD", //        = 2;
        "SWITCH_TO_SHORTPRESS", //           = 3;
        "SWITCH_TO_LONGPRESS", //            = 4;
        "RELEASE_SINGLE_TAP", //             = 5;
        "REQUEST_FORM_DATA", //              = 6;
        "RESUME_WEBCORE_PRIORITY", //        = 7;
        "DRAG_HELD_MOTIONLESS", //           = 8;
        "", //             = 9;
        "PREVENT_DEFAULT_TIMEOUT", //        = 10;
        "SCROLL_SELECT_TEXT" //              = 11;
    };

    static final String[] HandlerPackageDebugString = {
        "SCROLL_TO_MSG_ID", //               = 101;
        "102", //                            = 102;
        "103", //                            = 103;
        "104", //                            = 104;
        "NEW_PICTURE_MSG_ID", //             = 105;
        "UPDATE_TEXT_ENTRY_MSG_ID", //       = 106;
        "WEBCORE_INITIALIZED_MSG_ID", //     = 107;
        "UPDATE_TEXTFIELD_TEXT_MSG_ID", //   = 108;
        "UPDATE_ZOOM_RANGE", //              = 109;
        "UNHANDLED_NAV_KEY", //              = 110;
        "CLEAR_TEXT_ENTRY", //               = 111;
        "UPDATE_TEXT_SELECTION_MSG_ID", //   = 112;
        "SHOW_RECT_MSG_ID", //               = 113;
        "LONG_PRESS_CENTER", //              = 114;
        "PREVENT_TOUCH_ID", //               = 115;
        "WEBCORE_NEED_TOUCH_EVENTS", //      = 116;
        "INVAL_RECT_MSG_ID", //              = 117;
        "REQUEST_KEYBOARD", //               = 118;
        "DO_MOTION_UP", //                   = 119;
        "SHOW_FULLSCREEN", //                = 120;
        "HIDE_FULLSCREEN", //                = 121;
        "DOM_FOCUS_CHANGED", //              = 122;
        "REPLACE_BASE_CONTENT", //           = 123;
        "RETURN_LABEL", //                   = 125;
        "UPDATE_MATCH_COUNT", //             = 126;
        "CENTER_FIT_RECT", //                = 127;
        "REQUEST_KEYBOARD_WITH_SELECTION_MSG_ID", // = 128;
        "SET_SCROLLBAR_MODES", //            = 129;
        "SELECTION_STRING_CHANGED", //       = 130;
        "SET_TOUCH_HIGHLIGHT_RECTS", //      = 131;
        "SAVE_WEBARCHIVE_FINISHED", //       = 132;
        "SET_AUTOFILLABLE", //               = 133;
        "AUTOFILL_COMPLETE", //              = 134;
        "SELECT_AT", //                      = 135;
        "SCREEN_ON", //                      = 136;
        "ENTER_FULLSCREEN_VIDEO", //         = 137;
        "UPDATE_SELECTION", //               = 138;
        "UPDATE_ZOOM_DENSITY" //             = 139;
    };

    // If the site doesn't use the viewport meta tag to specify the viewport,
    // use DEFAULT_VIEWPORT_WIDTH as the default viewport width
    static final int DEFAULT_VIEWPORT_WIDTH = 980;

    // normally we try to fit the content to the minimum preferred width
    // calculated by the Webkit. To avoid the bad behavior when some site's
    // minimum preferred width keeps growing when changing the viewport width or
    // the minimum preferred width is huge, an upper limit is needed.
    static int sMaxViewportWidth = DEFAULT_VIEWPORT_WIDTH;

    // initial scale in percent. 0 means using default.
    private int mInitialScaleInPercent = 0;

    // Whether or not a scroll event should be sent to webkit.  This is only set
    // to false when restoring the scroll position.
    private boolean mSendScrollEvent = true;

    private int mSnapScrollMode = SNAP_NONE;
    private static final int SNAP_NONE = 0;
    private static final int SNAP_LOCK = 1; // not a separate state
    private static final int SNAP_X = 2; // may be combined with SNAP_LOCK
    private static final int SNAP_Y = 4; // may be combined with SNAP_LOCK
    private boolean mSnapPositive;

    // keep these in sync with their counterparts in WebView.cpp
    private static final int DRAW_EXTRAS_NONE = 0;
    private static final int DRAW_EXTRAS_SELECTION = 1;
    private static final int DRAW_EXTRAS_CURSOR_RING = 2;

    // keep this in sync with WebCore:ScrollbarMode in WebKit
    private static final int SCROLLBAR_AUTO = 0;
    private static final int SCROLLBAR_ALWAYSOFF = 1;
    // as we auto fade scrollbar, this is ignored.
    private static final int SCROLLBAR_ALWAYSON = 2;
    private int mHorizontalScrollBarMode = SCROLLBAR_AUTO;
    private int mVerticalScrollBarMode = SCROLLBAR_AUTO;

    /**
     * Max distance to overscroll by in pixels.
     * This how far content can be pulled beyond its normal bounds by the user.
     */
    private int mOverscrollDistance;

    /**
     * Max distance to overfling by in pixels.
     * This is how far flinged content can move beyond the end of its normal bounds.
     */
    private int mOverflingDistance;

    private OverScrollGlow mOverScrollGlow;

    // Used to match key downs and key ups
    private Vector<Integer> mKeysPressed;

    /* package */ static boolean mLogEvent = true;

    // for event log
    private long mLastTouchUpTime = 0;

    private WebViewCore.AutoFillData mAutoFillData;

    private static boolean sNotificationsEnabled = true;

    /**
     * URI scheme for telephone number
     */
    public static final String SCHEME_TEL = "tel:";
    /**
     * URI scheme for email address
     */
    public static final String SCHEME_MAILTO = "mailto:";
    /**
     * URI scheme for map address
     */
    public static final String SCHEME_GEO = "geo:0,0?q=";

    private int mBackgroundColor = Color.WHITE;

    private static final long SELECT_SCROLL_INTERVAL = 1000 / 60; // 60 / second
    private int mAutoScrollX = 0;
    private int mAutoScrollY = 0;
    private int mMinAutoScrollX = 0;
    private int mMaxAutoScrollX = 0;
    private int mMinAutoScrollY = 0;
    private int mMaxAutoScrollY = 0;
    private Rect mScrollingLayerBounds = new Rect();
    private boolean mSentAutoScrollMessage = false;

    // used for serializing asynchronously handled touch events.
    private WebViewInputDispatcher mInputDispatcher;

    // Used to track whether picture updating was paused due to a window focus change.
    private boolean mPictureUpdatePausedForFocusChange = false;

    // Used to notify listeners of a new picture.
    private PictureListener mPictureListener;

    // Used to notify listeners about find-on-page results.
    private WebView.FindListener mFindListener;

    // Used to prevent resending save password message
    private Message mResumeMsg;

    /**
     * Refer to {@link WebView#requestFocusNodeHref(Message)} for more information
     */
    static class FocusNodeHref {
        static final String TITLE = "title";
        static final String URL = "url";
        static final String SRC = "src";
    }

    public WebViewClassic(WebView webView, WebView.PrivateAccess privateAccess) {
        mWebView = webView;
        mWebViewPrivate = privateAccess;
        mContext = webView.getContext();
    }

    /**
     * See {@link WebViewProvider#init(Map, boolean)}
     */
    @Override
    public void init(Map<String, Object> javaScriptInterfaces, boolean privateBrowsing) {
        Context context = mContext;

        // Used by the chrome stack to find application paths
        JniUtil.setContext(context);

        mCallbackProxy = new CallbackProxy(context, this);
        mViewManager = new ViewManager(this);
        L10nUtils.setApplicationContext(context.getApplicationContext());
        mWebViewCore = new WebViewCore(context, this, mCallbackProxy, javaScriptInterfaces);
        mDatabase = WebViewDatabaseClassic.getInstance(context);
        mScroller = new OverScroller(context, null, 0, 0, false); //TODO Use OverScroller's flywheel
        mZoomManager = new ZoomManager(this, mCallbackProxy);

        /* The init method must follow the creation of certain member variables,
         * such as the mZoomManager.
         */
        init();
        setupPackageListener(context);
        setupProxyListener(context);
        setupTrustStorageListener(context);
        updateMultiTouchSupport(context);

        if (privateBrowsing) {
            startPrivateBrowsing();
        }

        mAutoFillData = new WebViewCore.AutoFillData();
        mEditTextScroller = new Scroller(context);
    }

    // WebViewProvider bindings

    static class Factory implements WebViewFactoryProvider,  WebViewFactoryProvider.Statics {
        @Override
        public String findAddress(String addr) {
            return WebViewClassic.findAddress(addr);
        }
        @Override
        public void setPlatformNotificationsEnabled(boolean enable) {
            if (enable) {
                WebViewClassic.enablePlatformNotifications();
            } else {
                WebViewClassic.disablePlatformNotifications();
            }
        }

        @Override
        public Statics getStatics() { return this; }

        @Override
        public WebViewProvider createWebView(WebView webView, WebView.PrivateAccess privateAccess) {
            return new WebViewClassic(webView, privateAccess);
        }

        @Override
        public GeolocationPermissions getGeolocationPermissions() {
            return GeolocationPermissionsClassic.getInstance();
        }

        @Override
        public CookieManager getCookieManager() {
            return CookieManagerClassic.getInstance();
        }

        @Override
        public WebIconDatabase getWebIconDatabase() {
            return WebIconDatabaseClassic.getInstance();
        }

        @Override
        public WebStorage getWebStorage() {
            return WebStorageClassic.getInstance();
        }

        @Override
        public WebViewDatabase getWebViewDatabase(Context context) {
            return WebViewDatabaseClassic.getInstance(context);
        }

        @Override
        public String getDefaultUserAgent(Context context) {
            return WebSettingsClassic.getDefaultUserAgentForLocale(context,
                    Locale.getDefault());
        }
    }

    private void onHandleUiEvent(MotionEvent event, int eventType, int flags) {
        switch (eventType) {
        case WebViewInputDispatcher.EVENT_TYPE_LONG_PRESS:
            HitTestResult hitTest = getHitTestResult();
            if (hitTest != null) {
                mWebView.performLongClick();
            }
            break;
        case WebViewInputDispatcher.EVENT_TYPE_DOUBLE_TAP:
            mZoomManager.handleDoubleTap(event.getX(), event.getY());
            break;
        case WebViewInputDispatcher.EVENT_TYPE_TOUCH:
            onHandleUiTouchEvent(event);
            break;
        case WebViewInputDispatcher.EVENT_TYPE_CLICK:
            if (mFocusedNode != null && mFocusedNode.mIntentUrl != null) {
                mWebView.playSoundEffect(SoundEffectConstants.CLICK);
                overrideLoading(mFocusedNode.mIntentUrl);
            }
            break;
        }
    }

    private void onHandleUiTouchEvent(MotionEvent ev) {
        final ScaleGestureDetector detector =
                mZoomManager.getScaleGestureDetector();

        int action = ev.getActionMasked();
        final boolean pointerUp = action == MotionEvent.ACTION_POINTER_UP;
        final boolean configChanged =
            action == MotionEvent.ACTION_POINTER_UP ||
            action == MotionEvent.ACTION_POINTER_DOWN;
        final int skipIndex = pointerUp ? ev.getActionIndex() : -1;

        // Determine focal point
        float sumX = 0, sumY = 0;
        final int count = ev.getPointerCount();
        for (int i = 0; i < count; i++) {
            if (skipIndex == i) continue;
            sumX += ev.getX(i);
            sumY += ev.getY(i);
        }
        final int div = pointerUp ? count - 1 : count;
        float x = sumX / div;
        float y = sumY / div;

        if (configChanged) {
            mLastTouchX = Math.round(x);
            mLastTouchY = Math.round(y);
            mLastTouchTime = ev.getEventTime();
            mWebView.cancelLongPress();
            mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
        }

        if (detector != null) {
            detector.onTouchEvent(ev);
            if (detector.isInProgress()) {
                mLastTouchTime = ev.getEventTime();

                if (!mZoomManager.supportsPanDuringZoom()) {
                    return;
                }
                mTouchMode = TOUCH_DRAG_MODE;
                if (mVelocityTracker == null) {
                    mVelocityTracker = VelocityTracker.obtain();
                }
            }
        }

        if (action == MotionEvent.ACTION_POINTER_DOWN) {
            cancelTouch();
            action = MotionEvent.ACTION_DOWN;
        } else if (action == MotionEvent.ACTION_MOVE) {
            // negative x or y indicate it is on the edge, skip it.
            if (x < 0 || y < 0) {
                return;
            }
        }

        handleTouchEventCommon(ev, action, Math.round(x), Math.round(y));
    }

    // The webview that is bound to this WebViewClassic instance. Primarily needed for supplying
    // as the first param in the WebViewClient and WebChromeClient callbacks.
    final private WebView mWebView;
    // Callback interface, provides priviledged access into the WebView instance.
    final private WebView.PrivateAccess mWebViewPrivate;
    // Cached reference to mWebView.getContext(), for convenience.
    final private Context mContext;

    /**
     * @return The webview proxy that this classic webview is bound to.
     */
    public WebView getWebView() {
        return mWebView;
    }

    @Override
    public ViewDelegate getViewDelegate() {
        return this;
    }

    @Override
    public ScrollDelegate getScrollDelegate() {
        return this;
    }

    public static WebViewClassic fromWebView(WebView webView) {
        return webView == null ? null : (WebViewClassic) webView.getWebViewProvider();
    }

    // Accessors, purely for convenience (and to reduce code churn during webview proxy migration).
    int getScrollX() {
        return mWebView.getScrollX();
    }

    int getScrollY() {
        return mWebView.getScrollY();
    }

    int getWidth() {
        return mWebView.getWidth();
    }

    int getHeight() {
        return mWebView.getHeight();
    }

    Context getContext() {
        return mContext;
    }

    void invalidate() {
        mWebView.invalidate();
    }

    // Setters for the Scroll X & Y, without invoking the onScrollChanged etc code paths.
    void setScrollXRaw(int mScrollX) {
        mWebViewPrivate.setScrollXRaw(mScrollX);
    }

    void setScrollYRaw(int mScrollY) {
        mWebViewPrivate.setScrollYRaw(mScrollY);
    }

    private static class TrustStorageListener extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(KeyChain.ACTION_STORAGE_CHANGED)) {
                handleCertTrustChanged();
            }
        }
    }
    private static TrustStorageListener sTrustStorageListener;

    /**
     * Handles update to the trust storage.
     */
    private static void handleCertTrustChanged() {
        // send a message for indicating trust storage change
        WebViewCore.sendStaticMessage(EventHub.TRUST_STORAGE_UPDATED, null);
    }

    /*
     * @param context This method expects this to be a valid context.
     */
    private static void setupTrustStorageListener(Context context) {
        if (sTrustStorageListener != null ) {
            return;
        }
        IntentFilter filter = new IntentFilter();
        filter.addAction(KeyChain.ACTION_STORAGE_CHANGED);
        sTrustStorageListener = new TrustStorageListener();
        Intent current =
            context.getApplicationContext().registerReceiver(sTrustStorageListener, filter);
        if (current != null) {
            handleCertTrustChanged();
        }
    }

    private static class ProxyReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(Proxy.PROXY_CHANGE_ACTION)) {
                handleProxyBroadcast(intent);
            }
        }
    }

    /*
     * Receiver for PROXY_CHANGE_ACTION, will be null when it is not added handling broadcasts.
     */
    private static ProxyReceiver sProxyReceiver;

    /*
     * @param context This method expects this to be a valid context
     */
    private static synchronized void setupProxyListener(Context context) {
        if (sProxyReceiver != null || sNotificationsEnabled == false) {
            return;
        }
        IntentFilter filter = new IntentFilter();
        filter.addAction(Proxy.PROXY_CHANGE_ACTION);
        sProxyReceiver = new ProxyReceiver();
        Intent currentProxy = context.getApplicationContext().registerReceiver(
                sProxyReceiver, filter);
        if (currentProxy != null) {
            handleProxyBroadcast(currentProxy);
        }
    }

    /*
     * @param context This method expects this to be a valid context
     */
    private static synchronized void disableProxyListener(Context context) {
        if (sProxyReceiver == null)
            return;

        context.getApplicationContext().unregisterReceiver(sProxyReceiver);
        sProxyReceiver = null;
    }

    private static void handleProxyBroadcast(Intent intent) {
        ProxyProperties proxyProperties = (ProxyProperties)intent.getExtra(Proxy.EXTRA_PROXY_INFO);
        if (proxyProperties == null || proxyProperties.getHost() == null) {
            WebViewCore.sendStaticMessage(EventHub.PROXY_CHANGED, null);
            return;
        }
        WebViewCore.sendStaticMessage(EventHub.PROXY_CHANGED, proxyProperties);
    }

    /*
     * A variable to track if there is a receiver added for ACTION_PACKAGE_ADDED
     * or ACTION_PACKAGE_REMOVED.
     */
    private static boolean sPackageInstallationReceiverAdded = false;

    /*
     * A set of Google packages we monitor for the
     * navigator.isApplicationInstalled() API. Add additional packages as
     * needed.
     */
    private static Set<String> sGoogleApps;
    static {
        sGoogleApps = new HashSet<String>();
        sGoogleApps.add("com.google.android.youtube");
    }

    private static class PackageListener extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            final String packageName = intent.getData().getSchemeSpecificPart();
            final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
            if (Intent.ACTION_PACKAGE_REMOVED.equals(action) && replacing) {
                // if it is replacing, refreshPlugins() when adding
                return;
            }

            if (sGoogleApps.contains(packageName)) {
                if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
                    WebViewCore.sendStaticMessage(EventHub.ADD_PACKAGE_NAME, packageName);
                } else {
                    WebViewCore.sendStaticMessage(EventHub.REMOVE_PACKAGE_NAME, packageName);
                }
            }

            PluginManager pm = PluginManager.getInstance(context);
            if (pm.containsPluginPermissionAndSignatures(packageName)) {
                pm.refreshPlugins(Intent.ACTION_PACKAGE_ADDED.equals(action));
            }
        }
    }

    private void setupPackageListener(Context context) {

        /*
         * we must synchronize the instance check and the creation of the
         * receiver to ensure that only ONE receiver exists for all WebView
         * instances.
         */
        synchronized (WebViewClassic.class) {

            // if the receiver already exists then we do not need to register it
            // again
            if (sPackageInstallationReceiverAdded) {
                return;
            }

            IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
            filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
            filter.addDataScheme("package");
            BroadcastReceiver packageListener = new PackageListener();
            context.getApplicationContext().registerReceiver(packageListener, filter);
            sPackageInstallationReceiverAdded = true;
        }

        // check if any of the monitored apps are already installed
        AsyncTask<Void, Void, Set<String>> task = new AsyncTask<Void, Void, Set<String>>() {

            @Override
            protected Set<String> doInBackground(Void... unused) {
                Set<String> installedPackages = new HashSet<String>();
                PackageManager pm = mContext.getPackageManager();
                for (String name : sGoogleApps) {
                    try {
                        pm.getPackageInfo(name,
                                PackageManager.GET_ACTIVITIES | PackageManager.GET_SERVICES);
                        installedPackages.add(name);
                    } catch (PackageManager.NameNotFoundException e) {
                        // package not found
                    }
                }
                return installedPackages;
            }

            // Executes on the UI thread
            @Override
            protected void onPostExecute(Set<String> installedPackages) {
                if (mWebViewCore != null) {
                    mWebViewCore.sendMessage(EventHub.ADD_PACKAGE_NAMES, installedPackages);
                }
            }
        };
        task.execute();
    }

    void updateMultiTouchSupport(Context context) {
        mZoomManager.updateMultiTouchSupport(context);
    }

    void updateJavaScriptEnabled(boolean enabled) {
        if (isAccessibilityInjectionEnabled()) {
            getAccessibilityInjector().updateJavaScriptEnabled(enabled);
        }
    }

    private void init() {
        OnTrimMemoryListener.init(mContext);
        mWebView.setWillNotDraw(false);
        mWebView.setClickable(true);
        mWebView.setLongClickable(true);

        final ViewConfiguration configuration = ViewConfiguration.get(mContext);
        int slop = configuration.getScaledTouchSlop();
        mTouchSlopSquare = slop * slop;
        slop = configuration.getScaledDoubleTapSlop();
        mDoubleTapSlopSquare = slop * slop;
        final float density = WebViewCore.getFixedDisplayDensity(mContext);
        // use one line height, 16 based on our current default font, for how
        // far we allow a touch be away from the edge of a link
        mNavSlop = (int) (16 * density);
        mZoomManager.init(density);
        mMaximumFling = configuration.getScaledMaximumFlingVelocity();

        // Compute the inverse of the density squared.
        DRAG_LAYER_INVERSE_DENSITY_SQUARED = 1 / (density * density);

        mOverscrollDistance = configuration.getScaledOverscrollDistance();
        mOverflingDistance = configuration.getScaledOverflingDistance();

        setScrollBarStyle(mWebViewPrivate.super_getScrollBarStyle());
        // Initially use a size of two, since the user is likely to only hold
        // down two keys at a time (shift + another key)
        mKeysPressed = new Vector<Integer>(2);
        mHTML5VideoViewProxy = null ;
    }

    @Override
    public boolean shouldDelayChildPressedState() {
        return true;
    }

    @Override
    public boolean performAccessibilityAction(int action, Bundle arguments) {
        if (!mWebView.isEnabled()) {
            // Only default actions are supported while disabled.
            return mWebViewPrivate.super_performAccessibilityAction(action, arguments);
        }

        if (getAccessibilityInjector().supportsAccessibilityAction(action)) {
            return getAccessibilityInjector().performAccessibilityAction(action, arguments);
        }

        switch (action) {
            case AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD:
            case AccessibilityNodeInfo.ACTION_SCROLL_FORWARD: {
                final int convertedContentHeight = contentToViewY(getContentHeight());
                final int adjustedViewHeight = getHeight() - mWebView.getPaddingTop()
                        - mWebView.getPaddingBottom();
                final int maxScrollY = Math.max(convertedContentHeight - adjustedViewHeight, 0);
                final boolean canScrollBackward = (getScrollY() > 0);
                final boolean canScrollForward = ((getScrollY() - maxScrollY) > 0);
                if ((action == AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD) && canScrollBackward) {
                    mWebView.scrollBy(0, adjustedViewHeight);
                    return true;
                }
                if ((action == AccessibilityNodeInfo.ACTION_SCROLL_FORWARD) && canScrollForward) {
                    mWebView.scrollBy(0, -adjustedViewHeight);
                    return true;
                }
                return false;
            }
        }

        return mWebViewPrivate.super_performAccessibilityAction(action, arguments);
    }

    @Override
    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
        if (!mWebView.isEnabled()) {
            // Only default actions are supported while disabled.
            return;
        }

        info.setScrollable(isScrollableForAccessibility());

        final int convertedContentHeight = contentToViewY(getContentHeight());
        final int adjustedViewHeight = getHeight() - mWebView.getPaddingTop()
                - mWebView.getPaddingBottom();
        final int maxScrollY = Math.max(convertedContentHeight - adjustedViewHeight, 0);
        final boolean canScrollBackward = (getScrollY() > 0);
        final boolean canScrollForward = ((getScrollY() - maxScrollY) > 0);

        if (canScrollForward) {
            info.addAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD);
        }

        if (canScrollForward) {
            info.addAction(AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD);
        }

        getAccessibilityInjector().onInitializeAccessibilityNodeInfo(info);
    }

    @Override
    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
        event.setScrollable(isScrollableForAccessibility());
        event.setScrollX(getScrollX());
        event.setScrollY(getScrollY());
        final int convertedContentWidth = contentToViewX(getContentWidth());
        final int adjustedViewWidth = getWidth() - mWebView.getPaddingLeft()
                - mWebView.getPaddingLeft();
        event.setMaxScrollX(Math.max(convertedContentWidth - adjustedViewWidth, 0));
        final int convertedContentHeight = contentToViewY(getContentHeight());
        final int adjustedViewHeight = getHeight() - mWebView.getPaddingTop()
                - mWebView.getPaddingBottom();
        event.setMaxScrollY(Math.max(convertedContentHeight - adjustedViewHeight, 0));
    }

    private boolean isAccessibilityInjectionEnabled() {
        final AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
        if (!manager.isEnabled()) {
            return false;
        }

        // Accessibility scripts should be injected only when a speaking service
        // is enabled. This may need to change later to accommodate Braille.
        final List<AccessibilityServiceInfo> services = manager.getEnabledAccessibilityServiceList(
                AccessibilityServiceInfo.FEEDBACK_SPOKEN);
        if (services.isEmpty()) {
            return false;
        }

        return true;
    }

    private AccessibilityInjector getAccessibilityInjector() {
        if (mAccessibilityInjector == null) {
            mAccessibilityInjector = new AccessibilityInjector(this);
        }
        return mAccessibilityInjector;
    }

    private boolean isScrollableForAccessibility() {
        return (contentToViewX(getContentWidth()) > getWidth() - mWebView.getPaddingLeft()
                - mWebView.getPaddingRight()
                || contentToViewY(getContentHeight()) > getHeight() - mWebView.getPaddingTop()
                - mWebView.getPaddingBottom());
    }

    @Override
    public void setOverScrollMode(int mode) {
        if (mode != View.OVER_SCROLL_NEVER) {
            if (mOverScrollGlow == null) {
                mOverScrollGlow = new OverScrollGlow(this);
            }
        } else {
            mOverScrollGlow = null;
        }
    }

    /* package */ void adjustDefaultZoomDensity(int zoomDensity) {
        final float density = WebViewCore.getFixedDisplayDensity(mContext)
                * 100 / zoomDensity;
        updateDefaultZoomDensity(density);
    }

    /* package */ void updateDefaultZoomDensity(float density) {
        mNavSlop = (int) (16 * density);
        mZoomManager.updateDefaultZoomDensity(density);
    }

    /* package */ int getScaledNavSlop() {
        return viewToContentDimension(mNavSlop);
    }

    /* package */ boolean onSavePassword(String schemePlusHost, String username,
            String password, final Message resumeMsg) {
        boolean rVal = false;
        if (resumeMsg == null) {
            // null resumeMsg implies saving password silently
            mDatabase.setUsernamePassword(schemePlusHost, username, password);
        } else {
            if (mResumeMsg != null) {
                Log.w(LOGTAG, "onSavePassword should not be called while dialog is up");
                resumeMsg.sendToTarget();
                return true;
            }
            mResumeMsg = resumeMsg;
            final Message remember = mPrivateHandler.obtainMessage(
                    REMEMBER_PASSWORD);
            remember.getData().putString("host", schemePlusHost);
            remember.getData().putString("username", username);
            remember.getData().putString("password", password);
            remember.obj = resumeMsg;

            final Message neverRemember = mPrivateHandler.obtainMessage(
                    NEVER_REMEMBER_PASSWORD);
            neverRemember.getData().putString("host", schemePlusHost);
            neverRemember.getData().putString("username", username);
            neverRemember.getData().putString("password", password);
            neverRemember.obj = resumeMsg;

            mSavePasswordDialog = new AlertDialog.Builder(mContext)
                    .setTitle(com.android.internal.R.string.save_password_label)
                    .setMessage(com.android.internal.R.string.save_password_message)
                    .setPositiveButton(com.android.internal.R.string.save_password_notnow,
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            if (mResumeMsg != null) {
                                resumeMsg.sendToTarget();
                                mResumeMsg = null;
                            }
                            mSavePasswordDialog = null;
                        }
                    })
                    .setNeutralButton(com.android.internal.R.string.save_password_remember,
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            if (mResumeMsg != null) {
                                remember.sendToTarget();
                                mResumeMsg = null;
                            }
                            mSavePasswordDialog = null;
                        }
                    })
                    .setNegativeButton(com.android.internal.R.string.save_password_never,
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            if (mResumeMsg != null) {
                                neverRemember.sendToTarget();
                                mResumeMsg = null;
                            }
                            mSavePasswordDialog = null;
                        }
                    })
                    .setOnDismissListener(new DialogInterface.OnDismissListener() {
                        @Override
                        public void onDismiss(DialogInterface dialog) {
                            if (mResumeMsg != null) {
                                resumeMsg.sendToTarget();
                                mResumeMsg = null;
                            }
                            mSavePasswordDialog = null;
                        }
                    }).show();
            // Return true so that WebViewCore will pause while the dialog is
            // up.
            rVal = true;
        }
        return rVal;
    }

    @Override
    public void setScrollBarStyle(int style) {
        if (style == View.SCROLLBARS_INSIDE_INSET
                || style == View.SCROLLBARS_OUTSIDE_INSET) {
            mOverlayHorizontalScrollbar = mOverlayVerticalScrollbar = false;
        } else {
            mOverlayHorizontalScrollbar = mOverlayVerticalScrollbar = true;
        }
    }

    /**
     * See {@link WebView#setHorizontalScrollbarOverlay(boolean)}
     */
    @Override
    public void setHorizontalScrollbarOverlay(boolean overlay) {
        mOverlayHorizontalScrollbar = overlay;
    }

    /**
     * See {@link WebView#setVerticalScrollbarOverlay(boolean)
     */
    @Override
    public void setVerticalScrollbarOverlay(boolean overlay) {
        mOverlayVerticalScrollbar = overlay;
    }

    /**
     * See {@link WebView#overlayHorizontalScrollbar()}
     */
    @Override
    public boolean overlayHorizontalScrollbar() {
        return mOverlayHorizontalScrollbar;
    }

    /**
     * See {@link WebView#overlayVerticalScrollbar()}
     */
    @Override
    public boolean overlayVerticalScrollbar() {
        return mOverlayVerticalScrollbar;
    }

    /*
     * Return the width of the view where the content of WebView should render
     * to.
     * Note: this can be called from WebCoreThread.
     */
    /* package */ int getViewWidth() {
        if (!mWebView.isVerticalScrollBarEnabled() || mOverlayVerticalScrollbar) {
            return getWidth();
        } else {
            return Math.max(0, getWidth() - mWebView.getVerticalScrollbarWidth());
        }
    }

    // Interface to enable the browser to override title bar handling.
    public interface TitleBarDelegate {
        int getTitleHeight();
        public void onSetEmbeddedTitleBar(final View title);
    }

    /**
     * Returns the height (in pixels) of the embedded title bar (if any). Does not care about
     * scrolling
     */
    protected int getTitleHeight() {
        if (mWebView instanceof TitleBarDelegate) {
            return ((TitleBarDelegate) mWebView).getTitleHeight();
        }
        return 0;
    }

    /**
     * See {@link WebView#getVisibleTitleHeight()}
     */
    @Override
    @Deprecated
    public int getVisibleTitleHeight() {
        // Actually, this method returns the height of the embedded title bar if one is set via the
        // hidden setEmbeddedTitleBar method.
        return getVisibleTitleHeightImpl();
    }

    private int getVisibleTitleHeightImpl() {
        // need to restrict mScrollY due to over scroll
        return Math.max(getTitleHeight() - Math.max(0, getScrollY()),
                getOverlappingActionModeHeight());
    }

    private int mCachedOverlappingActionModeHeight = -1;

    private int getOverlappingActionModeHeight() {
        if (mFindCallback == null) {
            return 0;
        }
        if (mCachedOverlappingActionModeHeight < 0) {
            mWebView.getGlobalVisibleRect(mGlobalVisibleRect, mGlobalVisibleOffset);
            mCachedOverlappingActionModeHeight = Math.max(0,
                    mFindCallback.getActionModeGlobalBottom() - mGlobalVisibleRect.top);
        }
        return mCachedOverlappingActionModeHeight;
    }

    /*
     * Return the height of the view where the content of WebView should render
     * to.  Note that this excludes mTitleBar, if there is one.
     * Note: this can be called from WebCoreThread.
     */
    /* package */ int getViewHeight() {
        return getViewHeightWithTitle() - getVisibleTitleHeightImpl();
    }

    int getViewHeightWithTitle() {
        int height = getHeight();
        if (mWebView.isHorizontalScrollBarEnabled() && !mOverlayHorizontalScrollbar) {
            height -= mWebViewPrivate.getHorizontalScrollbarHeight();
        }
        return height;
    }

    /**
     * See {@link WebView#getCertificate()}
     */
    @Override
    public SslCertificate getCertificate() {
        return mCertificate;
    }

    /**
     * See {@link WebView#setCertificate(SslCertificate)}
     */
    @Override
    public void setCertificate(SslCertificate certificate) {
        if (DebugFlags.WEB_VIEW) {
            Log.v(LOGTAG, "setCertificate=" + certificate);
        }
        // here, the certificate can be null (if the site is not secure)
        mCertificate = certificate;
    }

    //-------------------------------------------------------------------------
    // Methods called by activity
    //-------------------------------------------------------------------------

    /**
     * See {@link WebView#savePassword(String, String, String)}
     */
    @Override
    public void savePassword(String host, String username, String password) {
        mDatabase.setUsernamePassword(host, username, password);
    }

    /**
     * See {@link WebView#setHttpAuthUsernamePassword(String, String, String, String)}
     */
    @Override
    public void setHttpAuthUsernamePassword(String host, String realm,
            String username, String password) {
        mDatabase.setHttpAuthUsernamePassword(host, realm, username, password);
    }

    /**
     * See {@link WebView#getHttpAuthUsernamePassword(String, String)}
     */
    @Override
    public String[] getHttpAuthUsernamePassword(String host, String realm) {
        return mDatabase.getHttpAuthUsernamePassword(host, realm);
    }

    /**
     * Remove Find or Select ActionModes, if active.
     */
    private void clearActionModes() {
        if (mSelectCallback != null) {
            mSelectCallback.finish();
        }
        if (mFindCallback != null) {
            mFindCallback.finish();
        }
    }

    /**
     * Called to clear state when moving from one page to another, or changing
     * in some other way that makes elements associated with the current page
     * (such as ActionModes) no longer relevant.
     */
    private void clearHelpers() {
        hideSoftKeyboard();
        clearActionModes();
        dismissFullScreenMode();
        cancelDialogs();
    }

    private void cancelDialogs() {
        if (mListBoxDialog != null) {
            mListBoxDialog.cancel();
            mListBoxDialog = null;
        }
        if (mSavePasswordDialog != null) {
            mSavePasswordDialog.dismiss();
            mSavePasswordDialog = null;
        }
    }

    /**
     * See {@link WebView#destroy()}
     */
    @Override
    public void destroy() {
        if (mWebView.getViewRootImpl() != null) {
            Log.e(LOGTAG, "Error: WebView.destroy() called while still attached!");
        }
        ensureFunctorDetached();
        destroyJava();
        destroyNative();
    }

    private void ensureFunctorDetached() {
        if (mWebView.isHardwareAccelerated()) {
            int drawGLFunction = nativeGetDrawGLFunction(mNativeClass);
            ViewRootImpl viewRoot = mWebView.getViewRootImpl();
            if (drawGLFunction != 0 && viewRoot != null) {
                viewRoot.detachFunctor(drawGLFunction);
            }
        }
    }

    private void destroyJava() {
        mCallbackProxy.blockMessages();
        if (mWebViewCore != null) {
            // Tell WebViewCore to destroy itself
            synchronized (this) {
                WebViewCore webViewCore = mWebViewCore;
                mWebViewCore = null; // prevent using partial webViewCore
                webViewCore.destroy();
            }
            // Remove any pending messages that might not be serviced yet.
            mPrivateHandler.removeCallbacksAndMessages(null);
        }
    }

    private void destroyNative() {
        if (mNativeClass == 0) return;
        int nptr = mNativeClass;
        mNativeClass = 0;
        if (Thread.currentThread() == mPrivateHandler.getLooper().getThread()) {
            // We are on the main thread and can safely delete
            nativeDestroy(nptr);
        } else {
            mPrivateHandler.post(new DestroyNativeRunnable(nptr));
        }
    }

    private static class DestroyNativeRunnable implements Runnable {

        private int mNativePtr;

        public DestroyNativeRunnable(int nativePtr) {
            mNativePtr = nativePtr;
        }

        @Override
        public void run() {
            // nativeDestroy also does a stopGL()
            nativeDestroy(mNativePtr);
        }

    }

    /**
     * See {@link WebView#enablePlatformNotifications()}
     */
    @Deprecated
    public static void enablePlatformNotifications() {
        synchronized (WebViewClassic.class) {
            sNotificationsEnabled = true;
            Context context = JniUtil.getContext();
            if (context != null)
                setupProxyListener(context);
        }
    }

    /**
     * See {@link WebView#disablePlatformNotifications()}
     */
    @Deprecated
    public static void disablePlatformNotifications() {
        synchronized (WebViewClassic.class) {
            sNotificationsEnabled = false;
            Context context = JniUtil.getContext();
            if (context != null)
                disableProxyListener(context);
        }
    }

    /**
     * Sets JavaScript engine flags.
     *
     * @param flags JS engine flags in a String
     *
     * This is an implementation detail.
     */
    public void setJsFlags(String flags) {
        mWebViewCore.sendMessage(EventHub.SET_JS_FLAGS, flags);
    }

    /**
     * See {@link WebView#setNetworkAvailable(boolean)}
     */
    @Override
    public void setNetworkAvailable(boolean networkUp) {
        mWebViewCore.sendMessage(EventHub.SET_NETWORK_STATE,
                networkUp ? 1 : 0, 0);
    }

    /**
     * Inform WebView about the current network type.
     */
    public void setNetworkType(String type, String subtype) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("type", type);
        map.put("subtype", subtype);
        mWebViewCore.sendMessage(EventHub.SET_NETWORK_TYPE, map);
    }

    /**
     * See {@link WebView#saveState(Bundle)}
     */
    @Override
    public WebBackForwardList saveState(Bundle outState) {
        if (outState == null) {
            return null;
        }
        // We grab a copy of the back/forward list because a client of WebView
        // may have invalidated the history list by calling clearHistory.
        WebBackForwardListClassic list = copyBackForwardList();
        final int currentIndex = list.getCurrentIndex();
        final int size = list.getSize();
        // We should fail saving the state if the list is empty or the index is
        // not in a valid range.
        if (currentIndex < 0 || currentIndex >= size || size == 0) {
            return null;
        }
        outState.putInt("index", currentIndex);
        // FIXME: This should just be a byte[][] instead of ArrayList but
        // Parcel.java does not have the code to handle multi-dimensional
        // arrays.
        ArrayList<byte[]> history = new ArrayList<byte[]>(size);
        for (int i = 0; i < size; i++) {
            WebHistoryItemClassic item = list.getItemAtIndex(i);
            if (null == item) {
                // FIXME: this shouldn't happen
                // need to determine how item got set to null
                Log.w(LOGTAG, "saveState: Unexpected null history item.");
                return null;
            }
            byte[] data = item.getFlattenedData();
            if (data == null) {
                // It would be very odd to not have any data for a given history
                // item. And we will fail to rebuild the history list without
                // flattened data.
                return null;
            }
            history.add(data);
        }
        outState.putSerializable("history", history);
        if (mCertificate != null) {
            outState.putBundle("certificate",
                               SslCertificate.saveState(mCertificate));
        }
        outState.putBoolean("privateBrowsingEnabled", isPrivateBrowsingEnabled());
        mZoomManager.saveZoomState(outState);
        return list;
    }

    /**
     * See {@link WebView#savePicture(Bundle, File)}
     */
    @Override
    @Deprecated
    public boolean savePicture(Bundle b, final File dest) {
        if (dest == null || b == null) {
            return false;
        }
        final Picture p = capturePicture();
        // Use a temporary file while writing to ensure the destination file
        // contains valid data.
        final File temp = new File(dest.getPath() + ".writing");
        new Thread(new Runnable() {
            @Override
            public void run() {
                FileOutputStream out = null;
                try {
                    out = new FileOutputStream(temp);
                    p.writeToStream(out);
                    // Writing the picture succeeded, rename the temporary file
                    // to the destination.
                    temp.renameTo(dest);
                } catch (Exception e) {
                    // too late to do anything about it.
                } finally {
                    if (out != null) {
                        try {
                            out.close();
                        } catch (Exception e) {
                            // Can't do anything about that
                        }
                    }
                    temp.delete();
                }
            }
        }).start();
        // now update the bundle
        b.putInt("scrollX", getScrollX());
        b.putInt("scrollY", getScrollY());
        mZoomManager.saveZoomState(b);
        return true;
    }

    private void restoreHistoryPictureFields(Picture p, Bundle b) {
        int sx = b.getInt("scrollX", 0);
        int sy = b.getInt("scrollY", 0);

        mDrawHistory = true;
        mHistoryPicture = p;

        setScrollXRaw(sx);
        setScrollYRaw(sy);
        mZoomManager.restoreZoomState(b);
        final float scale = mZoomManager.getScale();
        mHistoryWidth = Math.round(p.getWidth() * scale);
        mHistoryHeight = Math.round(p.getHeight() * scale);

        invalidate();
    }

    /**
     * See {@link WebView#restorePicture(Bundle, File)};
     */
    @Override
    @Deprecated
    public boolean restorePicture(Bundle b, File src) {
        if (src == null || b == null) {
            return false;
        }
        if (!src.exists()) {
            return false;
        }
        try {
            final FileInputStream in = new FileInputStream(src);
            final Bundle copy = new Bundle(b);
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        final Picture p = Picture.createFromStream(in);
                        if (p != null) {
                            // Post a runnable on the main thread to update the
                            // history picture fields.
                            mPrivateHandler.post(new Runnable() {
                                @Override
                                public void run() {
                                    restoreHistoryPictureFields(p, copy);
                                }
                            });
                        }
                    } finally {
                        try {
                            in.close();
                        } catch (Exception e) {
                            // Nothing we can do now.
                        }
                    }
                }
            }).start();
        } catch (FileNotFoundException e){
            e.printStackTrace();
        }
        return true;
    }

    /**
     * Saves the view data to the output stream. The output is highly
     * version specific, and may not be able to be loaded by newer versions
     * of WebView.
     * @param stream The {@link OutputStream} to save to
     * @param callback The {@link ValueCallback} to call with the result
     */
    public void saveViewState(OutputStream stream, ValueCallback<Boolean> callback) {
        if (mWebViewCore == null) {
            callback.onReceiveValue(false);
            return;
        }
        mWebViewCore.sendMessageAtFrontOfQueue(EventHub.SAVE_VIEW_STATE,
                new WebViewCore.SaveViewStateRequest(stream, callback));
    }

    /**
     * Loads the view data from the input stream. See
     * {@link #saveViewState(java.io.OutputStream, ValueCallback)} for more information.
     * @param stream The {@link InputStream} to load from
     */
    public void loadViewState(InputStream stream) {
        mBlockWebkitViewMessages = true;
        new AsyncTask<InputStream, Void, DrawData>() {

            @Override
            protected DrawData doInBackground(InputStream... params) {
                try {
                    return ViewStateSerializer.deserializeViewState(params[0]);
                } catch (IOException e) {
                    return null;
                }
            }

            @Override
            protected void onPostExecute(DrawData draw) {
                if (draw == null) {
                    Log.e(LOGTAG, "Failed to load view state!");
                    return;
                }
                int viewWidth = getViewWidth();
                int viewHeight = getViewHeightWithTitle() - getTitleHeight();
                draw.mViewSize = new Point(viewWidth, viewHeight);
                draw.mViewState.mDefaultScale = getDefaultZoomScale();
                mLoadedPicture = draw;
                setNewPicture(mLoadedPicture, true);
                mLoadedPicture.mViewState = null;
            }

        }.execute(stream);
    }

    /**
     * Clears the view state set with {@link #loadViewState(InputStream)}.
     * This WebView will then switch to showing the content from webkit
     */
    public void clearViewState() {
        mBlockWebkitViewMessages = false;
        mLoadedPicture = null;
        invalidate();
    }

    /**
     * See {@link WebView#restoreState(Bundle)}
     */
    @Override
    public WebBackForwardList restoreState(Bundle inState) {
        WebBackForwardListClassic returnList = null;
        if (inState == null) {
            return returnList;
        }
        if (inState.containsKey("index") && inState.containsKey("history")) {
            mCertificate = SslCertificate.restoreState(
                inState.getBundle("certificate"));

            final WebBackForwardListClassic list = mCallbackProxy.getBackForwardList();
            final int index = inState.getInt("index");
            // We can't use a clone of the list because we need to modify the
            // shared copy, so synchronize instead to prevent concurrent
            // modifications.
            synchronized (list) {
                final List<byte[]> history =
                        (List<byte[]>) inState.getSerializable("history");
                final int size = history.size();
                // Check the index bounds so we don't crash in native code while
                // restoring the history index.
                if (index < 0 || index >= size) {
                    return null;
                }
                for (int i = 0; i < size; i++) {
                    byte[] data = history.remove(0);
                    if (data == null) {
                        // If we somehow have null data, we cannot reconstruct
                        // the item and thus our history list cannot be rebuilt.
                        return null;
                    }
                    WebHistoryItem item = new WebHistoryItemClassic(data);
                    list.addHistoryItem(item);
                }
                // Grab the most recent copy to return to the caller.
                returnList = copyBackForwardList();
                // Update the copy to have the correct index.
                returnList.setCurrentIndex(index);
            }
            // Restore private browsing setting.
            if (inState.getBoolean("privateBrowsingEnabled")) {
                getSettings().setPrivateBrowsingEnabled(true);
            }
            mZoomManager.restoreZoomState(inState);
            // Remove all pending messages because we are restoring previous
            // state.
            mWebViewCore.removeMessages();
            // Send a restore state message.
            mWebViewCore.sendMessage(EventHub.RESTORE_STATE, index);
        }
        return returnList;
    }

    /**
     * See {@link WebView#loadUrl(String, Map)}
     */
    @Override
    public void loadUrl(String url, Map<String, String> additionalHttpHeaders) {
        loadUrlImpl(url, additionalHttpHeaders);
    }

    private void loadUrlImpl(String url, Map<String, String> extraHeaders) {
        switchOutDrawHistory();
        WebViewCore.GetUrlData arg = new WebViewCore.GetUrlData();
        arg.mUrl = url;
        arg.mExtraHeaders = extraHeaders;
        mWebViewCore.sendMessage(EventHub.LOAD_URL, arg);
        clearHelpers();
    }

    /**
     * See {@link WebView#loadUrl(String)}
     */
    @Override
    public void loadUrl(String url) {
        loadUrlImpl(url);
    }

    private void loadUrlImpl(String url) {
        if (url == null) {
            return;
        }
        loadUrlImpl(url, null);
    }

    /**
     * See {@link WebView#postUrl(String, byte[])}
     */
    @Override
    public void postUrl(String url, byte[] postData) {
        if (URLUtil.isNetworkUrl(url)) {
            switchOutDrawHistory();
            WebViewCore.PostUrlData arg = new WebViewCore.PostUrlData();
            arg.mUrl = url;
            arg.mPostData = postData;
            mWebViewCore.sendMessage(EventHub.POST_URL, arg);
            clearHelpers();
        } else {
            loadUrlImpl(url);
        }
    }

    /**
     * See {@link WebView#loadData(String, String, String)}
     */
    @Override
    public void loadData(String data, String mimeType, String encoding) {
        loadDataImpl(data, mimeType, encoding);
    }

    private void loadDataImpl(String data, String mimeType, String encoding) {
        StringBuilder dataUrl = new StringBuilder("data:");
        dataUrl.append(mimeType);
        if ("base64".equals(encoding)) {
            dataUrl.append(";base64");
        }
        dataUrl.append(",");
        dataUrl.append(data);
        loadUrlImpl(dataUrl.toString());
    }

    /**
     * See {@link WebView#loadDataWithBaseURL(String, String, String, String, String)}
     */
    @Override
    public void loadDataWithBaseURL(String baseUrl, String data,
            String mimeType, String encoding, String historyUrl) {

        if (baseUrl != null && baseUrl.toLowerCase().startsWith("data:")) {
            loadDataImpl(data, mimeType, encoding);
            return;
        }
        switchOutDrawHistory();
        WebViewCore.BaseUrlData arg = new WebViewCore.BaseUrlData();
        arg.mBaseUrl = baseUrl;
        arg.mData = data;
        arg.mMimeType = mimeType;
        arg.mEncoding = encoding;
        arg.mHistoryUrl = historyUrl;
        mWebViewCore.sendMessage(EventHub.LOAD_DATA, arg);
        clearHelpers();
    }

    /**
     * See {@link WebView#saveWebArchive(String)}
     */
    @Override
    public void saveWebArchive(String filename) {
        saveWebArchiveImpl(filename, false, null);
    }

    /* package */ static class SaveWebArchiveMessage {
        SaveWebArchiveMessage (String basename, boolean autoname, ValueCallback<String> callback) {
            mBasename = basename;
            mAutoname = autoname;
            mCallback = callback;
        }

        /* package */ final String mBasename;
        /* package */ final boolean mAutoname;
        /* package */ final ValueCallback<String> mCallback;
        /* package */ String mResultFile;
    }

    /**
     * See {@link WebView#saveWebArchive(String, boolean, ValueCallback)}
     */
    @Override
    public void saveWebArchive(String basename, boolean autoname, ValueCallback<String> callback) {
        saveWebArchiveImpl(basename, autoname, callback);
    }

    private void saveWebArchiveImpl(String basename, boolean autoname,
            ValueCallback<String> callback) {
        mWebViewCore.sendMessage(EventHub.SAVE_WEBARCHIVE,
            new SaveWebArchiveMessage(basename, autoname, callback));
    }

    /**
     * See {@link WebView#stopLoading()}
     */
    @Override
    public void stopLoading() {
        // TODO: should we clear all the messages in the queue before sending
        // STOP_LOADING?
        switchOutDrawHistory();
        mWebViewCore.sendMessage(EventHub.STOP_LOADING);
    }

    /**
     * See {@link WebView#reload()}
     */
    @Override
    public void reload() {
        clearHelpers();
        switchOutDrawHistory();
        mWebViewCore.sendMessage(EventHub.RELOAD);
    }

    /**
     * See {@link WebView#canGoBack()}
     */
    @Override
    public boolean canGoBack() {
        WebBackForwardListClassic l = mCallbackProxy.getBackForwardList();
        synchronized (l) {
            if (l.getClearPending()) {
                return false;
            } else {
                return l.getCurrentIndex() > 0;
            }
        }
    }

    /**
     * See {@link WebView#goBack()}
     */
    @Override
    public void goBack() {
        goBackOrForwardImpl(-1);
    }

    /**
     * See {@link WebView#canGoForward()}
     */
    @Override
    public boolean canGoForward() {
        WebBackForwardListClassic l = mCallbackProxy.getBackForwardList();
        synchronized (l) {
            if (l.getClearPending()) {
                return false;
            } else {
                return l.getCurrentIndex() < l.getSize() - 1;
            }
        }
    }

    /**
     * See {@link WebView#goForward()}
     */
    @Override
    public void goForward() {
        goBackOrForwardImpl(1);
    }

    /**
     * See {@link WebView#canGoBackOrForward(int)}
     */
    @Override
    public boolean canGoBackOrForward(int steps) {
        WebBackForwardListClassic l = mCallbackProxy.getBackForwardList();
        synchronized (l) {
            if (l.getClearPending()) {
                return false;
            } else {
                int newIndex = l.getCurrentIndex() + steps;
                return newIndex >= 0 && newIndex < l.getSize();
            }
        }
    }

    /**
     * See {@link WebView#goBackOrForward(int)}
     */
    @Override
    public void goBackOrForward(int steps) {
        goBackOrForwardImpl(steps);
    }

    private void goBackOrForwardImpl(int steps) {
        goBackOrForward(steps, false);
    }

    private void goBackOrForward(int steps, boolean ignoreSnapshot) {
        if (steps != 0) {
            clearHelpers();
            mWebViewCore.sendMessage(EventHub.GO_BACK_FORWARD, steps,
                    ignoreSnapshot ? 1 : 0);
        }
    }

    /**
     * See {@link WebView#isPrivateBrowsingEnabled()}
     */
    @Override
    public boolean isPrivateBrowsingEnabled() {
        WebSettingsClassic settings = getSettings();
        return (settings != null) ? settings.isPrivateBrowsingEnabled() : false;
    }

    private void startPrivateBrowsing() {
        getSettings().setPrivateBrowsingEnabled(true);
    }

    private boolean extendScroll(int y) {
        int finalY = mScroller.getFinalY();
        int newY = pinLocY(finalY + y);
        if (newY == finalY) return false;
        mScroller.setFinalY(newY);
        mScroller.extendDuration(computeDuration(0, y));
        return true;
    }

    /**
     * See {@link WebView#pageUp(boolean)}
     */
    @Override
    public boolean pageUp(boolean top) {
        if (mNativeClass == 0) {
            return false;
        }
        if (top) {
            // go to the top of the document
            return pinScrollTo(getScrollX(), 0, true, 0);
        }
        // Page up
        int h = getHeight();
        int y;
        if (h > 2 * PAGE_SCROLL_OVERLAP) {
            y = -h + PAGE_SCROLL_OVERLAP;
        } else {
            y = -h / 2;
        }
        return mScroller.isFinished() ? pinScrollBy(0, y, true, 0)
                : extendScroll(y);
    }

    /**
     * See {@link WebView#pageDown(boolean)}
     */
    @Override
    public boolean pageDown(boolean bottom) {
        if (mNativeClass == 0) {
            return false;
        }
        if (bottom) {
            return pinScrollTo(getScrollX(), computeRealVerticalScrollRange(), true, 0);
        }
        // Page down.
        int h = getHeight();
        int y;
        if (h > 2 * PAGE_SCROLL_OVERLAP) {
            y = h - PAGE_SCROLL_OVERLAP;
        } else {
            y = h / 2;
        }
        return mScroller.isFinished() ? pinScrollBy(0, y, true, 0)
                : extendScroll(y);
    }

    /**
     * See {@link WebView#clearView()}
     */
    @Override
    public void clearView() {
        mContentWidth = 0;
        mContentHeight = 0;
        setBaseLayer(0, false, false);
        mWebViewCore.sendMessage(EventHub.CLEAR_CONTENT);
    }

    /**
     * See {@link WebView#capturePicture()}
     */
    @Override
    public Picture capturePicture() {
        if (mNativeClass == 0) return null;
        Picture result = new Picture();
        nativeCopyBaseContentToPicture(result);
        return result;
    }

    /**
     * See {@link WebView#getScale()}
     */
    @Override
    public float getScale() {
        return mZoomManager.getScale();
    }

    /**
     * Compute the reading level scale of the WebView
     * @param scale The current scale.
     * @return The reading level scale.
     */
    /*package*/ float computeReadingLevelScale(float scale) {
        return mZoomManager.computeReadingLevelScale(scale);
    }

    /**
     * See {@link WebView#setInitialScale(int)}
     */
    @Override
    public void setInitialScale(int scaleInPercent) {
        mZoomManager.setInitialScaleInPercent(scaleInPercent);
    }

    /**
     * See {@link WebView#invokeZoomPicker()}
     */
    @Override
    public void invokeZoomPicker() {
        if (!getSettings().supportZoom()) {
            Log.w(LOGTAG, "This WebView doesn't support zoom.");
            return;
        }
        clearHelpers();
        mZoomManager.invokeZoomPicker();
    }

    /**
     * See {@link WebView#getHitTestResult()}
     */
    @Override
    public HitTestResult getHitTestResult() {
        return mInitialHitTestResult;
    }

    // No left edge for double-tap zoom alignment
    static final int NO_LEFTEDGE = -1;

    int getBlockLeftEdge(int x, int y, float readingScale) {
        float invReadingScale = 1.0f / readingScale;
        int readingWidth = (int) (getViewWidth() * invReadingScale);
        int left = NO_LEFTEDGE;
        if (mFocusedNode != null) {
            final int length = mFocusedNode.mEnclosingParentRects.length;
            for (int i = 0; i < length; i++) {
                Rect rect = mFocusedNode.mEnclosingParentRects[i];
                if (rect.width() < mFocusedNode.mHitTestSlop) {
                    // ignore bounding boxes that are too small
                    continue;
                } else if (rect.width() > readingWidth) {
                    // stop when bounding box doesn't fit the screen width
                    // at reading scale
                    break;
                }

                left = rect.left;
            }
        }

        return left;
    }

    /**
     * See {@link WebView#requestFocusNodeHref(Message)}
     */
    @Override
    public void requestFocusNodeHref(Message hrefMsg) {
        if (hrefMsg == null) {
            return;
        }
        int contentX = viewToContentX(mLastTouchX + getScrollX());
        int contentY = viewToContentY(mLastTouchY + getScrollY());
        if (mFocusedNode != null && mFocusedNode.mHitTestX == contentX
                && mFocusedNode.mHitTestY == contentY) {
            hrefMsg.getData().putString(FocusNodeHref.URL, mFocusedNode.mLinkUrl);
            hrefMsg.getData().putString(FocusNodeHref.TITLE, mFocusedNode.mAnchorText);
            hrefMsg.getData().putString(FocusNodeHref.SRC, mFocusedNode.mImageUrl);
            hrefMsg.sendToTarget();
            return;
        }
        mWebViewCore.sendMessage(EventHub.REQUEST_CURSOR_HREF,
                contentX, contentY, hrefMsg);
    }

    /**
     * See {@link WebView#requestImageRef(Message)}
     */
    @Override
    public void requestImageRef(Message msg) {
        if (0 == mNativeClass) return; // client isn't initialized
        String url = mFocusedNode != null ? mFocusedNode.mImageUrl : null;
        Bundle data = msg.getData();
        data.putString("url", url);
        msg.setData(data);
        msg.sendToTarget();
    }

    static int pinLoc(int x, int viewMax, int docMax) {
//        Log.d(LOGTAG, "-- pinLoc " + x + " " + viewMax + " " + docMax);
        if (docMax < viewMax) {   // the doc has room on the sides for "blank"
            // pin the short document to the top/left of the screen
            x = 0;
//            Log.d(LOGTAG, "--- center " + x);
        } else if (x < 0) {
            x = 0;
//            Log.d(LOGTAG, "--- zero");
        } else if (x + viewMax > docMax) {
            x = docMax - viewMax;
//            Log.d(LOGTAG, "--- pin " + x);
        }
        return x;
    }

    // Expects x in view coordinates
    int pinLocX(int x) {
        if (mInOverScrollMode) return x;
        return pinLoc(x, getViewWidth(), computeRealHorizontalScrollRange());
    }

    // Expects y in view coordinates
    int pinLocY(int y) {
        if (mInOverScrollMode) return y;
        return pinLoc(y, getViewHeightWithTitle(),
                      computeRealVerticalScrollRange() + getTitleHeight());
    }

    /**
     * Given a distance in view space, convert it to content space. Note: this
     * does not reflect translation, just scaling, so this should not be called
     * with coordinates, but should be called for dimensions like width or
     * height.
     */
    private int viewToContentDimension(int d) {
        return Math.round(d * mZoomManager.getInvScale());
    }

    /**
     * Given an x coordinate in view space, convert it to content space.  Also
     * may be used for absolute heights.
     */
    /*package*/ int viewToContentX(int x) {
        return viewToContentDimension(x);
    }

    /**
     * Given a y coordinate in view space, convert it to content space.
     * Takes into account the height of the title bar if there is one
     * embedded into the WebView.
     */
    /*package*/ int viewToContentY(int y) {
        return viewToContentDimension(y - getTitleHeight());
    }

    /**
     * Given a x coordinate in view space, convert it to content space.
     * Returns the result as a float.
     */
    private float viewToContentXf(int x) {
        return x * mZoomManager.getInvScale();
    }

    /**
     * Given a y coordinate in view space, convert it to content space.
     * Takes into account the height of the title bar if there is one
     * embedded into the WebView. Returns the result as a float.
     */
    private float viewToContentYf(int y) {
        return (y - getTitleHeight()) * mZoomManager.getInvScale();
    }

    /**
     * Given a distance in content space, convert it to view space. Note: this
     * does not reflect translation, just scaling, so this should not be called
     * with coordinates, but should be called for dimensions like width or
     * height.
     */
    /*package*/ int contentToViewDimension(int d) {
        return Math.round(d * mZoomManager.getScale());
    }

    /**
     * Given an x coordinate in content space, convert it to view
     * space.
     */
    /*package*/ int contentToViewX(int x) {
        return contentToViewDimension(x);
    }

    /**
     * Given a y coordinate in content space, convert it to view
     * space.  Takes into account the height of the title bar.
     */
    /*package*/ int contentToViewY(int y) {
        return contentToViewDimension(y) + getTitleHeight();
    }

    private Rect contentToViewRect(Rect x) {
        return new Rect(contentToViewX(x.left), contentToViewY(x.top),
                        contentToViewX(x.right), contentToViewY(x.bottom));
    }

    /*  To invalidate a rectangle in content coordinates, we need to transform
        the rect into view coordinates, so we can then call invalidate(...).

        Normally, we would just call contentToView[XY](...), which eventually
        calls Math.round(coordinate * mActualScale). However, for invalidates,
        we need to account for the slop that occurs with antialiasing. To
        address that, we are a little more liberal in the size of the rect that
        we invalidate.

        This liberal calculation calls floor() for the top/left, and ceil() for
        the bottom/right coordinates. This catches the possible extra pixels of
        antialiasing that we might have missed with just round().
     */

    // Called by JNI to invalidate the View, given rectangle coordinates in
    // content space
    private void viewInvalidate(int l, int t, int r, int b) {
        final float scale = mZoomManager.getScale();
        final int dy = getTitleHeight();
        mWebView.invalidate((int)Math.floor(l * scale),
                (int)Math.floor(t * scale) + dy,
                (int)Math.ceil(r * scale),
                (int)Math.ceil(b * scale) + dy);
    }

    // Called by JNI to invalidate the View after a delay, given rectangle
    // coordinates in content space
    private void viewInvalidateDelayed(long delay, int l, int t, int r, int b) {
        final float scale = mZoomManager.getScale();
        final int dy = getTitleHeight();
        mWebView.postInvalidateDelayed(delay,
                (int)Math.floor(l * scale),
                (int)Math.floor(t * scale) + dy,
                (int)Math.ceil(r * scale),
                (int)Math.ceil(b * scale) + dy);
    }

    private void invalidateContentRect(Rect r) {
        viewInvalidate(r.left, r.top, r.right, r.bottom);
    }

    // stop the scroll animation, and don't let a subsequent fling add
    // to the existing velocity
    private void abortAnimation() {
        mScroller.abortAnimation();
        mLastVelocity = 0;
    }

    /* call from webcoreview.draw(), so we're still executing in the UI thread
    */
    private void recordNewContentSize(int w, int h, boolean updateLayout) {

        // premature data from webkit, ignore
        if ((w | h) == 0) {
            invalidate();
            return;
        }

        // don't abort a scroll animation if we didn't change anything
        if (mContentWidth != w || mContentHeight != h) {
            // record new dimensions
            mContentWidth = w;
            mContentHeight = h;
            // If history Picture is drawn, don't update scroll. They will be
            // updated when we get out of that mode.
            if (!mDrawHistory) {
                // repin our scroll, taking into account the new content size
                updateScrollCoordinates(pinLocX(getScrollX()), pinLocY(getScrollY()));
                if (!mScroller.isFinished()) {
                    // We are in the middle of a scroll.  Repin the final scroll
                    // position.
                    mScroller.setFinalX(pinLocX(mScroller.getFinalX()));
                    mScroller.setFinalY(pinLocY(mScroller.getFinalY()));
                }
            }
            invalidate();
        }
        contentSizeChanged(updateLayout);
    }

    // Used to avoid sending many visible rect messages.
    private Rect mLastVisibleRectSent = new Rect();
    private Rect mLastGlobalRect = new Rect();
    private Rect mVisibleRect = new Rect();
    private Rect mGlobalVisibleRect = new Rect();
    private Point mScrollOffset = new Point();

    Rect sendOurVisibleRect() {
        if (mZoomManager.isPreventingWebkitUpdates()) return mLastVisibleRectSent;
        calcOurContentVisibleRect(mVisibleRect);
        // Rect.equals() checks for null input.
        if (!mVisibleRect.equals(mLastVisibleRectSent)) {
            if (!mBlockWebkitViewMessages) {
                mScrollOffset.set(mVisibleRect.left, mVisibleRect.top);
                mWebViewCore.removeMessages(EventHub.SET_SCROLL_OFFSET);
                mWebViewCore.sendMessage(EventHub.SET_SCROLL_OFFSET,
                        mSendScrollEvent ? 1 : 0, mScrollOffset);
            }
            mLastVisibleRectSent.set(mVisibleRect);
            mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
        }
        if (mWebView.getGlobalVisibleRect(mGlobalVisibleRect)
                && !mGlobalVisibleRect.equals(mLastGlobalRect)) {
            if (DebugFlags.WEB_VIEW) {
                Log.v(LOGTAG, "sendOurVisibleRect=(" + mGlobalVisibleRect.left + ","
                        + mGlobalVisibleRect.top + ",r=" + mGlobalVisibleRect.right + ",b="
                        + mGlobalVisibleRect.bottom);
            }
            // TODO: the global offset is only used by windowRect()
            // in ChromeClientAndroid ; other clients such as touch
            // and mouse events could return view + screen relative points.
            if (!mBlockWebkitViewMessages) {
                mWebViewCore.sendMessage(EventHub.SET_GLOBAL_BOUNDS, mGlobalVisibleRect);
            }
            mLastGlobalRect.set(mGlobalVisibleRect);
        }
        return mVisibleRect;
    }

    private Point mGlobalVisibleOffset = new Point();
    // Sets r to be the visible rectangle of our webview in view coordinates
    private void calcOurVisibleRect(Rect r) {
        mWebView.getGlobalVisibleRect(r, mGlobalVisibleOffset);
        r.offset(-mGlobalVisibleOffset.x, -mGlobalVisibleOffset.y);
    }

    // Sets r to be our visible rectangle in content coordinates
    private void calcOurContentVisibleRect(Rect r) {
        calcOurVisibleRect(r);
        r.left = viewToContentX(r.left);
        // viewToContentY will remove the total height of the title bar.  Add
        // the visible height back in to account for the fact that if the title
        // bar is partially visible, the part of the visible rect which is
        // displaying our content is displaced by that amount.
        r.top = viewToContentY(r.top + getVisibleTitleHeightImpl());
        r.right = viewToContentX(r.right);
        r.bottom = viewToContentY(r.bottom);
    }

    private final Rect mTempContentVisibleRect = new Rect();
    // Sets r to be our visible rectangle in content coordinates. We use this
    // method on the native side to compute the position of the fixed layers.
    // Uses floating coordinates (necessary to correctly place elements when
    // the scale factor is not 1)
    private void calcOurContentVisibleRectF(RectF r) {
        calcOurVisibleRect(mTempContentVisibleRect);
        viewToContentVisibleRect(r, mTempContentVisibleRect);
    }

    static class ViewSizeData {
        int mWidth;
        int mHeight;
        float mHeightWidthRatio;
        int mActualViewHeight;
        int mTextWrapWidth;
        int mAnchorX;
        int mAnchorY;
        float mScale;
        boolean mIgnoreHeight;
    }

    /**
     * Compute unzoomed width and height, and if they differ from the last
     * values we sent, send them to webkit (to be used as new viewport)
     *
     * @param force ensures that the message is sent to webkit even if the width
     * or height has not changed since the last message
     *
     * @return true if new values were sent
     */
    boolean sendViewSizeZoom(boolean force) {
        if (mBlockWebkitViewMessages) return false;
        if (mZoomManager.isPreventingWebkitUpdates()) return false;

        int viewWidth = getViewWidth();
        int newWidth = Math.round(viewWidth * mZoomManager.getInvScale());
        // This height could be fixed and be different from actual visible height.
        int viewHeight = getViewHeightWithTitle() - getTitleHeight();
        int newHeight = Math.round(viewHeight * mZoomManager.getInvScale());
        // Make the ratio more accurate than (newHeight / newWidth), since the
        // latter both are calculated and rounded.
        float heightWidthRatio = (float) viewHeight / viewWidth;
        /*
         * Because the native side may have already done a layout before the
         * View system was able to measure us, we have to send a height of 0 to
         * remove excess whitespace when we grow our width. This will trigger a
         * layout and a change in content size. This content size change will
         * mean that contentSizeChanged will either call this method directly or
         * indirectly from onSizeChanged.
         */
        if (newWidth > mLastWidthSent && mWrapContent) {
            newHeight = 0;
            heightWidthRatio = 0;
        }
        // Actual visible content height.
        int actualViewHeight = Math.round(getViewHeight() * mZoomManager.getInvScale());
        // Avoid sending another message if the dimensions have not changed.
        if (newWidth != mLastWidthSent || newHeight != mLastHeightSent || force ||
                actualViewHeight != mLastActualHeightSent) {
            ViewSizeData data = new ViewSizeData();
            data.mWidth = newWidth;
            data.mHeight = newHeight;
            data.mHeightWidthRatio = heightWidthRatio;
            data.mActualViewHeight = actualViewHeight;
            data.mTextWrapWidth = Math.round(viewWidth / mZoomManager.getTextWrapScale());
            data.mScale = mZoomManager.getScale();
            data.mIgnoreHeight = mZoomManager.isFixedLengthAnimationInProgress()
                    && !mHeightCanMeasure;
            data.mAnchorX = mZoomManager.getDocumentAnchorX();
            data.mAnchorY = mZoomManager.getDocumentAnchorY();
            mWebViewCore.sendMessage(EventHub.VIEW_SIZE_CHANGED, data);
            mLastWidthSent = newWidth;
            mLastHeightSent = newHeight;
            mLastActualHeightSent = actualViewHeight;
            mZoomManager.clearDocumentAnchor();
            return true;
        }
        return false;
    }

    /**
     * Update the double-tap zoom.
     */
    /* package */ void updateDoubleTapZoom(int doubleTapZoom) {
        mZoomManager.updateDoubleTapZoom(doubleTapZoom);
    }

    private int computeRealHorizontalScrollRange() {
        if (mDrawHistory) {
            return mHistoryWidth;
        } else {
            // to avoid rounding error caused unnecessary scrollbar, use floor
            return (int) Math.floor(mContentWidth * mZoomManager.getScale());
        }
    }

    @Override
    public int computeHorizontalScrollRange() {
        int range = computeRealHorizontalScrollRange();

        // Adjust reported range if overscrolled to compress the scroll bars
        final int scrollX = getScrollX();
        final int overscrollRight = computeMaxScrollX();
        if (scrollX < 0) {
            range -= scrollX;
        } else if (scrollX > overscrollRight) {
            range += scrollX - overscrollRight;
        }

        return range;
    }

    @Override
    public int computeHorizontalScrollOffset() {
        return Math.max(getScrollX(), 0);
    }

    private int computeRealVerticalScrollRange() {
        if (mDrawHistory) {
            return mHistoryHeight;
        } else {
            // to avoid rounding error caused unnecessary scrollbar, use floor
            return (int) Math.floor(mContentHeight * mZoomManager.getScale());
        }
    }

    @Override
    public int computeVerticalScrollRange() {
        int range = computeRealVerticalScrollRange();

        // Adjust reported range if overscrolled to compress the scroll bars
        final int scrollY = getScrollY();
        final int overscrollBottom = computeMaxScrollY();
        if (scrollY < 0) {
            range -= scrollY;
        } else if (scrollY > overscrollBottom) {
            range += scrollY - overscrollBottom;
        }

        return range;
    }

    @Override
    public int computeVerticalScrollOffset() {
        return Math.max(getScrollY() - getTitleHeight(), 0);
    }

    @Override
    public int computeVerticalScrollExtent() {
        return getViewHeight();
    }

    @Override
    public void onDrawVerticalScrollBar(Canvas canvas,
                                           Drawable scrollBar,
                                           int l, int t, int r, int b) {
        if (getScrollY() < 0) {
            t -= getScrollY();
        }
        scrollBar.setBounds(l, t + getVisibleTitleHeightImpl(), r, b);
        scrollBar.draw(canvas);
    }

    @Override
    public void onOverScrolled(int scrollX, int scrollY, boolean clampedX,
            boolean clampedY) {
        // Special-case layer scrolling so that we do not trigger normal scroll
        // updating.
        if (mTouchMode == TOUCH_DRAG_TEXT_MODE) {
            scrollEditText(scrollX, scrollY);
            return;
        }
        if (mTouchMode == TOUCH_DRAG_LAYER_MODE) {
            scrollLayerTo(scrollX, scrollY);
            animateHandles();
            return;
        }
        mInOverScrollMode = false;
        int maxX = computeMaxScrollX();
        int maxY = computeMaxScrollY();
        if (maxX == 0) {
            // do not over scroll x if the page just fits the screen
            scrollX = pinLocX(scrollX);
        } else if (scrollX < 0 || scrollX > maxX) {
            mInOverScrollMode = true;
        }
        if (scrollY < 0 || scrollY > maxY) {
            mInOverScrollMode = true;
        }

        int oldX = getScrollX();
        int oldY = getScrollY();

        mWebViewPrivate.super_scrollTo(scrollX, scrollY);

        animateHandles();

        if (mOverScrollGlow != null) {
            mOverScrollGlow.pullGlow(getScrollX(), getScrollY(), oldX, oldY, maxX, maxY);
        }
    }

    /**
     * See {@link WebView#getUrl()}
     */
    @Override
    public String getUrl() {
        WebHistoryItem h = mCallbackProxy.getBackForwardList().getCurrentItem();
        return h != null ? h.getUrl() : null;
    }

    /**
     * See {@link WebView#getOriginalUrl()}
     */
    @Override
    public String getOriginalUrl() {
        WebHistoryItem h = mCallbackProxy.getBackForwardList().getCurrentItem();
        return h != null ? h.getOriginalUrl() : null;
    }

    /**
     * See {@link WebView#getTitle()}
     */
    @Override
    public String getTitle() {
        WebHistoryItem h = mCallbackProxy.getBackForwardList().getCurrentItem();
        return h != null ? h.getTitle() : null;
    }

    /**
     * See {@link WebView#getFavicon()}
     */
    @Override
    public Bitmap getFavicon() {
        WebHistoryItem h = mCallbackProxy.getBackForwardList().getCurrentItem();
        return h != null ? h.getFavicon() : null;
    }

    /**
     * See {@link WebView#getTouchIconUrl()}
     */
    @Override
    public String getTouchIconUrl() {
        WebHistoryItemClassic h = mCallbackProxy.getBackForwardList().getCurrentItem();
        return h != null ? h.getTouchIconUrl() : null;
    }

    /**
     * See {@link WebView#getProgress()}
     */
    @Override
    public int getProgress() {
        return mCallbackProxy.getProgress();
    }

    /**
     * See {@link WebView#getContentHeight()}
     */
    @Override
    public int getContentHeight() {
        return mContentHeight;
    }

    /**
     * See {@link WebView#getContentWidth()}
     */
    @Override
    public int getContentWidth() {
        return mContentWidth;
    }

    public int getPageBackgroundColor() {
        if (mNativeClass == 0) return Color.WHITE;
        return nativeGetBackgroundColor(mNativeClass);
    }

    /**
     * See {@link WebView#pauseTimers()}
     */
    @Override
    public void pauseTimers() {
        mWebViewCore.sendMessage(EventHub.PAUSE_TIMERS);
    }

    /**
     * See {@link WebView#resumeTimers()}
     */
    @Override
    public void resumeTimers() {
        mWebViewCore.sendMessage(EventHub.RESUME_TIMERS);
    }

    /**
     * See {@link WebView#onPause()}
     */
    @Override
    public void onPause() {
        if (!mIsPaused) {
            mIsPaused = true;
            mWebViewCore.sendMessage(EventHub.ON_PAUSE);
            // We want to pause the current playing video when switching out
            // from the current WebView/tab.
            if (mHTML5VideoViewProxy != null) {
                mHTML5VideoViewProxy.pauseAndDispatch();
            }
            if (mNativeClass != 0) {
                nativeSetPauseDrawing(mNativeClass, true);
            }

            cancelDialogs();
            WebCoreThreadWatchdog.pause();
        }
    }

    @Override
    public void onWindowVisibilityChanged(int visibility) {
        updateDrawingState();
    }

    void updateDrawingState() {
        if (mNativeClass == 0 || mIsPaused) return;
        if (mWebView.getWindowVisibility() != View.VISIBLE) {
            nativeSetPauseDrawing(mNativeClass, true);
        } else if (mWebView.getVisibility() != View.VISIBLE) {
            nativeSetPauseDrawing(mNativeClass, true);
        } else {
            nativeSetPauseDrawing(mNativeClass, false);
        }
    }

    /**
     * See {@link WebView#onResume()}
     */
    @Override
    public void onResume() {
        if (mIsPaused) {
            mIsPaused = false;
            mWebViewCore.sendMessage(EventHub.ON_RESUME);
            if (mNativeClass != 0) {
                nativeSetPauseDrawing(mNativeClass, false);
            }
        }
        // We get a call to onResume for new WebViews (i.e. mIsPaused will be false). We need
        // to ensure that the Watchdog thread is running for the new WebView, so call
        // it outside the if block above.
        WebCoreThreadWatchdog.resume();
    }

    /**
     * See {@link WebView#isPaused()}
     */
    @Override
    public boolean isPaused() {
        return mIsPaused;
    }

    /**
     * See {@link WebView#freeMemory()}
     */
    @Override
    public void freeMemory() {
        mWebViewCore.sendMessage(EventHub.FREE_MEMORY);
    }

    /**
     * See {@link WebView#clearCache(boolean)}
     */
    @Override
    public void clearCache(boolean includeDiskFiles) {
        // Note: this really needs to be a static method as it clears cache for all
        // WebView. But we need mWebViewCore to send message to WebCore thread, so
        // we can't make this static.
        mWebViewCore.sendMessage(EventHub.CLEAR_CACHE,
                includeDiskFiles ? 1 : 0, 0);
    }

    /**
     * See {@link WebView#clearFormData()}
     */
    @Override
    public void clearFormData() {
        if (mAutoCompletePopup != null) {
            mAutoCompletePopup.clearAdapter();
        }
    }

    /**
     * See {@link WebView#clearHistory()}
     */
    @Override
    public void clearHistory() {
        mCallbackProxy.getBackForwardList().setClearPending();
        mWebViewCore.sendMessage(EventHub.CLEAR_HISTORY);
    }

    /**
     * See {@link WebView#clearSslPreferences()}
     */
    @Override
    public void clearSslPreferences() {
        mWebViewCore.sendMessage(EventHub.CLEAR_SSL_PREF_TABLE);
    }

    /**
     * See {@link WebView#copyBackForwardList()}
     */
    @Override
    public WebBackForwardListClassic copyBackForwardList() {
        return mCallbackProxy.getBackForwardList().clone();
    }

    /**
     * See {@link WebView#setFindListener(WebView.FindListener)}.
     * @hide
     */
     @Override
    public void setFindListener(WebView.FindListener listener) {
         mFindListener = listener;
     }

    /**
     * See {@link WebView#findNext(boolean)}
     */
    @Override
    public void findNext(boolean forward) {
        if (0 == mNativeClass) return; // client isn't initialized
        if (mFindRequest != null) {
            mWebViewCore.sendMessage(EventHub.FIND_NEXT, forward ? 1 : 0, mFindRequest);
        }
    }

    /**
     * See {@link WebView#findAll(String)}
     */
    @Override
    public int findAll(String find) {
        return findAllBody(find, false);
    }

    @Override
    public void findAllAsync(String find) {
        findAllBody(find, true);
    }

    private int findAllBody(String find, boolean isAsync) {
        if (0 == mNativeClass) return 0; // client isn't initialized
        mFindRequest = null;
        if (find == null) return 0;
        mWebViewCore.removeMessages(EventHub.FIND_ALL);
        mFindRequest = new WebViewCore.FindAllRequest(find);
        if (isAsync) {
            mWebViewCore.sendMessage(EventHub.FIND_ALL, mFindRequest);
            return 0; // no need to wait for response
        }
        synchronized(mFindRequest) {
            try {
                mWebViewCore.sendMessageAtFrontOfQueue(EventHub.FIND_ALL, mFindRequest);
                while (mFindRequest.mMatchCount == -1) {
                    mFindRequest.wait();
                }
            }
            catch (InterruptedException e) {
                return 0;
            }
            return mFindRequest.mMatchCount;
        }
    }

    /**
     * Start an ActionMode for finding text in this WebView.  Only works if this
     *              WebView is attached to the view system.
     * @param text If non-null, will be the initial text to search for.
     *             Otherwise, the last String searched for in this WebView will
     *             be used to start.
     * @param showIme If true, show the IME, assuming the user will begin typing.
     *             If false and text is non-null, perform a find all.
     * @return boolean True if the find dialog is shown, false otherwise.
     */
    @Override
    public boolean showFindDialog(String text, boolean showIme) {
        FindActionModeCallback callback = new FindActionModeCallback(mContext);
        if (mWebView.getParent() == null || mWebView.startActionMode(callback) == null) {
            // Could not start the action mode, so end Find on page
            return false;
        }
        mCachedOverlappingActionModeHeight = -1;
        mFindCallback = callback;
        setFindIsUp(true);
        mFindCallback.setWebView(this);
        if (showIme) {
            mFindCallback.showSoftInput();
        } else if (text != null) {
            mFindCallback.setText(text);
            mFindCallback.findAll();
            return true;
        }
        if (text == null) {
            text = mFindRequest == null ? null : mFindRequest.mSearchText;
        }
        if (text != null) {
            mFindCallback.setText(text);
            mFindCallback.findAll();
        }
        return true;
    }

    /**
     * Keep track of the find callback so that we can remove its titlebar if
     * necessary.
     */
    private FindActionModeCallback mFindCallback;

    /**
     * Toggle whether the find dialog is showing, for both native and Java.
     */
    private void setFindIsUp(boolean isUp) {
        mFindIsUp = isUp;
    }

    // Used to know whether the find dialog is open.  Affects whether
    // or not we draw the highlights for matches.
    private boolean mFindIsUp;

    // Keep track of the last find request sent.
    private WebViewCore.FindAllRequest mFindRequest = null;

    /**
     * Return the first substring consisting of the address of a physical
     * location. Currently, only addresses in the United States are detected,
     * and consist of:
     * - a house number
     * - a street name
     * - a street type (Road, Circle, etc), either spelled out or abbreviated
     * - a city name
     * - a state or territory, either spelled out or two-letter abbr.
     * - an optional 5 digit or 9 digit zip code.
     *
     * All names must be correctly capitalized, and the zip code, if present,
     * must be valid for the state. The street type must be a standard USPS
     * spelling or abbreviation. The state or territory must also be spelled
     * or abbreviated using USPS standards. The house number may not exceed
     * five digits.
     * @param addr The string to search for addresses.
     *
     * @return the address, or if no address is found, return null.
     */
    public static String findAddress(String addr) {
        return findAddress(addr, false);
    }

    /**
     * Return the first substring consisting of the address of a physical
     * location. Currently, only addresses in the United States are detected,
     * and consist of:
     * - a house number
     * - a street name
     * - a street type (Road, Circle, etc), either spelled out or abbreviated
     * - a city name
     * - a state or territory, either spelled out or two-letter abbr.
     * - an optional 5 digit or 9 digit zip code.
     *
     * Names are optionally capitalized, and the zip code, if present,
     * must be valid for the state. The street type must be a standard USPS
     * spelling or abbreviation. The state or territory must also be spelled
     * or abbreviated using USPS standards. The house number may not exceed
     * five digits.
     * @param addr The string to search for addresses.
     * @param caseInsensitive addr Set to true to make search ignore case.
     *
     * @return the address, or if no address is found, return null.
     */
    public static String findAddress(String addr, boolean caseInsensitive) {
        return WebViewCore.nativeFindAddress(addr, caseInsensitive);
    }

    /**
     * See {@link WebView#clearMatches()}
     */
    @Override
    public void clearMatches() {
        if (mNativeClass == 0)
            return;
        mWebViewCore.removeMessages(EventHub.FIND_ALL);
        mWebViewCore.sendMessage(EventHub.FIND_ALL, null);
    }


    /**
     * Called when the find ActionMode ends.
     */
    void notifyFindDialogDismissed() {
        mFindCallback = null;
        mCachedOverlappingActionModeHeight = -1;
        if (mWebViewCore == null) {
            return;
        }
        clearMatches();
        setFindIsUp(false);
        // Now that the dialog has been removed, ensure that we scroll to a
        // location that is not beyond the end of the page.
        pinScrollTo(getScrollX(), getScrollY(), false, 0);
        invalidate();
    }

    /**
     * See {@link WebView#documentHasImages(Message)}
     */
    @Override
    public void documentHasImages(Message response) {
        if (response == null) {
            return;
        }
        mWebViewCore.sendMessage(EventHub.DOC_HAS_IMAGES, response);
    }

    /**
     * Request the scroller to abort any ongoing animation
     */
    public void stopScroll() {
        mScroller.forceFinished(true);
        mLastVelocity = 0;
    }

    @Override
    public void computeScroll() {
        if (mScroller.computeScrollOffset()) {
            int oldX = getScrollX();
            int oldY = getScrollY();
            int x = mScroller.getCurrX();
            int y = mScroller.getCurrY();
            invalidate();  // So we draw again

            if (!mScroller.isFinished()) {
                int rangeX = computeMaxScrollX();
                int rangeY = computeMaxScrollY();
                int overflingDistance = mOverflingDistance;

                // Use the layer's scroll data if needed.
                if (mTouchMode == TOUCH_DRAG_LAYER_MODE) {
                    oldX = mScrollingLayerRect.left;
                    oldY = mScrollingLayerRect.top;
                    rangeX = mScrollingLayerRect.right;
                    rangeY = mScrollingLayerRect.bottom;
                    // No overscrolling for layers.
                    overflingDistance = 0;
                } else if (mTouchMode == TOUCH_DRAG_TEXT_MODE) {
                    oldX = getTextScrollX();
                    oldY = getTextScrollY();
                    rangeX = getMaxTextScrollX();
                    rangeY = getMaxTextScrollY();
                    overflingDistance = 0;
                }

                mWebViewPrivate.overScrollBy(x - oldX, y - oldY, oldX, oldY,
                        rangeX, rangeY,
                        overflingDistance, overflingDistance, false);

                if (mOverScrollGlow != null) {
                    mOverScrollGlow.absorbGlow(x, y, oldX, oldY, rangeX, rangeY);
                }
            } else {
                if (mTouchMode == TOUCH_DRAG_LAYER_MODE) {
                    // Update the layer position instead of WebView.
                    scrollLayerTo(x, y);
                } else if (mTouchMode == TOUCH_DRAG_TEXT_MODE) {
                    scrollEditText(x, y);
                } else {
                    setScrollXRaw(x);
                    setScrollYRaw(y);
                }
                abortAnimation();
                nativeSetIsScrolling(false);
                if (!mBlockWebkitViewMessages) {
                    WebViewCore.resumePriority();
                    if (!mSelectingText) {
                        WebViewCore.resumeUpdatePicture(mWebViewCore);
                    }
                }
                if (oldX != getScrollX() || oldY != getScrollY()) {
                    sendOurVisibleRect();
                }
            }
        } else {
            mWebViewPrivate.super_computeScroll();
        }
    }

    private void scrollLayerTo(int x, int y) {
        int dx = mScrollingLayerRect.left - x;
        int dy = mScrollingLayerRect.top - y;
        if ((dx == 0 && dy == 0) || mNativeClass == 0) {
            return;
        }
        if (mSelectingText) {
            if (mSelectCursorBaseLayerId == mCurrentScrollingLayerId) {
                mSelectCursorBase.offset(dx, dy);
                mSelectCursorBaseTextQuad.offset(dx, dy);
            }
            if (mSelectCursorExtentLayerId == mCurrentScrollingLayerId) {
                mSelectCursorExtent.offset(dx, dy);
                mSelectCursorExtentTextQuad.offset(dx, dy);
            }
        }
        if (mAutoCompletePopup != null &&
                mCurrentScrollingLayerId == mEditTextLayerId) {
            mEditTextContentBounds.offset(dx, dy);
            mAutoCompletePopup.resetRect();
        }
        nativeScrollLayer(mNativeClass, mCurrentScrollingLayerId, x, y);
        mScrollingLayerRect.left = x;
        mScrollingLayerRect.top = y;
        mWebViewCore.sendMessage(WebViewCore.EventHub.SCROLL_LAYER, mCurrentScrollingLayerId,
                mScrollingLayerRect);
        mWebViewPrivate.onScrollChanged(getScrollX(), getScrollY(), getScrollX(), getScrollY());
        invalidate();
    }

    private static int computeDuration(int dx, int dy) {
        int distance = Math.max(Math.abs(dx), Math.abs(dy));
        int duration = distance * 1000 / STD_SPEED;
        return Math.min(duration, MAX_DURATION);
    }

    // helper to pin the scrollBy parameters (already in view coordinates)
    // returns true if the scroll was changed
    private boolean pinScrollBy(int dx, int dy, boolean animate, int animationDuration) {
        return pinScrollTo(getScrollX() + dx, getScrollY() + dy, animate, animationDuration);
    }
    // helper to pin the scrollTo parameters (already in view coordinates)
    // returns true if the scroll was changed
    private boolean pinScrollTo(int x, int y, boolean animate, int animationDuration) {
        abortAnimation();
        x = pinLocX(x);
        y = pinLocY(y);
        int dx = x - getScrollX();
        int dy = y - getScrollY();

        if ((dx | dy) == 0) {
            return false;
        }
        if (animate) {
            //        Log.d(LOGTAG, "startScroll: " + dx + " " + dy);
            mScroller.startScroll(getScrollX(), getScrollY(), dx, dy,
                    animationDuration > 0 ? animationDuration : computeDuration(dx, dy));
            invalidate();
        } else {
            mWebView.scrollTo(x, y);
        }
        return true;
    }

    // Scale from content to view coordinates, and pin.
    // Also called by jni webview.cpp
    private boolean setContentScrollBy(int cx, int cy, boolean animate) {
        if (mDrawHistory) {
            // disallow WebView to change the scroll position as History Picture
            // is used in the view system.
            // TODO: as we switchOutDrawHistory when trackball or navigation
            // keys are hit, this should be safe. Right?
            return false;
        }
        cx = contentToViewDimension(cx);
        cy = contentToViewDimension(cy);
        if (mHeightCanMeasure) {
            // move our visible rect according to scroll request
            if (cy != 0) {
                Rect tempRect = new Rect();
                calcOurVisibleRect(tempRect);
                tempRect.offset(cx, cy);
                mWebView.requestRectangleOnScreen(tempRect);
            }
            // FIXME: We scroll horizontally no matter what because currently
            // ScrollView and ListView will not scroll horizontally.
            // FIXME: Why do we only scroll horizontally if there is no
            // vertical scroll?
//                Log.d(LOGTAG, "setContentScrollBy cy=" + cy);
            return cy == 0 && cx != 0 && pinScrollBy(cx, 0, animate, 0);
        } else {
            return pinScrollBy(cx, cy, animate, 0);
        }
    }

    /**
     * Called by CallbackProxy when the page starts loading.
     * @param url The URL of the page which has started loading.
     */
    /* package */ void onPageStarted(String url) {
        // every time we start a new page, we want to reset the
        // WebView certificate:  if the new site is secure, we
        // will reload it and get a new certificate set;
        // if the new site is not secure, the certificate must be
        // null, and that will be the case
        mWebView.setCertificate(null);

        // reset the flag since we set to true in if need after
        // loading is see onPageFinished(Url)
        if (isAccessibilityInjectionEnabled()) {
            getAccessibilityInjector().onPageStarted(url);
        }

        // Don't start out editing.
        mIsEditingText = false;
    }

    /**
     * Called by CallbackProxy when the page finishes loading.
     * @param url The URL of the page which has finished loading.
     */
    /* package */ void onPageFinished(String url) {
        mZoomManager.onPageFinished(url);

        if (isAccessibilityInjectionEnabled()) {
            getAccessibilityInjector().onPageFinished(url);
        }
    }

    // scale from content to view coordinates, and pin
    private void contentScrollTo(int cx, int cy, boolean animate) {
        if (mDrawHistory) {
            // disallow WebView to change the scroll position as History Picture
            // is used in the view system.
            return;
        }
        int vx = contentToViewX(cx);
        int vy = contentToViewY(cy);
        pinScrollTo(vx, vy, animate, 0);
    }

    /**
     * These are from webkit, and are in content coordinate system (unzoomed)
     */
    private void contentSizeChanged(boolean updateLayout) {
        // suppress 0,0 since we usually see real dimensions soon after
        // this avoids drawing the prev content in a funny place. If we find a
        // way to consolidate these notifications, this check may become
        // obsolete
        if ((mContentWidth | mContentHeight) == 0) {
            return;
        }

        if (mHeightCanMeasure) {
            if (mWebView.getMeasuredHeight() != contentToViewDimension(mContentHeight)
                    || updateLayout) {
                mWebView.requestLayout();
            }
        } else if (mWidthCanMeasure) {
            if (mWebView.getMeasuredWidth() != contentToViewDimension(mContentWidth)
                    || updateLayout) {
                mWebView.requestLayout();
            }
        } else {
            // If we don't request a layout, try to send our view size to the
            // native side to ensure that WebCore has the correct dimensions.
            sendViewSizeZoom(false);
        }
    }

    /**
     * See {@link WebView#setWebViewClient(WebViewClient)}
     */
    @Override
    public void setWebViewClient(WebViewClient client) {
        mCallbackProxy.setWebViewClient(client);
    }

    /**
     * Gets the WebViewClient
     * @return the current WebViewClient instance.
     *
     * This is an implementation detail.
     */
    public WebViewClient getWebViewClient() {
        return mCallbackProxy.getWebViewClient();
    }

    /**
     * See {@link WebView#setDownloadListener(DownloadListener)}
     */
    @Override
    public void setDownloadListener(DownloadListener listener) {
        mCallbackProxy.setDownloadListener(listener);
    }

    /**
     * See {@link WebView#setWebChromeClient(WebChromeClient)}
     */
    @Override
    public void setWebChromeClient(WebChromeClient client) {
        mCallbackProxy.setWebChromeClient(client);
    }

    /**
     * Gets the chrome handler.
     * @return the current WebChromeClient instance.
     *
     * This is an implementation detail.
     */
    public WebChromeClient getWebChromeClient() {
        return mCallbackProxy.getWebChromeClient();
    }

    /**
     * Set the back/forward list client. This is an implementation of
     * WebBackForwardListClient for handling new items and changes in the
     * history index.
     * @param client An implementation of WebBackForwardListClient.
     */
    public void setWebBackForwardListClient(WebBackForwardListClient client) {
        mCallbackProxy.setWebBackForwardListClient(client);
    }

    /**
     * Gets the WebBackForwardListClient.
     */
    public WebBackForwardListClient getWebBackForwardListClient() {
        return mCallbackProxy.getWebBackForwardListClient();
    }

    /**
     * See {@link WebView#setPictureListener(PictureListener)}
     */
    @Override
    @Deprecated
    public void setPictureListener(PictureListener listener) {
        mPictureListener = listener;
    }

    /* FIXME: Debug only! Remove for SDK! */
    public void externalRepresentation(Message callback) {
        mWebViewCore.sendMessage(EventHub.REQUEST_EXT_REPRESENTATION, callback);
    }

    /* FIXME: Debug only! Remove for SDK! */
    public void documentAsText(Message callback) {
        mWebViewCore.sendMessage(EventHub.REQUEST_DOC_AS_TEXT, callback);
    }

    /**
     * See {@link WebView#addJavascriptInterface(Object, String)}
     */
    @Override
    public void addJavascriptInterface(Object object, String name) {

        if (object == null) {
            return;
        }
        WebViewCore.JSInterfaceData arg = new WebViewCore.JSInterfaceData();

        arg.mObject = object;
        arg.mInterfaceName = name;

        // starting with JELLY_BEAN_MR1, annotations are mandatory for enabling access to
        // methods that are accessible from JS.
        if (mContext.getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            arg.mRequireAnnotation = true;
        } else {
            arg.mRequireAnnotation = false;
        }
        mWebViewCore.sendMessage(EventHub.ADD_JS_INTERFACE, arg);
    }

    /**
     * See {@link WebView#removeJavascriptInterface(String)}
     */
    @Override
    public void removeJavascriptInterface(String interfaceName) {
        if (mWebViewCore != null) {
            WebViewCore.JSInterfaceData arg = new WebViewCore.JSInterfaceData();
            arg.mInterfaceName = interfaceName;
            mWebViewCore.sendMessage(EventHub.REMOVE_JS_INTERFACE, arg);
        }
    }

    /**
     * See {@link WebView#getSettings()}
     * Note this returns WebSettingsClassic, a sub-class of WebSettings, which can be used
     * to access extension APIs.
     */
    @Override
    public WebSettingsClassic getSettings() {
        return (mWebViewCore != null) ? mWebViewCore.getSettings() : null;
    }

    /**
     * See {@link WebView#getPluginList()}
     */
    @Deprecated
    public static synchronized PluginList getPluginList() {
        return new PluginList();
    }

    /**
     * See {@link WebView#refreshPlugins(boolean)}
     */
    @Deprecated
    public void refreshPlugins(boolean reloadOpenPages) {
    }

    //-------------------------------------------------------------------------
    // Override View methods
    //-------------------------------------------------------------------------

    @Override
    protected void finalize() throws Throwable {
        try {
            destroy();
        } finally {
            super.finalize();
        }
    }

    private void drawContent(Canvas canvas) {
        if (mDrawHistory) {
            canvas.scale(mZoomManager.getScale(), mZoomManager.getScale());
            canvas.drawPicture(mHistoryPicture);
            return;
        }
        if (mNativeClass == 0) return;

        boolean animateZoom = mZoomManager.isFixedLengthAnimationInProgress();
        boolean animateScroll = ((!mScroller.isFinished()
                || mVelocityTracker != null)
                && (mTouchMode != TOUCH_DRAG_MODE ||
                mHeldMotionless != MOTIONLESS_TRUE));
        if (mTouchMode == TOUCH_DRAG_MODE) {
            if (mHeldMotionless == MOTIONLESS_PENDING) {
                mPrivateHandler.removeMessages(DRAG_HELD_MOTIONLESS);
                mHeldMotionless = MOTIONLESS_FALSE;
            }
            if (mHeldMotionless == MOTIONLESS_FALSE) {
                mPrivateHandler.sendMessageDelayed(mPrivateHandler
                        .obtainMessage(DRAG_HELD_MOTIONLESS), MOTIONLESS_TIME);
                mHeldMotionless = MOTIONLESS_PENDING;
            }
        }
        int saveCount = canvas.save();
        if (animateZoom) {
            mZoomManager.animateZoom(canvas);
        } else if (!canvas.isHardwareAccelerated()) {
            canvas.scale(mZoomManager.getScale(), mZoomManager.getScale());
        }

        boolean UIAnimationsRunning = false;
        // Currently for each draw we compute the animation values;
        // We may in the future decide to do that independently.
        if (mNativeClass != 0 && !canvas.isHardwareAccelerated()
                && nativeEvaluateLayersAnimations(mNativeClass)) {
            UIAnimationsRunning = true;
            // If we have unfinished (or unstarted) animations,
            // we ask for a repaint. We only need to do this in software
            // rendering (with hardware rendering we already have a different
            // method of requesting a repaint)
            mWebViewCore.sendMessage(EventHub.NOTIFY_ANIMATION_STARTED);
            invalidate();
        }

        // decide which adornments to draw
        int extras = DRAW_EXTRAS_NONE;
        if (!mFindIsUp && mShowTextSelectionExtra) {
            extras = DRAW_EXTRAS_SELECTION;
        }

        calcOurContentVisibleRectF(mVisibleContentRect);
        if (canvas.isHardwareAccelerated()) {
            Rect invScreenRect = mIsWebViewVisible ? mInvScreenRect : null;
            Rect screenRect = mIsWebViewVisible ? mScreenRect : null;

            int functor = nativeCreateDrawGLFunction(mNativeClass, invScreenRect,
                    screenRect, mVisibleContentRect, getScale(), extras);
            ((HardwareCanvas) canvas).callDrawGLFunction(functor);
            if (mHardwareAccelSkia != getSettings().getHardwareAccelSkiaEnabled()) {
                mHardwareAccelSkia = getSettings().getHardwareAccelSkiaEnabled();
                nativeUseHardwareAccelSkia(mHardwareAccelSkia);
            }

        } else {
            DrawFilter df = null;
            if (mZoomManager.isZoomAnimating() || UIAnimationsRunning) {
                df = mZoomFilter;
            } else if (animateScroll) {
                df = mScrollFilter;
            }
            canvas.setDrawFilter(df);
            nativeDraw(canvas, mVisibleContentRect, mBackgroundColor, extras);
            canvas.setDrawFilter(null);
        }

        canvas.restoreToCount(saveCount);
        drawTextSelectionHandles(canvas);

        if (extras == DRAW_EXTRAS_CURSOR_RING) {
            if (mTouchMode == TOUCH_SHORTPRESS_START_MODE) {
                mTouchMode = TOUCH_SHORTPRESS_MODE;
            }
        }
    }

    /**
     * Draw the background when beyond bounds
     * @param canvas Canvas to draw into
     */
    private void drawOverScrollBackground(Canvas canvas) {
        if (mOverScrollBackground == null) {
            mOverScrollBackground = new Paint();
            Bitmap bm = BitmapFactory.decodeResource(
                    mContext.getResources(),
                    com.android.internal.R.drawable.status_bar_background);
            mOverScrollBackground.setShader(new BitmapShader(bm,
                    Shader.TileMode.REPEAT, Shader.TileMode.REPEAT));
            mOverScrollBorder = new Paint();
            mOverScrollBorder.setStyle(Paint.Style.STROKE);
            mOverScrollBorder.setStrokeWidth(0);
            mOverScrollBorder.setColor(0xffbbbbbb);
        }

        int top = 0;
        int right = computeRealHorizontalScrollRange();
        int bottom = top + computeRealVerticalScrollRange();
        // first draw the background and anchor to the top of the view
        canvas.save();
        canvas.translate(getScrollX(), getScrollY());
        canvas.clipRect(-getScrollX(), top - getScrollY(), right - getScrollX(), bottom
                - getScrollY(), Region.Op.DIFFERENCE);
        canvas.drawPaint(mOverScrollBackground);
        canvas.restore();
        // then draw the border
        canvas.drawRect(-1, top - 1, right, bottom, mOverScrollBorder);
        // next clip the region for the content
        canvas.clipRect(0, top, right, bottom);
    }

    @Override
    public void onDraw(Canvas canvas) {
        if (inFullScreenMode()) {
            return; // no need to draw anything if we aren't visible.
        }
        // if mNativeClass is 0, the WebView is either destroyed or not
        // initialized. In either case, just draw the background color and return
        if (mNativeClass == 0) {
            canvas.drawColor(mBackgroundColor);
            return;
        }

        // if both mContentWidth and mContentHeight are 0, it means there is no
        // valid Picture passed to WebView yet. This can happen when WebView
        // just starts. Draw the background and return.
        if ((mContentWidth | mContentHeight) == 0 && mHistoryPicture == null) {
            canvas.drawColor(mBackgroundColor);
            return;
        }

        if (canvas.isHardwareAccelerated()) {
            mZoomManager.setHardwareAccelerated();
        } else {
            mWebViewCore.resumeWebKitDraw();
        }

        int saveCount = canvas.save();
        if (mInOverScrollMode && !getSettings()
                .getUseWebViewBackgroundForOverscrollBackground()) {
            drawOverScrollBackground(canvas);
        }

        canvas.translate(0, getTitleHeight());
        drawContent(canvas);
        canvas.restoreToCount(saveCount);

        if (AUTO_REDRAW_HACK && mAutoRedraw) {
            invalidate();
        }
        mWebViewCore.signalRepaintDone();

        if (mOverScrollGlow != null && mOverScrollGlow.drawEdgeGlows(canvas)) {
            invalidate();
        }

        if (mFocusTransition != null) {
            mFocusTransition.draw(canvas);
        } else if (shouldDrawHighlightRect()) {
            RegionIterator iter = new RegionIterator(mTouchHighlightRegion);
            Rect r = new Rect();
            while (iter.next(r)) {
                canvas.drawRect(r, mTouchHightlightPaint);
            }
        }
        if (DEBUG_TOUCH_HIGHLIGHT) {
            if (getSettings().getNavDump()) {
                if ((mTouchHighlightX | mTouchHighlightY) != 0) {
                    if (mTouchCrossHairColor == null) {
                        mTouchCrossHairColor = new Paint();
                        mTouchCrossHairColor.setColor(Color.RED);
                    }
                    canvas.drawLine(mTouchHighlightX - mNavSlop,
                            mTouchHighlightY - mNavSlop, mTouchHighlightX
                                    + mNavSlop + 1, mTouchHighlightY + mNavSlop
                                    + 1, mTouchCrossHairColor);
                    canvas.drawLine(mTouchHighlightX + mNavSlop + 1,
                            mTouchHighlightY - mNavSlop, mTouchHighlightX
                                    - mNavSlop,
                            mTouchHighlightY + mNavSlop + 1,
                            mTouchCrossHairColor);
                }
            }
        }
    }

    private void removeTouchHighlight() {
        setTouchHighlightRects(null);
    }

    @Override
    public void setLayoutParams(ViewGroup.LayoutParams params) {
        if (params.height == AbsoluteLayout.LayoutParams.WRAP_CONTENT) {
            mWrapContent = true;
        }
        mWebViewPrivate.super_setLayoutParams(params);
    }

    @Override
    public boolean performLongClick() {
        // performLongClick() is the result of a delayed message. If we switch
        // to windows overview, the WebView will be temporarily removed from the
        // view system. In that case, do nothing.
        if (mWebView.getParent() == null) return false;

        // A multi-finger gesture can look like a long press; make sure we don't take
        // long press actions if we're scaling.
        final ScaleGestureDetector detector = mZoomManager.getScaleGestureDetector();
        if (detector != null && detector.isInProgress()) {
            return false;
        }

        if (mSelectingText) return false; // long click does nothing on selection
        /* if long click brings up a context menu, the super function
         * returns true and we're done. Otherwise, nothing happened when
         * the user clicked. */
        if (mWebViewPrivate.super_performLongClick()) {
            return true;
        }
        /* In the case where the application hasn't already handled the long
         * click action, look for a word under the  click. If one is found,
         * animate the text selection into view.
         * FIXME: no animation code yet */
        final boolean isSelecting = selectText();
        if (isSelecting) {
            mWebView.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
        } else if (focusCandidateIsEditableText()) {
            mSelectCallback = new SelectActionModeCallback();
            mSelectCallback.setWebView(this);
            mSelectCallback.setTextSelected(false);
            mWebView.startActionMode(mSelectCallback);
        }
        return isSelecting;
    }

    /**
     * Select the word at the last click point.
     *
     * This is an implementation detail.
     */
    public boolean selectText() {
        int x = viewToContentX(mLastTouchX + getScrollX());
        int y = viewToContentY(mLastTouchY + getScrollY());
        return selectText(x, y);
    }

    /**
     * Select the word at the indicated content coordinates.
     */
    boolean selectText(int x, int y) {
        if (mWebViewCore == null) {
            return false;
        }
        mWebViewCore.sendMessage(EventHub.SELECT_WORD_AT, x, y);
        return true;
    }

    private int mOrientation = Configuration.ORIENTATION_UNDEFINED;

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        mCachedOverlappingActionModeHeight = -1;
        if (mSelectingText && mOrientation != newConfig.orientation) {
            selectionDone();
        }
        mOrientation = newConfig.orientation;
        if (mWebViewCore != null && !mBlockWebkitViewMessages) {
            mWebViewCore.sendMessage(EventHub.CLEAR_CONTENT);
        }
    }

    /**
     * Keep track of the Callback so we can end its ActionMode or remove its
     * titlebar.
     */
    private SelectActionModeCallback mSelectCallback;

    void setBaseLayer(int layer, boolean showVisualIndicator,
            boolean isPictureAfterFirstLayout) {
        if (mNativeClass == 0)
            return;
        boolean queueFull;
        final int scrollingLayer = (mTouchMode == TOUCH_DRAG_LAYER_MODE)
                ? mCurrentScrollingLayerId : 0;
        queueFull = nativeSetBaseLayer(mNativeClass, layer,
                                       showVisualIndicator, isPictureAfterFirstLayout,
                                       scrollingLayer);

        if (queueFull) {
            mWebViewCore.pauseWebKitDraw();
        } else {
            mWebViewCore.resumeWebKitDraw();
        }

        if (mHTML5VideoViewProxy != null) {
            mHTML5VideoViewProxy.setBaseLayer(layer);
        }
    }

    int getBaseLayer() {
        if (mNativeClass == 0) {
            return 0;
        }
        return nativeGetBaseLayer(mNativeClass);
    }

    private void onZoomAnimationStart() {
    }

    private void onZoomAnimationEnd() {
        mPrivateHandler.sendEmptyMessage(RELOCATE_AUTO_COMPLETE_POPUP);
    }

    void onFixedLengthZoomAnimationStart() {
        WebViewCore.pauseUpdatePicture(getWebViewCore());
        onZoomAnimationStart();
    }

    void onFixedLengthZoomAnimationEnd() {
        if (!mBlockWebkitViewMessages && !mSelectingText) {
            WebViewCore.resumeUpdatePicture(mWebViewCore);
        }
        onZoomAnimationEnd();
    }

    private static final int ZOOM_BITS = Paint.FILTER_BITMAP_FLAG |
                                         Paint.DITHER_FLAG |
                                         Paint.SUBPIXEL_TEXT_FLAG;
    private static final int SCROLL_BITS = Paint.FILTER_BITMAP_FLAG |
                                           Paint.DITHER_FLAG;

    private final DrawFilter mZoomFilter =
            new PaintFlagsDrawFilter(ZOOM_BITS, Paint.LINEAR_TEXT_FLAG);
    // If we need to trade better quality for speed, set mScrollFilter to null
    private final DrawFilter mScrollFilter =
            new PaintFlagsDrawFilter(SCROLL_BITS, 0);

    private class SelectionHandleAlpha {
        private int mAlpha = 0;
        private int mTargetAlpha = 0;

        public void setAlpha(int alpha) {
            mAlpha = alpha;
            // TODO: Use partial invalidate
            invalidate();
        }

        public int getAlpha() {
            return mAlpha;
        }

        public void setTargetAlpha(int alpha) {
            mTargetAlpha = alpha;
        }

        public int getTargetAlpha() {
            return mTargetAlpha;
        }

    }

    private void startSelectingText() {
        mSelectingText = true;
        mShowTextSelectionExtra = true;
        animateHandles();
    }

    private void animateHandle(boolean canShow, ObjectAnimator animator,
            Point selectionPoint, int selectionLayerId,
            SelectionHandleAlpha alpha) {
        boolean isVisible = canShow && mSelectingText
                && ((mSelectionStarted && mSelectDraggingCursor == selectionPoint)
                || isHandleVisible(selectionPoint, selectionLayerId));
        int targetValue = isVisible ? 255 : 0;
        if (targetValue != alpha.getTargetAlpha()) {
            alpha.setTargetAlpha(targetValue);
            animator.setIntValues(targetValue);
            animator.setDuration(SELECTION_HANDLE_ANIMATION_MS);
            animator.start();
        }
    }

    private void animateHandles() {
        boolean canShowBase = mSelectingText;
        boolean canShowExtent = mSelectingText && !mIsCaretSelection;
        animateHandle(canShowBase, mBaseHandleAlphaAnimator, mSelectCursorBase,
                mSelectCursorBaseLayerId, mBaseAlpha);
        animateHandle(canShowExtent, mExtentHandleAlphaAnimator,
                mSelectCursorExtent, mSelectCursorExtentLayerId,
                mExtentAlpha);
    }

    private void endSelectingText() {
        mSelectingText = false;
        mShowTextSelectionExtra = false;
        animateHandles();
    }

    private void ensureSelectionHandles() {
        if (mSelectHandleCenter == null) {
            mSelectHandleCenter = mContext.getResources().getDrawable(
                    com.android.internal.R.drawable.text_select_handle_middle).mutate();
            mSelectHandleLeft = mContext.getResources().getDrawable(
                    com.android.internal.R.drawable.text_select_handle_left).mutate();
            mSelectHandleRight = mContext.getResources().getDrawable(
                    com.android.internal.R.drawable.text_select_handle_right).mutate();
            // All handles have the same height, so we can save effort with
            // this assumption.
            mSelectOffset = new Point(0,
                    -mSelectHandleLeft.getIntrinsicHeight());
        }
    }

    private void drawHandle(Point point, int handleId, Rect bounds,
            int alpha, Canvas canvas) {
        int offset;
        int width;
        int height;
        Drawable drawable;
        boolean isLeft = nativeIsHandleLeft(mNativeClass, handleId);
        if (isLeft) {
            drawable = mSelectHandleLeft;
            width = mSelectHandleLeft.getIntrinsicWidth();
            height = mSelectHandleLeft.getIntrinsicHeight();
            // Magic formula copied from TextView
            offset = (width * 3) / 4;
        } else {
            drawable = mSelectHandleRight;
            width = mSelectHandleRight.getIntrinsicWidth();
            height = mSelectHandleRight.getIntrinsicHeight();
            // Magic formula copied from TextView
            offset = width / 4;
        }
        int x = contentToViewDimension(point.x);
        int y = contentToViewDimension(point.y);
        bounds.set(x - offset, y, x - offset + width, y + height);
        drawable.setBounds(bounds);
        drawable.setAlpha(alpha);
        drawable.draw(canvas);
    }

    private void drawTextSelectionHandles(Canvas canvas) {
        if (mBaseAlpha.getAlpha() == 0 && mExtentAlpha.getAlpha() == 0) {
            return;
        }
        ensureSelectionHandles();
        if (mIsCaretSelection) {
            // Caret handle is centered
            int x = contentToViewDimension(mSelectCursorBase.x) -
                    (mSelectHandleCenter.getIntrinsicWidth() / 2);
            int y = contentToViewDimension(mSelectCursorBase.y);
            mSelectHandleBaseBounds.set(x, y,
                    x + mSelectHandleCenter.getIntrinsicWidth(),
                    y + mSelectHandleCenter.getIntrinsicHeight());
            mSelectHandleCenter.setBounds(mSelectHandleBaseBounds);
            mSelectHandleCenter.setAlpha(mBaseAlpha.getAlpha());
            mSelectHandleCenter.draw(canvas);
        } else {
            drawHandle(mSelectCursorBase, HANDLE_ID_BASE,
                    mSelectHandleBaseBounds, mBaseAlpha.getAlpha(), canvas);
            drawHandle(mSelectCursorExtent, HANDLE_ID_EXTENT,
                    mSelectHandleExtentBounds, mExtentAlpha.getAlpha(), canvas);
        }
    }

    private boolean isHandleVisible(Point selectionPoint, int layerId) {
        boolean isVisible = true;
        if (mIsEditingText) {
            isVisible = mEditTextContentBounds.contains(selectionPoint.x,
                    selectionPoint.y);
        }
        if (isVisible) {
            isVisible = nativeIsPointVisible(mNativeClass, layerId,
                    selectionPoint.x, selectionPoint.y);
        }
        return isVisible;
    }

    /**
     * Takes an int[4] array as an output param with the values being
     * startX, startY, endX, endY
     */
    private void getSelectionHandles(int[] handles) {
        handles[0] = mSelectCursorBase.x;
        handles[1] = mSelectCursorBase.y;
        handles[2] = mSelectCursorExtent.x;
        handles[3] = mSelectCursorExtent.y;
    }

    // draw history
    private boolean mDrawHistory = false;
    private Picture mHistoryPicture = null;
    private int mHistoryWidth = 0;
    private int mHistoryHeight = 0;

    // Only check the flag, can be called from WebCore thread
    boolean drawHistory() {
        return mDrawHistory;
    }

    int getHistoryPictureWidth() {
        return (mHistoryPicture != null) ? mHistoryPicture.getWidth() : 0;
    }

    // Should only be called in UI thread
    void switchOutDrawHistory() {
        if (null == mWebViewCore) return; // CallbackProxy may trigger this
        if (mDrawHistory && (getProgress() == 100 || nativeHasContent())) {
            mDrawHistory = false;
            mHistoryPicture = null;
            invalidate();
            int oldScrollX = getScrollX();
            int oldScrollY = getScrollY();
            setScrollXRaw(pinLocX(getScrollX()));
            setScrollYRaw(pinLocY(getScrollY()));
            if (oldScrollX != getScrollX() || oldScrollY != getScrollY()) {
                mWebViewPrivate.onScrollChanged(getScrollX(), getScrollY(), oldScrollX, oldScrollY);
            } else {
                sendOurVisibleRect();
            }
        }
    }

    /**
     *  Delete text from start to end in the focused textfield. If there is no
     *  focus, or if start == end, silently fail.  If start and end are out of
     *  order, swap them.
     *  @param  start   Beginning of selection to delete.
     *  @param  end     End of selection to delete.
     */
    /* package */ void deleteSelection(int start, int end) {
        mTextGeneration++;
        WebViewCore.TextSelectionData data
                = new WebViewCore.TextSelectionData(start, end, 0);
        mWebViewCore.sendMessage(EventHub.DELETE_SELECTION, mTextGeneration, 0,
                data);
    }

    /**
     *  Set the selection to (start, end) in the focused textfield. If start and
     *  end are out of order, swap them.
     *  @param  start   Beginning of selection.
     *  @param  end     End of selection.
     */
    /* package */ void setSelection(int start, int end) {
        if (mWebViewCore != null) {
            mWebViewCore.sendMessage(EventHub.SET_SELECTION, start, end);
        }
    }

    @Override
    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
        if (mInputConnection == null) {
            mInputConnection = new WebViewInputConnection();
            mAutoCompletePopup = new AutoCompletePopup(this, mInputConnection);
        }
        mInputConnection.setupEditorInfo(outAttrs);
        return mInputConnection;
    }

    private void relocateAutoCompletePopup() {
        if (mAutoCompletePopup != null) {
            mAutoCompletePopup.resetRect();
            mAutoCompletePopup.setText(mInputConnection.getEditable());
        }
    }

    /**
     * Called in response to a message from webkit telling us that the soft
     * keyboard should be launched.
     */
    private void displaySoftKeyboard(boolean isTextView) {
        InputMethodManager imm = (InputMethodManager)
                mContext.getSystemService(Context.INPUT_METHOD_SERVICE);

        // bring it back to the default level scale so that user can enter text
        boolean zoom = mZoomManager.getScale() < mZoomManager.getDefaultScale();
        if (zoom) {
            mZoomManager.setZoomCenter(mLastTouchX, mLastTouchY);
            mZoomManager.setZoomScale(mZoomManager.getDefaultScale(), false);
        }
        // Used by plugins and contentEditable.
        // Also used if the navigation cache is out of date, and
        // does not recognize that a textfield is in focus.  In that
        // case, use WebView as the targeted view.
        // see http://b/issue?id=2457459
        imm.showSoftInput(mWebView, 0);
    }

    // Called by WebKit to instruct the UI to hide the keyboard
    private void hideSoftKeyboard() {
        InputMethodManager imm = InputMethodManager.peekInstance();
        if (imm != null && (imm.isActive(mWebView))) {
            imm.hideSoftInputFromWindow(mWebView.getWindowToken(), 0);
        }
    }

    /**
     * Called by AutoCompletePopup to find saved form data associated with the
     * textfield
     * @param name Name of the textfield.
     * @param nodePointer Pointer to the node of the textfield, so it can be
     *          compared to the currently focused textfield when the data is
     *          retrieved.
     * @param autoFillable true if WebKit has determined this field is part of
     *          a form that can be auto filled.
     * @param autoComplete true if the attribute "autocomplete" is set to true
     *          on the textfield.
     */
    /* package */ void requestFormData(String name, int nodePointer,
            boolean autoFillable, boolean autoComplete) {
        if (mWebViewCore.getSettings().getSaveFormData()) {
            Message update = mPrivateHandler.obtainMessage(REQUEST_FORM_DATA);
            update.arg1 = nodePointer;
            RequestFormData updater = new RequestFormData(name, getUrl(),
                    update, autoFillable, autoComplete);
            Thread t = new Thread(updater);
            t.start();
        }
    }

    /*
     * This class requests an Adapter for the AutoCompletePopup which shows past
     * entries stored in the database.  It is a Runnable so that it can be done
     * in its own thread, without slowing down the UI.
     */
    private class RequestFormData implements Runnable {
        private String mName;
        private String mUrl;
        private Message mUpdateMessage;
        private boolean mAutoFillable;
        private boolean mAutoComplete;
        private WebSettingsClassic mWebSettings;

        public RequestFormData(String name, String url, Message msg,
                boolean autoFillable, boolean autoComplete) {
            mName = name;
            mUrl = WebTextView.urlForAutoCompleteData(url);
            mUpdateMessage = msg;
            mAutoFillable = autoFillable;
            mAutoComplete = autoComplete;
            mWebSettings = getSettings();
        }

        @Override
        public void run() {
            ArrayList<String> pastEntries = new ArrayList<String>();

            if (mAutoFillable) {
                // Note that code inside the adapter click handler in AutoCompletePopup depends
                // on the AutoFill item being at the top of the drop down list. If you change
                // the order, make sure to do it there too!
                if (mWebSettings != null && mWebSettings.getAutoFillProfile() != null) {
                    pastEntries.add(mWebView.getResources().getText(
                            com.android.internal.R.string.autofill_this_form).toString() +
                            " " +
                    mAutoFillData.getPreviewString());
                    mAutoCompletePopup.setIsAutoFillProfileSet(true);
                } else {
                    // There is no autofill profile set up yet, so add an option that
                    // will invite the user to set their profile up.
                    pastEntries.add(mWebView.getResources().getText(
                            com.android.internal.R.string.setup_autofill).toString());
                    mAutoCompletePopup.setIsAutoFillProfileSet(false);
                }
            }

            if (mAutoComplete) {
                pastEntries.addAll(mDatabase.getFormData(mUrl, mName));
            }

            if (pastEntries.size() > 0) {
                ArrayAdapter<String> adapter = new ArrayAdapter<String>(
                        mContext,
                        com.android.internal.R.layout.web_text_view_dropdown,
                        pastEntries);
                mUpdateMessage.obj = adapter;
                mUpdateMessage.sendToTarget();
            }
        }
    }

    /**
     * Dump the display tree to "/sdcard/displayTree.txt"
     *
     * debug only
     */
    public void dumpDisplayTree() {
        nativeDumpDisplayTree(getUrl());
    }

    /**
     * Dump the dom tree to adb shell if "toFile" is False, otherwise dump it to
     * "/sdcard/domTree.txt"
     *
     * debug only
     */
    public void dumpDomTree(boolean toFile) {
        mWebViewCore.sendMessage(EventHub.DUMP_DOMTREE, toFile ? 1 : 0, 0);
    }

    /**
     * Dump the render tree to adb shell if "toFile" is False, otherwise dump it
     * to "/sdcard/renderTree.txt"
     *
     * debug only
     */
    public void dumpRenderTree(boolean toFile) {
        mWebViewCore.sendMessage(EventHub.DUMP_RENDERTREE, toFile ? 1 : 0, 0);
    }

    /**
     * Called by DRT on UI thread, need to proxy to WebCore thread.
     *
     * debug only
     */
    public void setUseMockDeviceOrientation() {
        mWebViewCore.sendMessage(EventHub.SET_USE_MOCK_DEVICE_ORIENTATION);
    }

    /**
     * Sets use of the Geolocation mock client. Also resets that client. Called
     * by DRT on UI thread, need to proxy to WebCore thread.
     *
     * debug only
     */
    public void setUseMockGeolocation() {
        mWebViewCore.sendMessage(EventHub.SET_USE_MOCK_GEOLOCATION);
    }

    /**
     * Called by DRT on WebCore thread.
     *
     * debug only
     */
    public void setMockGeolocationPosition(double latitude, double longitude, double accuracy) {
        mWebViewCore.setMockGeolocationPosition(latitude, longitude, accuracy);
    }

    /**
     * Called by DRT on WebCore thread.
     *
     * debug only
     */
    public void setMockGeolocationError(int code, String message) {
        mWebViewCore.setMockGeolocationError(code, message);
    }

    /**
     * Called by DRT on WebCore thread.
     *
     * debug only
     */
    public void setMockGeolocationPermission(boolean allow) {
        mWebViewCore.setMockGeolocationPermission(allow);
    }

    /**
     * Called by DRT on WebCore thread.
     *
     * debug only
     */
    public void setMockDeviceOrientation(boolean canProvideAlpha, double alpha,
            boolean canProvideBeta, double beta, boolean canProvideGamma, double gamma) {
        mWebViewCore.setMockDeviceOrientation(canProvideAlpha, alpha, canProvideBeta, beta,
                canProvideGamma, gamma);
    }

    // This is used to determine long press with the center key.  Does not
    // affect long press with the trackball/touch.
    private boolean mGotCenterDown = false;

    @Override
    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
        if (mBlockWebkitViewMessages) {
            return false;
        }
        // send complex characters to webkit for use by JS and plugins
        if (keyCode == KeyEvent.KEYCODE_UNKNOWN && event.getCharacters() != null) {
            // pass the key to DOM
            sendBatchableInputMessage(EventHub.KEY_DOWN, 0, 0, event);
            sendBatchableInputMessage(EventHub.KEY_UP, 0, 0, event);
            // return true as DOM handles the key
            return true;
        }
        return false;
    }

    private boolean isEnterActionKey(int keyCode) {
        return keyCode == KeyEvent.KEYCODE_DPAD_CENTER
                || keyCode == KeyEvent.KEYCODE_ENTER
                || keyCode == KeyEvent.KEYCODE_NUMPAD_ENTER;
    }

    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
        if (mAutoCompletePopup != null) {
            return mAutoCompletePopup.onKeyPreIme(keyCode, event);
        }
        return false;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (DebugFlags.WEB_VIEW) {
            Log.v(LOGTAG, "keyDown at " + System.currentTimeMillis()
                    + "keyCode=" + keyCode
                    + ", " + event + ", unicode=" + event.getUnicodeChar());
        }
        if (mIsCaretSelection) {
            selectionDone();
        }
        if (mBlockWebkitViewMessages) {
            return false;
        }

        // don't implement accelerator keys here; defer to host application
        if (event.isCtrlPressed()) {
            return false;
        }

        if (mNativeClass == 0) {
            return false;
        }

        // do this hack up front, so it always works, regardless of touch-mode
        if (AUTO_REDRAW_HACK && (keyCode == KeyEvent.KEYCODE_CALL)) {
            mAutoRedraw = !mAutoRedraw;
            if (mAutoRedraw) {
                invalidate();
            }
            return true;
        }

        // Bubble up the key event if
        // 1. it is a system key; or
        // 2. the host application wants to handle it;
        if (event.isSystem()
                || mCallbackProxy.uiOverrideKeyEvent(event)) {
            return false;
        }

        // See if the accessibility injector needs to handle this event.
        if (isAccessibilityInjectionEnabled()
                && getAccessibilityInjector().handleKeyEventIfNecessary(event)) {
            return true;
        }

        if (keyCode == KeyEvent.KEYCODE_PAGE_UP) {
            if (event.hasNoModifiers()) {
                pageUp(false);
                return true;
            } else if (event.hasModifiers(KeyEvent.META_ALT_ON)) {
                pageUp(true);
                return true;
            }
        }

        if (keyCode == KeyEvent.KEYCODE_PAGE_DOWN) {
            if (event.hasNoModifiers()) {
                pageDown(false);
                return true;
            } else if (event.hasModifiers(KeyEvent.META_ALT_ON)) {
                pageDown(true);
                return true;
            }
        }

        if (keyCode == KeyEvent.KEYCODE_MOVE_HOME && event.hasNoModifiers()) {
            pageUp(true);
            return true;
        }

        if (keyCode == KeyEvent.KEYCODE_MOVE_END && event.hasNoModifiers()) {
            pageDown(true);
            return true;
        }

        if (keyCode >= KeyEvent.KEYCODE_DPAD_UP
                && keyCode <= KeyEvent.KEYCODE_DPAD_RIGHT) {
            switchOutDrawHistory();
        }

        if (isEnterActionKey(keyCode)) {
            switchOutDrawHistory();
            if (event.getRepeatCount() == 0) {
                if (mSelectingText) {
                    return true; // discard press if copy in progress
                }
                mGotCenterDown = true;
                mPrivateHandler.sendMessageDelayed(mPrivateHandler
                        .obtainMessage(LONG_PRESS_CENTER), LONG_PRESS_TIMEOUT);
            }
        }

        if (getSettings().getNavDump()) {
            switch (keyCode) {
                case KeyEvent.KEYCODE_4:
                    dumpDisplayTree();
                    break;
                case KeyEvent.KEYCODE_5:
                case KeyEvent.KEYCODE_6:
                    dumpDomTree(keyCode == KeyEvent.KEYCODE_5);
                    break;
                case KeyEvent.KEYCODE_7:
                case KeyEvent.KEYCODE_8:
                    dumpRenderTree(keyCode == KeyEvent.KEYCODE_7);
                    break;
            }
        }

        // pass the key to DOM
        sendKeyEvent(event);
        // return true as DOM handles the key
        return true;
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (DebugFlags.WEB_VIEW) {
            Log.v(LOGTAG, "keyUp at " + System.currentTimeMillis()
                    + ", " + event + ", unicode=" + event.getUnicodeChar());
        }
        if (mBlockWebkitViewMessages) {
            return false;
        }

        if (mNativeClass == 0) {
            return false;
        }

        // special CALL handling when cursor node's href is "tel:XXX"
        if (keyCode == KeyEvent.KEYCODE_CALL
                && mInitialHitTestResult != null
                && mInitialHitTestResult.getType() == HitTestResult.PHONE_TYPE) {
            String text = mInitialHitTestResult.getExtra();
            Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(text));
            mContext.startActivity(intent);
            return true;
        }

        // Bubble up the key event if
        // 1. it is a system key; or
        // 2. the host application wants to handle it;
        if (event.isSystem()
                || mCallbackProxy.uiOverrideKeyEvent(event)) {
            return false;
        }

        // See if the accessibility injector needs to handle this event.
        if (isAccessibilityInjectionEnabled()
                && getAccessibilityInjector().handleKeyEventIfNecessary(event)) {
            return true;
        }

        if (isEnterActionKey(keyCode)) {
            // remove the long press message first
            mPrivateHandler.removeMessages(LONG_PRESS_CENTER);
            mGotCenterDown = false;

            if (mSelectingText) {
                copySelection();
                selectionDone();
                return true; // discard press if copy in progress
            }
        }

        // pass the key to DOM
        sendKeyEvent(event);
        // return true as DOM handles the key
        return true;
    }

    private boolean startSelectActionMode() {
        mSelectCallback = new SelectActionModeCallback();
        mSelectCallback.setTextSelected(!mIsCaretSelection);
        mSelectCallback.setWebView(this);
        if (mWebView.startActionMode(mSelectCallback) == null) {
            // There is no ActionMode, so do not allow the user to modify a
            // selection.
            selectionDone();
            return false;
        }
        mWebView.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
        return true;
    }

    private void showPasteWindow() {
        ClipboardManager cm = (ClipboardManager)(mContext
                .getSystemService(Context.CLIPBOARD_SERVICE));
        if (cm.hasPrimaryClip()) {
            Point cursorPoint = new Point(contentToViewX(mSelectCursorBase.x),
                    contentToViewY(mSelectCursorBase.y));
            Point cursorTop = calculateCaretTop();
            cursorTop.set(contentToViewX(cursorTop.x),
                    contentToViewY(cursorTop.y));

            int[] location = new int[2];
            mWebView.getLocationInWindow(location);
            int offsetX = location[0] - getScrollX();
            int offsetY = location[1] - getScrollY();
            cursorPoint.offset(offsetX, offsetY);
            cursorTop.offset(offsetX, offsetY);
            if (mPasteWindow == null) {
                mPasteWindow = new PastePopupWindow();
            }
            mPasteWindow.show(cursorPoint, cursorTop, location[0], location[1]);
        }
    }

    /**
     * Given segment AB, this finds the point C along AB that is closest to
     * point and then returns it scale along AB. The scale factor is AC/AB.
     *
     * @param x The x coordinate of the point near segment AB that determines
     * the scale factor.
     * @param y The y coordinate of the point near segment AB that determines
     * the scale factor.
     * @param a The first point of the line segment.
     * @param b The second point of the line segment.
     * @return The scale factor AC/AB, where C is the point on AB closest to
     *         point.
     */
    private static float scaleAlongSegment(int x, int y, PointF a, PointF b) {
        // The bottom line of the text box is line AB
        float abX = b.x - a.x;
        float abY = b.y - a.y;
        float ab2 = (abX * abX) + (abY * abY);

        // The line from first point in text bounds to bottom is AP
        float apX = x - a.x;
        float apY = y - a.y;
        float abDotAP = (apX * abX) + (apY * abY);
        float scale = abDotAP / ab2;
        return scale;
    }

    /**
     * Assuming arbitrary shape of a quadralateral forming text bounds, this
     * calculates the top of a caret.
     */
    private Point calculateCaretTop() {
        float scale = scaleAlongSegment(mSelectCursorBase.x, mSelectCursorBase.y,
                mSelectCursorBaseTextQuad.p4, mSelectCursorBaseTextQuad.p3);
        int x = Math.round(scaleCoordinate(scale,
                mSelectCursorBaseTextQuad.p1.x, mSelectCursorBaseTextQuad.p2.x));
        int y = Math.round(scaleCoordinate(scale,
                mSelectCursorBaseTextQuad.p1.y, mSelectCursorBaseTextQuad.p2.y));
        return new Point(x, y);
    }

    private void hidePasteButton() {
        if (mPasteWindow != null) {
            mPasteWindow.hide();
        }
    }

    private void syncSelectionCursors() {
        mSelectCursorBaseLayerId =
                nativeGetHandleLayerId(mNativeClass, HANDLE_ID_BASE,
                        mSelectCursorBase, mSelectCursorBaseTextQuad);
        mSelectCursorExtentLayerId =
                nativeGetHandleLayerId(mNativeClass, HANDLE_ID_EXTENT,
                        mSelectCursorExtent, mSelectCursorExtentTextQuad);
    }

    private boolean setupWebkitSelect() {
        syncSelectionCursors();
        if (!mIsCaretSelection && !startSelectActionMode()) {
            selectionDone();
            return false;
        }
        startSelectingText();
        mTouchMode = TOUCH_DRAG_MODE;
        return true;
    }

    private void updateWebkitSelection() {
        int handleId = (mSelectDraggingCursor == mSelectCursorBase)
                ? HANDLE_ID_BASE : HANDLE_ID_EXTENT;
        mWebViewCore.removeMessages(EventHub.SELECT_TEXT);
        mWebViewCore.sendMessageAtFrontOfQueue(EventHub.SELECT_TEXT,
                mSelectDraggingCursor.x, mSelectDraggingCursor.y, (Integer)handleId);
    }

    private void resetCaretTimer() {
        mPrivateHandler.removeMessages(CLEAR_CARET_HANDLE);
        if (!mSelectionStarted) {
            mPrivateHandler.sendEmptyMessageDelayed(CLEAR_CARET_HANDLE,
                    CARET_HANDLE_STAMINA_MS);
        }
    }

    /**
     * Select all of the text in this WebView.
     *
     * This is an implementation detail.
     */
    public void selectAll() {
        mWebViewCore.sendMessage(EventHub.SELECT_ALL);
    }

    /**
     * Called when the selection has been removed.
     */
    void selectionDone() {
        if (mSelectingText) {
            hidePasteButton();
            endSelectingText();
            // finish is idempotent, so this is fine even if selectionDone was
            // called by mSelectCallback.onDestroyActionMode
            if (mSelectCallback != null) {
                mSelectCallback.finish();
                mSelectCallback = null;
            }
            invalidate(); // redraw without selection
            mAutoScrollX = 0;
            mAutoScrollY = 0;
            mSentAutoScrollMessage = false;
        }
    }

    /**
     * Copy the selection to the clipboard
     *
     * This is an implementation detail.
     */
    public boolean copySelection() {
        boolean copiedSomething = false;
        String selection = getSelection();
        if (selection != null && selection != "") {
            if (DebugFlags.WEB_VIEW) {
                Log.v(LOGTAG, "copySelection \"" + selection + "\"");
            }
            Toast.makeText(mContext
                    , com.android.internal.R.string.text_copied
                    , Toast.LENGTH_SHORT).show();
            copiedSomething = true;
            ClipboardManager cm = (ClipboardManager)mContext
                    .getSystemService(Context.CLIPBOARD_SERVICE);
            cm.setText(selection);
            int[] handles = new int[4];
            getSelectionHandles(handles);
            mWebViewCore.sendMessage(EventHub.COPY_TEXT, handles);
        }
        invalidate(); // remove selection region and pointer
        return copiedSomething;
    }

    /**
     * Cut the selected text into the clipboard
     *
     * This is an implementation detail
     */
    public void cutSelection() {
        copySelection();
        int[] handles = new int[4];
        getSelectionHandles(handles);
        mWebViewCore.sendMessage(EventHub.DELETE_TEXT, handles);
    }

    /**
     * Paste text from the clipboard to the cursor position.
     *
     * This is an implementation detail
     */
    public void pasteFromClipboard() {
        ClipboardManager cm = (ClipboardManager)mContext
                .getSystemService(Context.CLIPBOARD_SERVICE);
        ClipData clipData = cm.getPrimaryClip();
        if (clipData != null) {
            ClipData.Item clipItem = clipData.getItemAt(0);
            CharSequence pasteText = clipItem.getText();
            if (mInputConnection != null) {
                mInputConnection.replaceSelection(pasteText);
            }
        }
    }

    /**
     * Returns the currently highlighted text as a string.
     */
    String getSelection() {
        if (mNativeClass == 0) return "";
        return nativeGetSelection();
    }

    @Override
    public void onAttachedToWindow() {
        if (mWebView.hasWindowFocus()) setActive(true);

        if (isAccessibilityInjectionEnabled()) {
            getAccessibilityInjector().addAccessibilityApisIfNecessary();
        }

        updateHwAccelerated();
    }

    @Override
    public void onDetachedFromWindow() {
        clearHelpers();
        mZoomManager.dismissZoomPicker();
        if (mWebView.hasWindowFocus()) setActive(false);

        if (isAccessibilityInjectionEnabled()) {
            getAccessibilityInjector().removeAccessibilityApisIfNecessary();
        } else {
            // Ensure the injector is cleared if we're detaching from the window
            // and accessibility is disabled.
            mAccessibilityInjector = null;
        }

        updateHwAccelerated();

        ensureFunctorDetached();
    }

    @Override
    public void onVisibilityChanged(View changedView, int visibility) {
        // The zoomManager may be null if the webview is created from XML that
        // specifies the view's visibility param as not visible (see http://b/2794841)
        if (visibility != View.VISIBLE && mZoomManager != null) {
            mZoomManager.dismissZoomPicker();
        }
        updateDrawingState();
    }

    void setActive(boolean active) {
        if (active) {
            if (mWebView.hasFocus()) {
                // If our window regained focus, and we have focus, then begin
                // drawing the cursor ring
                mDrawCursorRing = true;
                setFocusControllerActive(true);
            } else {
                mDrawCursorRing = false;
                setFocusControllerActive(false);
            }
        } else {
            if (!mZoomManager.isZoomPickerVisible()) {
                /*
                 * The external zoom controls come in their own window, so our
                 * window loses focus. Our policy is to not draw the cursor ring
                 * if our window is not focused, but this is an exception since
                 * the user can still navigate the web page with the zoom
                 * controls showing.
                 */
                mDrawCursorRing = false;
            }
            mKeysPressed.clear();
            mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
            mTouchMode = TOUCH_DONE_MODE;
            setFocusControllerActive(false);
        }
        invalidate();
    }

    // To avoid drawing the cursor ring, and remove the TextView when our window
    // loses focus.
    @Override
    public void onWindowFocusChanged(boolean hasWindowFocus) {
        setActive(hasWindowFocus);
        if (hasWindowFocus) {
            JWebCoreJavaBridge.setActiveWebView(this);
            if (mPictureUpdatePausedForFocusChange) {
                WebViewCore.resumeUpdatePicture(mWebViewCore);
                mPictureUpdatePausedForFocusChange = false;
            }
        } else {
            JWebCoreJavaBridge.removeActiveWebView(this);
            final WebSettings settings = getSettings();
            if (settings != null && settings.enableSmoothTransition() &&
                    mWebViewCore != null && !WebViewCore.isUpdatePicturePaused(mWebViewCore)) {
                WebViewCore.pauseUpdatePicture(mWebViewCore);
                mPictureUpdatePausedForFocusChange = true;
            }
        }
    }

    /*
     * Pass a message to WebCore Thread, telling the WebCore::Page's
     * FocusController to be  "inactive" so that it will
     * not draw the blinking cursor.  It gets set to "active" to draw the cursor
     * in WebViewCore.cpp, when the WebCore thread receives key events/clicks.
     */
    /* package */ void setFocusControllerActive(boolean active) {
        if (mWebViewCore == null) return;
        mWebViewCore.sendMessage(EventHub.SET_ACTIVE, active ? 1 : 0, 0);
        // Need to send this message after the document regains focus.
        if (active && mListBoxMessage != null) {
            mWebViewCore.sendMessage(mListBoxMessage);
            mListBoxMessage = null;
        }
    }

    @Override
    public void onFocusChanged(boolean focused, int direction,
            Rect previouslyFocusedRect) {
        if (DebugFlags.WEB_VIEW) {
            Log.v(LOGTAG, "MT focusChanged " + focused + ", " + direction);
        }
        if (focused) {
            mDrawCursorRing = true;
            setFocusControllerActive(true);
        } else {
            mDrawCursorRing = false;
            setFocusControllerActive(false);
            mKeysPressed.clear();
        }
        if (!mTouchHighlightRegion.isEmpty()) {
            mWebView.invalidate(mTouchHighlightRegion.getBounds());
        }
    }

    // updateRectsForGL() happens almost every draw call, in order to avoid creating
    // any object in this code path, we move the local variable out to be a private
    // final member, and we marked them as mTemp*.
    private final Point mTempVisibleRectOffset = new Point();
    private final Rect mTempVisibleRect = new Rect();

    void updateRectsForGL() {
        // Use the getGlobalVisibleRect() to get the intersection among the parents
        // visible == false means we're clipped - send a null rect down to indicate that
        // we should not draw
        boolean visible = mWebView.getGlobalVisibleRect(mTempVisibleRect, mTempVisibleRectOffset);
        mInvScreenRect.set(mTempVisibleRect);
        if (visible) {
            // Then need to invert the Y axis, just for GL
            View rootView = mWebView.getRootView();
            int rootViewHeight = rootView.getHeight();
            mScreenRect.set(mInvScreenRect);
            int savedWebViewBottom = mInvScreenRect.bottom;
            mInvScreenRect.bottom = rootViewHeight - mInvScreenRect.top - getVisibleTitleHeightImpl();
            mInvScreenRect.top = rootViewHeight - savedWebViewBottom;
            mIsWebViewVisible = true;
        } else {
            mIsWebViewVisible = false;
        }

        mTempVisibleRect.offset(-mTempVisibleRectOffset.x, -mTempVisibleRectOffset.y);
        viewToContentVisibleRect(mVisibleContentRect, mTempVisibleRect);

        nativeUpdateDrawGLFunction(mNativeClass, mIsWebViewVisible ? mInvScreenRect : null,
                mIsWebViewVisible ? mScreenRect : null,
                mVisibleContentRect, getScale());
    }

    // Input : viewRect, rect in view/screen coordinate.
    // Output: contentRect, rect in content/document coordinate.
    private void viewToContentVisibleRect(RectF contentRect, Rect viewRect) {
        contentRect.left = viewToContentXf(viewRect.left) / mWebView.getScaleX();
        // viewToContentY will remove the total height of the title bar.  Add
        // the visible height back in to account for the fact that if the title
        // bar is partially visible, the part of the visible rect which is
        // displaying our content is displaced by that amount.
        contentRect.top = viewToContentYf(viewRect.top + getVisibleTitleHeightImpl())
                / mWebView.getScaleY();
        contentRect.right = viewToContentXf(viewRect.right) / mWebView.getScaleX();
        contentRect.bottom = viewToContentYf(viewRect.bottom) / mWebView.getScaleY();
    }

    @Override
    public boolean setFrame(int left, int top, int right, int bottom) {
        boolean changed = mWebViewPrivate.super_setFrame(left, top, right, bottom);
        if (!changed && mHeightCanMeasure) {
            // When mHeightCanMeasure is true, we will set mLastHeightSent to 0
            // in WebViewCore after we get the first layout. We do call
            // requestLayout() when we get contentSizeChanged(). But the View
            // system won't call onSizeChanged if the dimension is not changed.
            // In this case, we need to call sendViewSizeZoom() explicitly to
            // notify the WebKit about the new dimensions.
            sendViewSizeZoom(false);
        }
        updateRectsForGL();
        return changed;
    }

    @Override
    public void onSizeChanged(int w, int h, int ow, int oh) {
        // adjust the max viewport width depending on the view dimensions. This
        // is to ensure the scaling is not going insane. So do not shrink it if
        // the view size is temporarily smaller, e.g. when soft keyboard is up.
        int newMaxViewportWidth = (int) (Math.max(w, h) / mZoomManager.getDefaultMinZoomScale());
        if (newMaxViewportWidth > sMaxViewportWidth) {
            sMaxViewportWidth = newMaxViewportWidth;
        }

        mZoomManager.onSizeChanged(w, h, ow, oh);

        if (mLoadedPicture != null && mDelaySetPicture == null) {
            // Size changes normally result in a new picture
            // Re-set the loaded picture to simulate that
            // However, do not update the base layer as that hasn't changed
            setNewPicture(mLoadedPicture, false);
        }
        if (mIsEditingText) {
            scrollEditIntoView();
        }
        relocateAutoCompletePopup();
    }

    /**
     * Scrolls the edit field into view using the minimum scrolling necessary.
     * If the edit field is too large to fit in the visible window, the caret
     * dimensions are used so that at least the caret is visible.
     * A buffer of EDIT_RECT_BUFFER in view pixels is used to offset the
     * edit rectangle to ensure a margin with the edge of the screen.
     */
    private void scrollEditIntoView() {
        Rect visibleRect = new Rect(viewToContentX(getScrollX()),
                viewToContentY(getScrollY()),
                viewToContentX(getScrollX() + getWidth()),
                viewToContentY(getScrollY() + getViewHeightWithTitle()));
        if (visibleRect.contains(mEditTextContentBounds)) {
            return; // no need to scroll
        }
        syncSelectionCursors();
        nativeFindMaxVisibleRect(mNativeClass, mEditTextLayerId, visibleRect);
        final int buffer = Math.max(1, viewToContentDimension(EDIT_RECT_BUFFER));
        Rect showRect = new Rect(
                Math.max(0, mEditTextContentBounds.left - buffer),
                Math.max(0, mEditTextContentBounds.top - buffer),
                mEditTextContentBounds.right + buffer,
                mEditTextContentBounds.bottom + buffer);
        Point caretTop = calculateCaretTop();
        if (visibleRect.width() < mEditTextContentBounds.width()) {
            // The whole edit won't fit in the width, so use the caret rect
            if (mSelectCursorBase.x < caretTop.x) {
                showRect.left = Math.max(0, mSelectCursorBase.x - buffer);
                showRect.right = caretTop.x + buffer;
            } else {
                showRect.left = Math.max(0, caretTop.x - buffer);
                showRect.right = mSelectCursorBase.x + buffer;
            }
        }
        if (visibleRect.height() < mEditTextContentBounds.height()) {
            // The whole edit won't fit in the height, so use the caret rect
            if (mSelectCursorBase.y > caretTop.y) {
                showRect.top = Math.max(0, caretTop.y - buffer);
                showRect.bottom = mSelectCursorBase.y + buffer;
            } else {
                showRect.top = Math.max(0, mSelectCursorBase.y - buffer);
                showRect.bottom = caretTop.y + buffer;
            }
        }

        if (visibleRect.contains(showRect)) {
            return; // no need to scroll
        }

        int scrollX = viewToContentX(getScrollX());
        if (visibleRect.left > showRect.left) {
            // We are scrolled too far
            scrollX += showRect.left - visibleRect.left;
        } else if (visibleRect.right < showRect.right) {
            // We aren't scrolled enough to include the right
            scrollX += showRect.right - visibleRect.right;
        }
        int scrollY = viewToContentY(getScrollY());
        if (visibleRect.top > showRect.top) {
            scrollY += showRect.top - visibleRect.top;
        } else if (visibleRect.bottom < showRect.bottom) {
            scrollY += showRect.bottom - visibleRect.bottom;
        }

        contentScrollTo(scrollX, scrollY, false);
    }

    @Override
    public void onScrollChanged(int l, int t, int oldl, int oldt) {
        if (!mInOverScrollMode) {
            sendOurVisibleRect();
            // update WebKit if visible title bar height changed. The logic is same
            // as getVisibleTitleHeightImpl.
            int titleHeight = getTitleHeight();
            if (Math.max(titleHeight - t, 0) != Math.max(titleHeight - oldt, 0)) {
                sendViewSizeZoom(false);
            }
        }
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        switch (event.getAction()) {
            case KeyEvent.ACTION_DOWN:
                mKeysPressed.add(Integer.valueOf(event.getKeyCode()));
                break;
            case KeyEvent.ACTION_MULTIPLE:
                // Always accept the action.
                break;
            case KeyEvent.ACTION_UP:
                int location = mKeysPressed.indexOf(Integer.valueOf(event.getKeyCode()));
                if (location == -1) {
                    // We did not receive the key down for this key, so do not
                    // handle the key up.
                    return false;
                } else {
                    // We did receive the key down.  Handle the key up, and
                    // remove it from our pressed keys.
                    mKeysPressed.remove(location);
                }
                break;
            default:
                // Accept the action.  This should not happen, unless a new
                // action is added to KeyEvent.
                break;
        }
        return mWebViewPrivate.super_dispatchKeyEvent(event);
    }

    /*
     * Here is the snap align logic:
     * 1. If it starts nearly horizontally or vertically, snap align;
     * 2. If there is a dramitic direction change, let it go;
     *
     * Adjustable parameters. Angle is the radians on a unit circle, limited
     * to quadrant 1. Values range from 0f (horizontal) to PI/2 (vertical)
     */
    private static final float HSLOPE_TO_START_SNAP = .25f;
    private static final float HSLOPE_TO_BREAK_SNAP = .4f;
    private static final float VSLOPE_TO_START_SNAP = 1.25f;
    private static final float VSLOPE_TO_BREAK_SNAP = .95f;
    /*
     *  These values are used to influence the average angle when entering
     *  snap mode. If is is the first movement entering snap, we set the average
     *  to the appropriate ideal. If the user is entering into snap after the
     *  first movement, then we average the average angle with these values.
     */
    private static final float ANGLE_VERT = 2f;
    private static final float ANGLE_HORIZ = 0f;
    /*
     *  The modified moving average weight.
     *  Formula: MAV[t]=MAV[t-1] + (P[t]-MAV[t-1])/n
     */
    private static final float MMA_WEIGHT_N = 5;

    private boolean inFullScreenMode() {
        return mFullScreenHolder != null;
    }

    private void dismissFullScreenMode() {
        if (inFullScreenMode()) {
            mFullScreenHolder.hide();
            mFullScreenHolder = null;
            invalidate();
        }
    }

    void onPinchToZoomAnimationStart() {
        // cancel the single touch handling
        cancelTouch();
        onZoomAnimationStart();
    }

    void onPinchToZoomAnimationEnd(ScaleGestureDetector detector) {
        onZoomAnimationEnd();
        // start a drag, TOUCH_PINCH_DRAG, can't use TOUCH_INIT_MODE as
        // it may trigger the unwanted click, can't use TOUCH_DRAG_MODE
        // as it may trigger the unwanted fling.
        mTouchMode = TOUCH_PINCH_DRAG;
        mConfirmMove = true;
        startTouch(detector.getFocusX(), detector.getFocusY(), mLastTouchTime);
    }

    // See if there is a layer at x, y and switch to TOUCH_DRAG_LAYER_MODE if a
    // layer is found.
    private void startScrollingLayer(float x, float y) {
        if (mNativeClass == 0)
            return;

        int contentX = viewToContentX((int) x + getScrollX());
        int contentY = viewToContentY((int) y + getScrollY());
        mCurrentScrollingLayerId = nativeScrollableLayer(mNativeClass,
                contentX, contentY, mScrollingLayerRect, mScrollingLayerBounds);
        if (mCurrentScrollingLayerId != 0) {
            mTouchMode = TOUCH_DRAG_LAYER_MODE;
        }
    }

    // 1/(density * density) used to compute the distance between points.
    // Computed in init().
    private float DRAG_LAYER_INVERSE_DENSITY_SQUARED;

    // The distance between two points reported in onTouchEvent scaled by the
    // density of the screen.
    private static final int DRAG_LAYER_FINGER_DISTANCE = 20000;

    @Override
    public boolean onHoverEvent(MotionEvent event) {
        if (mNativeClass == 0) {
            return false;
        }
        int x = viewToContentX((int) event.getX() + getScrollX());
        int y = viewToContentY((int) event.getY() + getScrollY());
        mWebViewCore.sendMessage(EventHub.SET_MOVE_MOUSE, x, y);
        mWebViewPrivate.super_onHoverEvent(event);
        return true;
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        if (mNativeClass == 0 || (!mWebView.isClickable() && !mWebView.isLongClickable())) {
            return false;
        }

        if (mInputDispatcher == null) {
            return false;
        }

        if (mWebView.isFocusable() && mWebView.isFocusableInTouchMode()
                && !mWebView.isFocused()) {
            mWebView.requestFocus();
        }

        if (mInputDispatcher.postPointerEvent(ev, getScrollX(),
                getScrollY() - getTitleHeight(), mZoomManager.getInvScale())) {
            mInputDispatcher.dispatchUiEvents();
            return true;
        } else {
            Log.w(LOGTAG, "mInputDispatcher rejected the event!");
            return false;
        }
    }

    private float calculateDragAngle(int dx, int dy) {
        dx = Math.abs(dx);
        dy = Math.abs(dy);
        return (float) Math.atan2(dy, dx);
    }

    /*
    * Common code for single touch and multi-touch.
    * (x, y) denotes current focus point, which is the touch point for single touch
    * and the middle point for multi-touch.
    */
    private void handleTouchEventCommon(MotionEvent event, int action, int x, int y) {
        ScaleGestureDetector detector = mZoomManager.getScaleGestureDetector();

        long eventTime = event.getEventTime();

        // Due to the touch screen edge effect, a touch closer to the edge
        // always snapped to the edge. As getViewWidth() can be different from
        // getWidth() due to the scrollbar, adjusting the point to match
        // getViewWidth(). Same applied to the height.
        x = Math.min(x, getViewWidth() - 1);
        y = Math.min(y, getViewHeightWithTitle() - 1);

        int deltaX = mLastTouchX - x;
        int deltaY = mLastTouchY - y;
        int contentX = viewToContentX(x + getScrollX());
        int contentY = viewToContentY(y + getScrollY());

        switch (action) {
            case MotionEvent.ACTION_DOWN: {
                mConfirmMove = false;
                if (!mEditTextScroller.isFinished()) {
                    mEditTextScroller.abortAnimation();
                }
                if (!mScroller.isFinished()) {
                    // stop the current scroll animation, but if this is
                    // the start of a fling, allow it to add to the current
                    // fling's velocity
                    mScroller.abortAnimation();
                    mTouchMode = TOUCH_DRAG_START_MODE;
                    mConfirmMove = true;
                    nativeSetIsScrolling(false);
                } else if (mPrivateHandler.hasMessages(RELEASE_SINGLE_TAP)) {
                    mPrivateHandler.removeMessages(RELEASE_SINGLE_TAP);
                    removeTouchHighlight();
                    if (deltaX * deltaX + deltaY * deltaY < mDoubleTapSlopSquare) {
                        mTouchMode = TOUCH_DOUBLE_TAP_MODE;
                    } else {
                        mTouchMode = TOUCH_INIT_MODE;
                    }
                } else { // the normal case
                    mTouchMode = TOUCH_INIT_MODE;
                    if (mLogEvent && eventTime - mLastTouchUpTime < 1000) {
                        EventLog.writeEvent(EventLogTags.BROWSER_DOUBLE_TAP_DURATION,
                                (eventTime - mLastTouchUpTime), eventTime);
                    }
                    mSelectionStarted = false;
                    if (mSelectingText) {
                        ensureSelectionHandles();
                        int shiftedY = y - getTitleHeight() + getScrollY();
                        int shiftedX = x + getScrollX();
                        if (mSelectHandleBaseBounds.contains(shiftedX, shiftedY)) {
                            mSelectionStarted = true;
                            mSelectDraggingCursor = mSelectCursorBase;
                            mSelectDraggingTextQuad = mSelectCursorBaseTextQuad;
                            if (mIsCaretSelection) {
                                mPrivateHandler.removeMessages(CLEAR_CARET_HANDLE);
                                hidePasteButton();
                            }
                        } else if (mSelectHandleExtentBounds
                                .contains(shiftedX, shiftedY)) {
                            mSelectionStarted = true;
                            mSelectDraggingCursor = mSelectCursorExtent;
                            mSelectDraggingTextQuad = mSelectCursorExtentTextQuad;
                        } else if (mIsCaretSelection) {
                            selectionDone();
                        }
                        if (DebugFlags.WEB_VIEW) {
                            Log.v(LOGTAG, "select=" + contentX + "," + contentY);
                        }
                    }
                }
                // Trigger the link
                if (!mSelectingText && (mTouchMode == TOUCH_INIT_MODE
                        || mTouchMode == TOUCH_DOUBLE_TAP_MODE)) {
                    mPrivateHandler.sendEmptyMessageDelayed(
                            SWITCH_TO_SHORTPRESS, TAP_TIMEOUT);
                    mPrivateHandler.sendEmptyMessageDelayed(
                            SWITCH_TO_LONGPRESS, LONG_PRESS_TIMEOUT);
                }
                startTouch(x, y, eventTime);
                if (mIsEditingText) {
                    mTouchInEditText = mEditTextContentBounds
                            .contains(contentX, contentY);
                }
                break;
            }
            case MotionEvent.ACTION_MOVE: {
                if (!mConfirmMove && (deltaX * deltaX + deltaY * deltaY)
                        >= mTouchSlopSquare) {
                    mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS);
                    mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
                    mConfirmMove = true;
                    if (mTouchMode == TOUCH_DOUBLE_TAP_MODE) {
                        mTouchMode = TOUCH_INIT_MODE;
                    }
                    removeTouchHighlight();
                }
                if (mSelectingText && mSelectionStarted) {
                    if (DebugFlags.WEB_VIEW) {
                        Log.v(LOGTAG, "extend=" + contentX + "," + contentY);
                    }
                    ViewParent parent = mWebView.getParent();
                    if (parent != null) {
                        parent.requestDisallowInterceptTouchEvent(true);
                    }
                    if (deltaX != 0 || deltaY != 0) {
                        int handleX = contentX +
                                viewToContentDimension(mSelectOffset.x);
                        int handleY = contentY +
                                viewToContentDimension(mSelectOffset.y);
                        mSelectDraggingCursor.set(handleX, handleY);
                        boolean inCursorText =
                                mSelectDraggingTextQuad.containsPoint(handleX, handleY);
                        boolean inEditBounds = mEditTextContentBounds
                                .contains(handleX, handleY);
                        if (mIsEditingText && !inEditBounds) {
                            beginScrollEdit();
                        } else {
                            endScrollEdit();
                        }
                        if (inCursorText || (mIsEditingText && !inEditBounds)) {
                            snapDraggingCursor();
                        }
                        updateWebkitSelection();
                        if (!inCursorText && mIsEditingText && inEditBounds) {
                            // Visually snap even if we have moved the handle.
                            snapDraggingCursor();
                        }
                        mLastTouchX = x;
                        mLastTouchY = y;
                        invalidate();
                    }
                    break;
                }

                if (mTouchMode == TOUCH_DONE_MODE) {
                    // no dragging during scroll zoom animation, or when prevent
                    // default is yes
                    break;
                }
                if (mVelocityTracker == null) {
                    Log.e(LOGTAG, "Got null mVelocityTracker when "
                            + " mTouchMode = " + mTouchMode);
                } else {
                    mVelocityTracker.addMovement(event);
                }

                if (mTouchMode != TOUCH_DRAG_MODE &&
                        mTouchMode != TOUCH_DRAG_LAYER_MODE &&
                        mTouchMode != TOUCH_DRAG_TEXT_MODE) {

                    if (!mConfirmMove) {
                        break;
                    }

                    // Only lock dragging to one axis if we don't have a scale in progress.
                    // Scaling implies free-roaming movement. Note this is only ever a question
                    // if mZoomManager.supportsPanDuringZoom() is true.
                    mAverageAngle = calculateDragAngle(deltaX, deltaY);
                    if (detector == null || !detector.isInProgress()) {
                        // if it starts nearly horizontal or vertical, enforce it
                        if (mAverageAngle < HSLOPE_TO_START_SNAP) {
                            mSnapScrollMode = SNAP_X;
                            mSnapPositive = deltaX > 0;
                            mAverageAngle = ANGLE_HORIZ;
                        } else if (mAverageAngle > VSLOPE_TO_START_SNAP) {
                            mSnapScrollMode = SNAP_Y;
                            mSnapPositive = deltaY > 0;
                            mAverageAngle = ANGLE_VERT;
                        }
                    }

                    mTouchMode = TOUCH_DRAG_MODE;
                    mLastTouchX = x;
                    mLastTouchY = y;
                    deltaX = 0;
                    deltaY = 0;

                    startScrollingLayer(x, y);
                    startDrag();
                }

                // do pan
                boolean keepScrollBarsVisible = false;
                if (deltaX == 0 && deltaY == 0) {
                    keepScrollBarsVisible = true;
                } else {
                    mAverageAngle +=
                        (calculateDragAngle(deltaX, deltaY) - mAverageAngle)
                        / MMA_WEIGHT_N;
                    if (mSnapScrollMode != SNAP_NONE) {
                        if (mSnapScrollMode == SNAP_Y) {
                            // radical change means getting out of snap mode
                            if (mAverageAngle < VSLOPE_TO_BREAK_SNAP) {
                                mSnapScrollMode = SNAP_NONE;
                            }
                        }
                        if (mSnapScrollMode == SNAP_X) {
                            // radical change means getting out of snap mode
                            if (mAverageAngle > HSLOPE_TO_BREAK_SNAP) {
                                mSnapScrollMode = SNAP_NONE;
                            }
                        }
                    } else {
                        if (mAverageAngle < HSLOPE_TO_START_SNAP) {
                            mSnapScrollMode = SNAP_X;
                            mSnapPositive = deltaX > 0;
                            mAverageAngle = (mAverageAngle + ANGLE_HORIZ) / 2;
                        } else if (mAverageAngle > VSLOPE_TO_START_SNAP) {
                            mSnapScrollMode = SNAP_Y;
                            mSnapPositive = deltaY > 0;
                            mAverageAngle = (mAverageAngle + ANGLE_VERT) / 2;
                        }
                    }
                    if (mSnapScrollMode != SNAP_NONE) {
                        if ((mSnapScrollMode & SNAP_X) == SNAP_X) {
                            deltaY = 0;
                        } else {
                            deltaX = 0;
                        }
                    }
                    if (deltaX * deltaX + deltaY * deltaY > mTouchSlopSquare) {
                        mHeldMotionless = MOTIONLESS_FALSE;
                    } else {
                        mHeldMotionless = MOTIONLESS_TRUE;
                        keepScrollBarsVisible = true;
                    }

                    mLastTouchTime = eventTime;
                    boolean allDrag = doDrag(deltaX, deltaY);
                    if (allDrag) {
                        mLastTouchX = x;
                        mLastTouchY = y;
                    } else {
                        int contentDeltaX = (int)Math.floor(deltaX * mZoomManager.getInvScale());
                        int roundedDeltaX = contentToViewDimension(contentDeltaX);
                        int contentDeltaY = (int)Math.floor(deltaY * mZoomManager.getInvScale());
                        int roundedDeltaY = contentToViewDimension(contentDeltaY);
                        mLastTouchX -= roundedDeltaX;
                        mLastTouchY -= roundedDeltaY;
                    }
                }

                break;
            }
            case MotionEvent.ACTION_UP: {
                if (mIsEditingText && mSelectionStarted) {
                    endScrollEdit();
                    mPrivateHandler.sendEmptyMessageDelayed(SCROLL_HANDLE_INTO_VIEW,
                            TEXT_SCROLL_FIRST_SCROLL_MS);
                    if (!mConfirmMove && mIsCaretSelection) {
                        showPasteWindow();
                        stopTouch();
                        break;
                    }
                }
                mLastTouchUpTime = eventTime;
                if (mSentAutoScrollMessage) {
                    mAutoScrollX = mAutoScrollY = 0;
                }
                switch (mTouchMode) {
                    case TOUCH_DOUBLE_TAP_MODE: // double tap
                        mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS);
                        mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
                        mTouchMode = TOUCH_DONE_MODE;
                        break;
                    case TOUCH_INIT_MODE: // tap
                    case TOUCH_SHORTPRESS_START_MODE:
                    case TOUCH_SHORTPRESS_MODE:
                        mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS);
                        mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
                        if (!mConfirmMove) {
                            if (mSelectingText) {
                                // tapping on selection or controls does nothing
                                if (!mSelectionStarted) {
                                    selectionDone();
                                }
                                break;
                            }
                            // only trigger double tap if the WebView is
                            // scalable
                            if (mTouchMode == TOUCH_INIT_MODE
                                    && (canZoomIn() || canZoomOut())) {
                                mPrivateHandler.sendEmptyMessageDelayed(
                                        RELEASE_SINGLE_TAP, ViewConfiguration
                                                .getDoubleTapTimeout());
                            }
                            break;
                        }
                    case TOUCH_DRAG_MODE:
                    case TOUCH_DRAG_LAYER_MODE:
                    case TOUCH_DRAG_TEXT_MODE:
                        mPrivateHandler.removeMessages(DRAG_HELD_MOTIONLESS);
                        // if the user waits a while w/o moving before the
                        // up, we don't want to do a fling
                        if (eventTime - mLastTouchTime <= MIN_FLING_TIME) {
                            if (mVelocityTracker == null) {
                                Log.e(LOGTAG, "Got null mVelocityTracker");
                            } else {
                                mVelocityTracker.addMovement(event);
                            }
                            // set to MOTIONLESS_IGNORE so that it won't keep
                            // removing and sending message in
                            // drawCoreAndCursorRing()
                            mHeldMotionless = MOTIONLESS_IGNORE;
                            doFling();
                            break;
                        } else {
                            if (mScroller.springBack(getScrollX(), getScrollY(), 0,
                                    computeMaxScrollX(), 0,
                                    computeMaxScrollY())) {
                                invalidate();
                            }
                        }
                        // redraw in high-quality, as we're done dragging
                        mHeldMotionless = MOTIONLESS_TRUE;
                        invalidate();
                        // fall through
                    case TOUCH_DRAG_START_MODE:
                        // TOUCH_DRAG_START_MODE should not happen for the real
                        // device as we almost certain will get a MOVE. But this
                        // is possible on emulator.
                        mLastVelocity = 0;
                        WebViewCore.resumePriority();
                        if (!mSelectingText) {
                            WebViewCore.resumeUpdatePicture(mWebViewCore);
                        }
                        break;
                }
                stopTouch();
                break;
            }
            case MotionEvent.ACTION_CANCEL: {
                if (mTouchMode == TOUCH_DRAG_MODE) {
                    mScroller.springBack(getScrollX(), getScrollY(), 0,
                            computeMaxScrollX(), 0, computeMaxScrollY());
                    invalidate();
                }
                cancelTouch();
                break;
            }
        }
    }

    /**
     * Returns the text scroll speed in content pixels per millisecond based on
     * the touch location.
     * @param coordinate The x or y touch coordinate in content space
     * @param min The minimum coordinate (x or y) of the edit content bounds
     * @param max The maximum coordinate (x or y) of the edit content bounds
     */
    private static float getTextScrollSpeed(int coordinate, int min, int max) {
        if (coordinate < min) {
            return (coordinate - min) * TEXT_SCROLL_RATE;
        } else if (coordinate >= max) {
            return (coordinate - max + 1) * TEXT_SCROLL_RATE;
        } else {
            return 0.0f;
        }
    }

    private static int getSelectionCoordinate(int coordinate, int min, int max) {
        return Math.max(Math.min(coordinate, max), min);
    }

    private void beginScrollEdit() {
        if (mLastEditScroll == 0) {
            mLastEditScroll = SystemClock.uptimeMillis() -
                    TEXT_SCROLL_FIRST_SCROLL_MS;
            scrollEditWithCursor();
        }
    }

    private void scrollDraggedSelectionHandleIntoView() {
        if (mSelectDraggingCursor == null) {
            return;
        }
        int x = mSelectDraggingCursor.x;
        int y = mSelectDraggingCursor.y;
        if (!mEditTextContentBounds.contains(x,y)) {
            int left = Math.min(0, x - mEditTextContentBounds.left - EDIT_RECT_BUFFER);
            int right = Math.max(0, x - mEditTextContentBounds.right + EDIT_RECT_BUFFER);
            int deltaX = left + right;
            int above = Math.min(0, y - mEditTextContentBounds.top - EDIT_RECT_BUFFER);
            int below = Math.max(0, y - mEditTextContentBounds.bottom + EDIT_RECT_BUFFER);
            int deltaY = above + below;
            if (deltaX != 0 || deltaY != 0) {
                int scrollX = getTextScrollX() + deltaX;
                int scrollY = getTextScrollY() + deltaY;
                scrollX = clampBetween(scrollX, 0, getMaxTextScrollX());
                scrollY = clampBetween(scrollY, 0, getMaxTextScrollY());
                scrollEditText(scrollX, scrollY);
            }
        }
    }

    private void endScrollEdit() {
        mLastEditScroll = 0;
    }

    private static int clampBetween(int value, int min, int max) {
        return Math.max(min, Math.min(value, max));
    }

    private static int getTextScrollDelta(float speed, long deltaT) {
        float distance = speed * deltaT;
        int intDistance = (int)Math.floor(distance);
        float probability = distance - intDistance;
        if (Math.random() < probability) {
            intDistance++;
        }
        return intDistance;
    }
    /**
     * Scrolls edit text a distance based on the last touch point,
     * the last scroll time, and the edit text content bounds.
     */
    private void scrollEditWithCursor() {
        if (mLastEditScroll != 0) {
            int x = viewToContentX(mLastTouchX + getScrollX() + mSelectOffset.x);
            float scrollSpeedX = getTextScrollSpeed(x, mEditTextContentBounds.left,
                    mEditTextContentBounds.right);
            int y = viewToContentY(mLastTouchY + getScrollY() + mSelectOffset.y);
            float scrollSpeedY = getTextScrollSpeed(y, mEditTextContentBounds.top,
                    mEditTextContentBounds.bottom);
            if (scrollSpeedX == 0.0f && scrollSpeedY == 0.0f) {
                endScrollEdit();
            } else {
                long currentTime = SystemClock.uptimeMillis();
                long timeSinceLastUpdate = currentTime - mLastEditScroll;
                int deltaX = getTextScrollDelta(scrollSpeedX, timeSinceLastUpdate);
                int deltaY = getTextScrollDelta(scrollSpeedY, timeSinceLastUpdate);
                int scrollX = getTextScrollX() + deltaX;
                scrollX = clampBetween(scrollX, 0, getMaxTextScrollX());
                int scrollY = getTextScrollY() + deltaY;
                scrollY = clampBetween(scrollY, 0, getMaxTextScrollY());

                mLastEditScroll = currentTime;
                if (scrollX == getTextScrollX() && scrollY == getTextScrollY()) {
                    // By probability no text scroll this time. Try again later.
                    mPrivateHandler.sendEmptyMessageDelayed(SCROLL_EDIT_TEXT,
                            TEXT_SCROLL_FIRST_SCROLL_MS);
                } else {
                    int selectionX = getSelectionCoordinate(x,
                            mEditTextContentBounds.left, mEditTextContentBounds.right);
                    int selectionY = getSelectionCoordinate(y,
                            mEditTextContentBounds.top, mEditTextContentBounds.bottom);
                    int oldX = mSelectDraggingCursor.x;
                    int oldY = mSelectDraggingCursor.y;
                    mSelectDraggingCursor.set(selectionX, selectionY);
                    updateWebkitSelection();
                    scrollEditText(scrollX, scrollY);
                    mSelectDraggingCursor.set(oldX, oldY);
                }
            }
        }
    }

    private void startTouch(float x, float y, long eventTime) {
        // Remember where the motion event started
        mStartTouchX = mLastTouchX = Math.round(x);
        mStartTouchY = mLastTouchY = Math.round(y);
        mLastTouchTime = eventTime;
        mVelocityTracker = VelocityTracker.obtain();
        mSnapScrollMode = SNAP_NONE;
    }

    private void startDrag() {
        WebViewCore.reducePriority();
        // to get better performance, pause updating the picture
        WebViewCore.pauseUpdatePicture(mWebViewCore);
        nativeSetIsScrolling(true);

        if (mHorizontalScrollBarMode != SCROLLBAR_ALWAYSOFF
                || mVerticalScrollBarMode != SCROLLBAR_ALWAYSOFF) {
            mZoomManager.invokeZoomPicker();
        }
    }

    private boolean doDrag(int deltaX, int deltaY) {
        boolean allDrag = true;
        if ((deltaX | deltaY) != 0) {
            int oldX = getScrollX();
            int oldY = getScrollY();
            int rangeX = computeMaxScrollX();
            int rangeY = computeMaxScrollY();
            final int contentX = (int)Math.floor(deltaX * mZoomManager.getInvScale());
            final int contentY = (int)Math.floor(deltaY * mZoomManager.getInvScale());

            // Assume page scrolling and change below if we're wrong
            mTouchMode = TOUCH_DRAG_MODE;

            // Check special scrolling before going to main page scrolling.
            if (mIsEditingText && mTouchInEditText && canTextScroll(deltaX, deltaY)) {
                // Edit text scrolling
                oldX = getTextScrollX();
                rangeX = getMaxTextScrollX();
                deltaX = contentX;
                oldY = getTextScrollY();
                rangeY = getMaxTextScrollY();
                deltaY = contentY;
                mTouchMode = TOUCH_DRAG_TEXT_MODE;
                allDrag = false;
            } else if (mCurrentScrollingLayerId != 0) {
                // Check the scrolling bounds to see if we will actually do any
                // scrolling.  The rectangle is in document coordinates.
                final int maxX = mScrollingLayerRect.right;
                final int maxY = mScrollingLayerRect.bottom;
                final int resultX = clampBetween(maxX, 0,
                        mScrollingLayerRect.left + contentX);
                final int resultY = clampBetween(maxY, 0,
                        mScrollingLayerRect.top + contentY);

                if (resultX != mScrollingLayerRect.left
                        || resultY != mScrollingLayerRect.top
                        || (contentX | contentY) == 0) {
                    // In case we switched to dragging the page.
                    mTouchMode = TOUCH_DRAG_LAYER_MODE;
                    deltaX = contentX;
                    deltaY = contentY;
                    oldX = mScrollingLayerRect.left;
                    oldY = mScrollingLayerRect.top;
                    rangeX = maxX;
                    rangeY = maxY;
                    allDrag = false;
                }
            }

            if (mOverScrollGlow != null) {
                mOverScrollGlow.setOverScrollDeltas(deltaX, deltaY);
            }

            mWebViewPrivate.overScrollBy(deltaX, deltaY, oldX, oldY,
                    rangeX, rangeY,
                    mOverscrollDistance, mOverscrollDistance, true);
            if (mOverScrollGlow != null && mOverScrollGlow.isAnimating()) {
                invalidate();
            }
        }
        mZoomManager.keepZoomPickerVisible();
        return allDrag;
    }

    private void stopTouch() {
        if (mScroller.isFinished() && !mSelectingText
                && (mTouchMode == TOUCH_DRAG_MODE
                || mTouchMode == TOUCH_DRAG_LAYER_MODE)) {
            WebViewCore.resumePriority();
            WebViewCore.resumeUpdatePicture(mWebViewCore);
            nativeSetIsScrolling(false);
        }

        // we also use mVelocityTracker == null to tell us that we are
        // not "moving around", so we can take the slower/prettier
        // mode in the drawing code
        if (mVelocityTracker != null) {
            mVelocityTracker.recycle();
            mVelocityTracker = null;
        }

        // Release any pulled glows
        if (mOverScrollGlow != null) {
            mOverScrollGlow.releaseAll();
        }

        if (mSelectingText) {
            mSelectionStarted = false;
            syncSelectionCursors();
            if (mIsCaretSelection) {
                resetCaretTimer();
            }
            invalidate();
        }
    }

    private void cancelTouch() {
        // we also use mVelocityTracker == null to tell us that we are
        // not "moving around", so we can take the slower/prettier
        // mode in the drawing code
        if (mVelocityTracker != null) {
            mVelocityTracker.recycle();
            mVelocityTracker = null;
        }

        if ((mTouchMode == TOUCH_DRAG_MODE
                || mTouchMode == TOUCH_DRAG_LAYER_MODE) && !mSelectingText) {
            WebViewCore.resumePriority();
            WebViewCore.resumeUpdatePicture(mWebViewCore);
            nativeSetIsScrolling(false);
        }
        mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS);
        mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
        mPrivateHandler.removeMessages(DRAG_HELD_MOTIONLESS);
        removeTouchHighlight();
        mHeldMotionless = MOTIONLESS_TRUE;
        mTouchMode = TOUCH_DONE_MODE;
    }

    private void snapDraggingCursor() {
        float scale = scaleAlongSegment(
                mSelectDraggingCursor.x, mSelectDraggingCursor.y,
                mSelectDraggingTextQuad.p4, mSelectDraggingTextQuad.p3);
        // clamp scale to ensure point is on the bottom segment
        scale = Math.max(0.0f, scale);
        scale = Math.min(scale, 1.0f);
        float newX = scaleCoordinate(scale,
                mSelectDraggingTextQuad.p4.x, mSelectDraggingTextQuad.p3.x);
        float newY = scaleCoordinate(scale,
                mSelectDraggingTextQuad.p4.y, mSelectDraggingTextQuad.p3.y);
        int x = Math.round(newX);
        int y = Math.round(newY);
        if (mIsEditingText) {
            x = clampBetween(x, mEditTextContentBounds.left,
                    mEditTextContentBounds.right);
            y = clampBetween(y, mEditTextContentBounds.top,
                    mEditTextContentBounds.bottom);
        }
        mSelectDraggingCursor.set(x, y);
    }

    private static float scaleCoordinate(float scale, float coord1, float coord2) {
        float diff = coord2 - coord1;
        return coord1 + (scale * diff);
    }

    @Override
    public boolean onGenericMotionEvent(MotionEvent event) {
        if ((event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_SCROLL: {
                    final float vscroll;
                    final float hscroll;
                    if ((event.getMetaState() & KeyEvent.META_SHIFT_ON) != 0) {
                        vscroll = 0;
                        hscroll = event.getAxisValue(MotionEvent.AXIS_VSCROLL);
                    } else {
                        vscroll = -event.getAxisValue(MotionEvent.AXIS_VSCROLL);
                        hscroll = event.getAxisValue(MotionEvent.AXIS_HSCROLL);
                    }
                    if (hscroll != 0 || vscroll != 0) {
                        final int vdelta = (int) (vscroll *
                                mWebViewPrivate.getVerticalScrollFactor());
                        final int hdelta = (int) (hscroll *
                                mWebViewPrivate.getHorizontalScrollFactor());

                        abortAnimation();
                        int oldTouchMode = mTouchMode;
                        startScrollingLayer(event.getX(), event.getY());
                        doDrag(hdelta, vdelta);
                        mTouchMode = oldTouchMode;
                        return true;
                    }
                }
            }
        }
        return mWebViewPrivate.super_onGenericMotionEvent(event);
    }

    private long mTrackballFirstTime = 0;
    private long mTrackballLastTime = 0;
    private float mTrackballRemainsX = 0.0f;
    private float mTrackballRemainsY = 0.0f;
    private int mTrackballXMove = 0;
    private int mTrackballYMove = 0;
    private boolean mSelectingText = false;
    private boolean mShowTextSelectionExtra = false;
    private boolean mSelectionStarted = false;
    private static final int TRACKBALL_KEY_TIMEOUT = 1000;
    private static final int TRACKBALL_TIMEOUT = 200;
    private static final int TRACKBALL_WAIT = 100;
    private static final int TRACKBALL_SCALE = 400;
    private static final int TRACKBALL_SCROLL_COUNT = 5;
    private static final int TRACKBALL_MOVE_COUNT = 10;
    private static final int TRACKBALL_MULTIPLIER = 3;
    private static final int SELECT_CURSOR_OFFSET = 16;
    private static final int SELECT_SCROLL = 5;
    private int mSelectX = 0;
    private int mSelectY = 0;
    private boolean mTrackballDown = false;
    private long mTrackballUpTime = 0;
    private long mLastCursorTime = 0;
    private Rect mLastCursorBounds;
    private SelectionHandleAlpha mBaseAlpha = new SelectionHandleAlpha();
    private SelectionHandleAlpha mExtentAlpha = new SelectionHandleAlpha();
    private ObjectAnimator mBaseHandleAlphaAnimator =
            ObjectAnimator.ofInt(mBaseAlpha, "alpha", 0);
    private ObjectAnimator mExtentHandleAlphaAnimator =
            ObjectAnimator.ofInt(mExtentAlpha, "alpha", 0);

    // Set by default; BrowserActivity clears to interpret trackball data
    // directly for movement. Currently, the framework only passes
    // arrow key events, not trackball events, from one child to the next
    private boolean mMapTrackballToArrowKeys = true;

    private DrawData mDelaySetPicture;
    private DrawData mLoadedPicture;

    @Override
    public void setMapTrackballToArrowKeys(boolean setMap) {
        mMapTrackballToArrowKeys = setMap;
    }

    void resetTrackballTime() {
        mTrackballLastTime = 0;
    }

    @Override
    public boolean onTrackballEvent(MotionEvent ev) {
        long time = ev.getEventTime();
        if ((ev.getMetaState() & KeyEvent.META_ALT_ON) != 0) {
            if (ev.getY() > 0) pageDown(true);
            if (ev.getY() < 0) pageUp(true);
            return true;
        }
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            if (mSelectingText) {
                return true; // discard press if copy in progress
            }
            mTrackballDown = true;
            if (mNativeClass == 0) {
                return false;
            }
            if (DebugFlags.WEB_VIEW) {
                Log.v(LOGTAG, "onTrackballEvent down ev=" + ev
                        + " time=" + time
                        + " mLastCursorTime=" + mLastCursorTime);
            }
            if (mWebView.isInTouchMode()) mWebView.requestFocusFromTouch();
            return false; // let common code in onKeyDown at it
        }
        if (ev.getAction() == MotionEvent.ACTION_UP) {
            // LONG_PRESS_CENTER is set in common onKeyDown
            mPrivateHandler.removeMessages(LONG_PRESS_CENTER);
            mTrackballDown = false;
            mTrackballUpTime = time;
            if (mSelectingText) {
                copySelection();
                selectionDone();
                return true; // discard press if copy in progress
            }
            if (DebugFlags.WEB_VIEW) {
                Log.v(LOGTAG, "onTrackballEvent up ev=" + ev
                        + " time=" + time
                );
            }
            return false; // let common code in onKeyUp at it
        }
        if ((mMapTrackballToArrowKeys && (ev.getMetaState() & KeyEvent.META_SHIFT_ON) == 0) ||
                AccessibilityManager.getInstance(mContext).isEnabled()) {
            if (DebugFlags.WEB_VIEW) Log.v(LOGTAG, "onTrackballEvent gmail quit");
            return false;
        }
        if (mTrackballDown) {
            if (DebugFlags.WEB_VIEW) Log.v(LOGTAG, "onTrackballEvent down quit");
            return true; // discard move if trackball is down
        }
        if (time - mTrackballUpTime < TRACKBALL_TIMEOUT) {
            if (DebugFlags.WEB_VIEW) Log.v(LOGTAG, "onTrackballEvent up timeout quit");
            return true;
        }
        // TODO: alternatively we can do panning as touch does
        switchOutDrawHistory();
        if (time - mTrackballLastTime > TRACKBALL_TIMEOUT) {
            if (DebugFlags.WEB_VIEW) {
                Log.v(LOGTAG, "onTrackballEvent time="
                        + time + " last=" + mTrackballLastTime);
            }
            mTrackballFirstTime = time;
            mTrackballXMove = mTrackballYMove = 0;
        }
        mTrackballLastTime = time;
        if (DebugFlags.WEB_VIEW) {
            Log.v(LOGTAG, "onTrackballEvent ev=" + ev + " time=" + time);
        }
        mTrackballRemainsX += ev.getX();
        mTrackballRemainsY += ev.getY();
        doTrackball(time, ev.getMetaState());
        return true;
    }

    private int scaleTrackballX(float xRate, int width) {
        int xMove = (int) (xRate / TRACKBALL_SCALE * width);
        int nextXMove = xMove;
        if (xMove > 0) {
            if (xMove > mTrackballXMove) {
                xMove -= mTrackballXMove;
            }
        } else if (xMove < mTrackballXMove) {
            xMove -= mTrackballXMove;
        }
        mTrackballXMove = nextXMove;
        return xMove;
    }

    private int scaleTrackballY(float yRate, int height) {
        int yMove = (int) (yRate / TRACKBALL_SCALE * height);
        int nextYMove = yMove;
        if (yMove > 0) {
            if (yMove > mTrackballYMove) {
                yMove -= mTrackballYMove;
            }
        } else if (yMove < mTrackballYMove) {
            yMove -= mTrackballYMove;
        }
        mTrackballYMove = nextYMove;
        return yMove;
    }

    private int keyCodeToSoundsEffect(int keyCode) {
        switch(keyCode) {
            case KeyEvent.KEYCODE_DPAD_UP:
                return SoundEffectConstants.NAVIGATION_UP;
            case KeyEvent.KEYCODE_DPAD_RIGHT:
                return SoundEffectConstants.NAVIGATION_RIGHT;
            case KeyEvent.KEYCODE_DPAD_DOWN:
                return SoundEffectConstants.NAVIGATION_DOWN;
            case KeyEvent.KEYCODE_DPAD_LEFT:
                return SoundEffectConstants.NAVIGATION_LEFT;
        }
        return 0;
    }

    private void doTrackball(long time, int metaState) {
        int elapsed = (int) (mTrackballLastTime - mTrackballFirstTime);
        if (elapsed == 0) {
            elapsed = TRACKBALL_TIMEOUT;
        }
        float xRate = mTrackballRemainsX * 1000 / elapsed;
        float yRate = mTrackballRemainsY * 1000 / elapsed;
        int viewWidth = getViewWidth();
        int viewHeight = getViewHeight();
        float ax = Math.abs(xRate);
        float ay = Math.abs(yRate);
        float maxA = Math.max(ax, ay);
        if (DebugFlags.WEB_VIEW) {
            Log.v(LOGTAG, "doTrackball elapsed=" + elapsed
                    + " xRate=" + xRate
                    + " yRate=" + yRate
                    + " mTrackballRemainsX=" + mTrackballRemainsX
                    + " mTrackballRemainsY=" + mTrackballRemainsY);
        }
        int width = mContentWidth - viewWidth;
        int height = mContentHeight - viewHeight;
        if (width < 0) width = 0;
        if (height < 0) height = 0;
        ax = Math.abs(mTrackballRemainsX * TRACKBALL_MULTIPLIER);
        ay = Math.abs(mTrackballRemainsY * TRACKBALL_MULTIPLIER);
        maxA = Math.max(ax, ay);
        int count = Math.max(0, (int) maxA);
        int oldScrollX = getScrollX();
        int oldScrollY = getScrollY();
        if (count > 0) {
            int selectKeyCode = ax < ay ? mTrackballRemainsY < 0 ?
                    KeyEvent.KEYCODE_DPAD_UP : KeyEvent.KEYCODE_DPAD_DOWN :
                    mTrackballRemainsX < 0 ? KeyEvent.KEYCODE_DPAD_LEFT :
                    KeyEvent.KEYCODE_DPAD_RIGHT;
            count = Math.min(count, TRACKBALL_MOVE_COUNT);
            if (DebugFlags.WEB_VIEW) {
                Log.v(LOGTAG, "doTrackball keyCode=" + selectKeyCode
                        + " count=" + count
                        + " mTrackballRemainsX=" + mTrackballRemainsX
                        + " mTrackballRemainsY=" + mTrackballRemainsY);
            }
            if (mNativeClass != 0) {
                for (int i = 0; i < count; i++) {
                    letPageHandleNavKey(selectKeyCode, time, true, metaState);
                }
                letPageHandleNavKey(selectKeyCode, time, false, metaState);
            }
            mTrackballRemainsX = mTrackballRemainsY = 0;
        }
        if (count >= TRACKBALL_SCROLL_COUNT) {
            int xMove = scaleTrackballX(xRate, width);
            int yMove = scaleTrackballY(yRate, height);
            if (DebugFlags.WEB_VIEW) {
                Log.v(LOGTAG, "doTrackball pinScrollBy"
                        + " count=" + count
                        + " xMove=" + xMove + " yMove=" + yMove
                        + " mScrollX-oldScrollX=" + (getScrollX()-oldScrollX)
                        + " mScrollY-oldScrollY=" + (getScrollY()-oldScrollY)
                        );
            }
            if (Math.abs(getScrollX() - oldScrollX) > Math.abs(xMove)) {
                xMove = 0;
            }
            if (Math.abs(getScrollY() - oldScrollY) > Math.abs(yMove)) {
                yMove = 0;
            }
            if (xMove != 0 || yMove != 0) {
                pinScrollBy(xMove, yMove, true, 0);
            }
        }
    }

    /**
     * Compute the maximum horizontal scroll position. Used by {@link OverScrollGlow}.
     * @return Maximum horizontal scroll position within real content
     */
    int computeMaxScrollX() {
        return Math.max(computeRealHorizontalScrollRange() - getViewWidth(), 0);
    }

    /**
     * Compute the maximum vertical scroll position. Used by {@link OverScrollGlow}.
     * @return Maximum vertical scroll position within real content
     */
    int computeMaxScrollY() {
        return Math.max(computeRealVerticalScrollRange() + getTitleHeight()
                - getViewHeightWithTitle(), 0);
    }

    boolean updateScrollCoordinates(int x, int y) {
        int oldX = getScrollX();
        int oldY = getScrollY();
        setScrollXRaw(x);
        setScrollYRaw(y);
        if (oldX != getScrollX() || oldY != getScrollY()) {
            mWebViewPrivate.onScrollChanged(getScrollX(), getScrollY(), oldX, oldY);
            return true;
        } else {
            return false;
        }
    }

    @Override
    public void flingScroll(int vx, int vy) {
        mScroller.fling(getScrollX(), getScrollY(), vx, vy, 0, computeMaxScrollX(), 0,
                computeMaxScrollY(), mOverflingDistance, mOverflingDistance);
        invalidate();
    }

    private void doFling() {
        if (mVelocityTracker == null) {
            return;
        }
        int maxX = computeMaxScrollX();
        int maxY = computeMaxScrollY();

        mVelocityTracker.computeCurrentVelocity(1000, mMaximumFling);
        int vx = (int) mVelocityTracker.getXVelocity();
        int vy = (int) mVelocityTracker.getYVelocity();

        int scrollX = getScrollX();
        int scrollY = getScrollY();
        int overscrollDistance = mOverscrollDistance;
        int overflingDistance = mOverflingDistance;

        // Use the layer's scroll data if applicable.
        if (mTouchMode == TOUCH_DRAG_LAYER_MODE) {
            scrollX = mScrollingLayerRect.left;
            scrollY = mScrollingLayerRect.top;
            maxX = mScrollingLayerRect.right;
            maxY = mScrollingLayerRect.bottom;
            // No overscrolling for layers.
            overscrollDistance = overflingDistance = 0;
        } else if (mTouchMode == TOUCH_DRAG_TEXT_MODE) {
            scrollX = getTextScrollX();
            scrollY = getTextScrollY();
            maxX = getMaxTextScrollX();
            maxY = getMaxTextScrollY();
            // No overscrolling for edit text.
            overscrollDistance = overflingDistance = 0;
        }

        if (mSnapScrollMode != SNAP_NONE) {
            if ((mSnapScrollMode & SNAP_X) == SNAP_X) {
                vy = 0;
            } else {
                vx = 0;
            }
        }
        if ((maxX == 0 && vy == 0) || (maxY == 0 && vx == 0)) {
            WebViewCore.resumePriority();
            if (!mSelectingText) {
                WebViewCore.resumeUpdatePicture(mWebViewCore);
            }
            if (mScroller.springBack(scrollX, scrollY, 0, maxX, 0, maxY)) {
                invalidate();
            }
            return;
        }
        float currentVelocity = mScroller.getCurrVelocity();
        float velocity = (float) Math.hypot(vx, vy);
        if (mLastVelocity > 0 && currentVelocity > 0 && velocity
                > mLastVelocity * MINIMUM_VELOCITY_RATIO_FOR_ACCELERATION) {
            float deltaR = (float) (Math.abs(Math.atan2(mLastVelY, mLastVelX)
                    - Math.atan2(vy, vx)));
            final float circle = (float) (Math.PI) * 2.0f;
            if (deltaR > circle * 0.9f || deltaR < circle * 0.1f) {
                vx += currentVelocity * mLastVelX / mLastVelocity;
                vy += currentVelocity * mLastVelY / mLastVelocity;
                velocity = (float) Math.hypot(vx, vy);
                if (DebugFlags.WEB_VIEW) {
                    Log.v(LOGTAG, "doFling vx= " + vx + " vy=" + vy);
                }
            } else if (DebugFlags.WEB_VIEW) {
                Log.v(LOGTAG, "doFling missed " + deltaR / circle);
            }
        } else if (DebugFlags.WEB_VIEW) {
            Log.v(LOGTAG, "doFling start last=" + mLastVelocity
                    + " current=" + currentVelocity
                    + " vx=" + vx + " vy=" + vy
                    + " maxX=" + maxX + " maxY=" + maxY
                    + " scrollX=" + scrollX + " scrollY=" + scrollY
                    + " layer=" + mCurrentScrollingLayerId);
        }

        // Allow sloppy flings without overscrolling at the edges.
        if ((scrollX == 0 || scrollX == maxX) && Math.abs(vx) < Math.abs(vy)) {
            vx = 0;
        }
        if ((scrollY == 0 || scrollY == maxY) && Math.abs(vy) < Math.abs(vx)) {
            vy = 0;
        }

        if (overscrollDistance < overflingDistance) {
            if ((vx > 0 && scrollX == -overscrollDistance) ||
                    (vx < 0 && scrollX == maxX + overscrollDistance)) {
                vx = 0;
            }
            if ((vy > 0 && scrollY == -overscrollDistance) ||
                    (vy < 0 && scrollY == maxY + overscrollDistance)) {
                vy = 0;
            }
        }

        mLastVelX = vx;
        mLastVelY = vy;
        mLastVelocity = velocity;

        // no horizontal overscroll if the content just fits
        mScroller.fling(scrollX, scrollY, -vx, -vy, 0, maxX, 0, maxY,
                maxX == 0 ? 0 : overflingDistance, overflingDistance);

        invalidate();
    }

    /**
     * See {@link WebView#getZoomControls()}
     */
    @Override
    @Deprecated
    public View getZoomControls() {
        if (!getSettings().supportZoom()) {
            Log.w(LOGTAG, "This WebView doesn't support zoom.");
            return null;
        }
        return mZoomManager.getExternalZoomPicker();
    }

    void dismissZoomControl() {
        mZoomManager.dismissZoomPicker();
    }

    float getDefaultZoomScale() {
        return mZoomManager.getDefaultScale();
    }

    /**
     * Return the overview scale of the WebView
     * @return The overview scale.
     */
    float getZoomOverviewScale() {
        return mZoomManager.getZoomOverviewScale();
    }

    /**
     * See {@link WebView#canZoomIn()}
     */
    @Override
    public boolean canZoomIn() {
        return mZoomManager.canZoomIn();
    }

    /**
     * See {@link WebView#canZoomOut()}
     */
    @Override
    public boolean canZoomOut() {
        return mZoomManager.canZoomOut();
    }

    /**
     * See {@link WebView#zoomIn()}
     */
    @Override
    public boolean zoomIn() {
        return mZoomManager.zoomIn();
    }

    /**
     * See {@link WebView#zoomOut()}
     */
    @Override
    public boolean zoomOut() {
        return mZoomManager.zoomOut();
    }

    /*
     * Return true if the rect (e.g. plugin) is fully visible and maximized
     * inside the WebView.
     */
    boolean isRectFitOnScreen(Rect rect) {
        final int rectWidth = rect.width();
        final int rectHeight = rect.height();
        final int viewWidth = getViewWidth();
        final int viewHeight = getViewHeightWithTitle();
        float scale = Math.min((float) viewWidth / rectWidth, (float) viewHeight / rectHeight);
        scale = mZoomManager.computeScaleWithLimits(scale);
        return !mZoomManager.willScaleTriggerZoom(scale)
                && contentToViewX(rect.left) >= getScrollX()
                && contentToViewX(rect.right) <= getScrollX() + viewWidth
                && contentToViewY(rect.top) >= getScrollY()
                && contentToViewY(rect.bottom) <= getScrollY() + viewHeight;
    }

    /*
     * Maximize and center the rectangle, specified in the document coordinate
     * space, inside the WebView. If the zoom doesn't need to be changed, do an
     * animated scroll to center it. If the zoom needs to be changed, find the
     * zoom center and do a smooth zoom transition. The rect is in document
     * coordinates
     */
    void centerFitRect(Rect rect) {
        final int rectWidth = rect.width();
        final int rectHeight = rect.height();
        final int viewWidth = getViewWidth();
        final int viewHeight = getViewHeightWithTitle();
        float scale = Math.min((float) viewWidth / rectWidth, (float) viewHeight
                / rectHeight);
        scale = mZoomManager.computeScaleWithLimits(scale);
        if (!mZoomManager.willScaleTriggerZoom(scale)) {
            pinScrollTo(contentToViewX(rect.left + rectWidth / 2) - viewWidth / 2,
                    contentToViewY(rect.top + rectHeight / 2) - viewHeight / 2,
                    true, 0);
        } else {
            float actualScale = mZoomManager.getScale();
            float oldScreenX = rect.left * actualScale - getScrollX();
            float rectViewX = rect.left * scale;
            float rectViewWidth = rectWidth * scale;
            float newMaxWidth = mContentWidth * scale;
            float newScreenX = (viewWidth - rectViewWidth) / 2;
            // pin the newX to the WebView
            if (newScreenX > rectViewX) {
                newScreenX = rectViewX;
            } else if (newScreenX > (newMaxWidth - rectViewX - rectViewWidth)) {
                newScreenX = viewWidth - (newMaxWidth - rectViewX);
            }
            float zoomCenterX = (oldScreenX * scale - newScreenX * actualScale)
                    / (scale - actualScale);
            float oldScreenY = rect.top * actualScale + getTitleHeight()
                    - getScrollY();
            float rectViewY = rect.top * scale + getTitleHeight();
            float rectViewHeight = rectHeight * scale;
            float newMaxHeight = mContentHeight * scale + getTitleHeight();
            float newScreenY = (viewHeight - rectViewHeight) / 2;
            // pin the newY to the WebView
            if (newScreenY > rectViewY) {
                newScreenY = rectViewY;
            } else if (newScreenY > (newMaxHeight - rectViewY - rectViewHeight)) {
                newScreenY = viewHeight - (newMaxHeight - rectViewY);
            }
            float zoomCenterY = (oldScreenY * scale - newScreenY * actualScale)
                    / (scale - actualScale);
            mZoomManager.setZoomCenter(zoomCenterX, zoomCenterY);
            mZoomManager.startZoomAnimation(scale, false);
        }
    }

    // Called by JNI to handle a touch on a node representing an email address,
    // address, or phone number
    private void overrideLoading(String url) {
        mCallbackProxy.uiOverrideUrlLoading(url);
    }

    @Override
    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
        // Check if we are destroyed
        if (mWebViewCore == null) return false;
        // FIXME: If a subwindow is showing find, and the user touches the
        // background window, it can steal focus.
        if (mFindIsUp) return false;
        boolean result = false;
        result = mWebViewPrivate.super_requestFocus(direction, previouslyFocusedRect);
        if (mWebViewCore.getSettings().getNeedInitialFocus()
                && !mWebView.isInTouchMode()) {
            // For cases such as GMail, where we gain focus from a direction,
            // we want to move to the first available link.
            // FIXME: If there are no visible links, we may not want to
            int fakeKeyDirection = 0;
            switch(direction) {
                case View.FOCUS_UP:
                    fakeKeyDirection = KeyEvent.KEYCODE_DPAD_UP;
                    break;
                case View.FOCUS_DOWN:
                    fakeKeyDirection = KeyEvent.KEYCODE_DPAD_DOWN;
                    break;
                case View.FOCUS_LEFT:
                    fakeKeyDirection = KeyEvent.KEYCODE_DPAD_LEFT;
                    break;
                case View.FOCUS_RIGHT:
                    fakeKeyDirection = KeyEvent.KEYCODE_DPAD_RIGHT;
                    break;
                default:
                    return result;
            }
            mWebViewCore.sendMessage(EventHub.SET_INITIAL_FOCUS, fakeKeyDirection);
        }
        return result;
    }

    @Override
    public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);

        int measuredHeight = heightSize;
        int measuredWidth = widthSize;

        // Grab the content size from WebViewCore.
        int contentHeight = contentToViewDimension(mContentHeight);
        int contentWidth = contentToViewDimension(mContentWidth);

//        Log.d(LOGTAG, "------- measure " + heightMode);

        if (heightMode != MeasureSpec.EXACTLY) {
            mHeightCanMeasure = true;
            measuredHeight = contentHeight;
            if (heightMode == MeasureSpec.AT_MOST) {
                // If we are larger than the AT_MOST height, then our height can
                // no longer be measured and we should scroll internally.
                if (measuredHeight > heightSize) {
                    measuredHeight = heightSize;
                    mHeightCanMeasure = false;
                    measuredHeight |= View.MEASURED_STATE_TOO_SMALL;
                }
            }
        } else {
            mHeightCanMeasure = false;
        }
        if (mNativeClass != 0) {
            nativeSetHeightCanMeasure(mHeightCanMeasure);
        }
        // For the width, always use the given size unless unspecified.
        if (widthMode == MeasureSpec.UNSPECIFIED) {
            mWidthCanMeasure = true;
            measuredWidth = contentWidth;
        } else {
            if (measuredWidth < contentWidth) {
                measuredWidth |= View.MEASURED_STATE_TOO_SMALL;
            }
            mWidthCanMeasure = false;
        }

        synchronized (this) {
            mWebViewPrivate.setMeasuredDimension(measuredWidth, measuredHeight);
        }
    }

    @Override
    public boolean requestChildRectangleOnScreen(View child,
                                                 Rect rect,
                                                 boolean immediate) {
        if (mNativeClass == 0) {
            return false;
        }
        // don't scroll while in zoom animation. When it is done, we will adjust
        // the necessary components
        if (mZoomManager.isFixedLengthAnimationInProgress()) {
            return false;
        }

        rect.offset(child.getLeft() - child.getScrollX(),
                child.getTop() - child.getScrollY());

        Rect content = new Rect(viewToContentX(getScrollX()),
                viewToContentY(getScrollY()),
                viewToContentX(getScrollX() + getWidth()
                - mWebView.getVerticalScrollbarWidth()),
                viewToContentY(getScrollY() + getViewHeightWithTitle()));
        int screenTop = contentToViewY(content.top);
        int screenBottom = contentToViewY(content.bottom);
        int height = screenBottom - screenTop;
        int scrollYDelta = 0;

        if (rect.bottom > screenBottom) {
            int oneThirdOfScreenHeight = height / 3;
            if (rect.height() > 2 * oneThirdOfScreenHeight) {
                // If the rectangle is too tall to fit in the bottom two thirds
                // of the screen, place it at the top.
                scrollYDelta = rect.top - screenTop;
            } else {
                // If the rectangle will still fit on screen, we want its
                // top to be in the top third of the screen.
                scrollYDelta = rect.top - (screenTop + oneThirdOfScreenHeight);
            }
        } else if (rect.top < screenTop) {
            scrollYDelta = rect.top - screenTop;
        }

        int screenLeft = contentToViewX(content.left);
        int screenRight = contentToViewX(content.right);
        int width = screenRight - screenLeft;
        int scrollXDelta = 0;

        if (rect.right > screenRight && rect.left > screenLeft) {
            if (rect.width() > width) {
                scrollXDelta += (rect.left - screenLeft);
            } else {
                scrollXDelta += (rect.right - screenRight);
            }
        } else if (rect.left < screenLeft) {
            scrollXDelta -= (screenLeft - rect.left);
        }

        if ((scrollYDelta | scrollXDelta) != 0) {
            return pinScrollBy(scrollXDelta, scrollYDelta, !immediate, 0);
        }

        return false;
    }

    /* package */ void replaceTextfieldText(int oldStart, int oldEnd,
            String replace, int newStart, int newEnd) {
        WebViewCore.ReplaceTextData arg = new WebViewCore.ReplaceTextData();
        arg.mReplace = replace;
        arg.mNewStart = newStart;
        arg.mNewEnd = newEnd;
        mTextGeneration++;
        arg.mTextGeneration = mTextGeneration;
        sendBatchableInputMessage(EventHub.REPLACE_TEXT, oldStart, oldEnd, arg);
    }

    /* package */ void passToJavaScript(String currentText, KeyEvent event) {
        // check if mWebViewCore has been destroyed
        if (mWebViewCore == null) {
            return;
        }
        WebViewCore.JSKeyData arg = new WebViewCore.JSKeyData();
        arg.mEvent = event;
        arg.mCurrentText = currentText;
        // Increase our text generation number, and pass it to webcore thread
        mTextGeneration++;
        mWebViewCore.sendMessage(EventHub.PASS_TO_JS, mTextGeneration, 0, arg);
        // WebKit's document state is not saved until about to leave the page.
        // To make sure the host application, like Browser, has the up to date
        // document state when it goes to background, we force to save the
        // document state.
        mWebViewCore.removeMessages(EventHub.SAVE_DOCUMENT_STATE);
        mWebViewCore.sendMessageDelayed(EventHub.SAVE_DOCUMENT_STATE, null, 1000);
    }

    public synchronized WebViewCore getWebViewCore() {
        return mWebViewCore;
    }

    private boolean canTextScroll(int directionX, int directionY) {
        int scrollX = getTextScrollX();
        int scrollY = getTextScrollY();
        int maxScrollX = getMaxTextScrollX();
        int maxScrollY = getMaxTextScrollY();
        boolean canScrollX = (directionX > 0)
                ? (scrollX < maxScrollX)
                : (scrollX > 0);
        boolean canScrollY = (directionY > 0)
                ? (scrollY < maxScrollY)
                : (scrollY > 0);
        return canScrollX || canScrollY;
    }

    private int getTextScrollX() {
        return -mEditTextContent.left;
    }

    private int getTextScrollY() {
        return -mEditTextContent.top;
    }

    private int getMaxTextScrollX() {
        return Math.max(0, mEditTextContent.width() - mEditTextContentBounds.width());
    }

    private int getMaxTextScrollY() {
        return Math.max(0, mEditTextContent.height() - mEditTextContentBounds.height());
    }

    //-------------------------------------------------------------------------
    // Methods can be called from a separate thread, like WebViewCore
    // If it needs to call the View system, it has to send message.
    //-------------------------------------------------------------------------

    /**
     * General handler to receive message coming from webkit thread
     */
    class PrivateHandler extends Handler implements WebViewInputDispatcher.UiCallbacks {
        @Override
        public void handleMessage(Message msg) {
            // exclude INVAL_RECT_MSG_ID since it is frequently output
            if (DebugFlags.WEB_VIEW && msg.what != INVAL_RECT_MSG_ID) {
                if (msg.what >= FIRST_PRIVATE_MSG_ID
                        && msg.what <= LAST_PRIVATE_MSG_ID) {
                    Log.v(LOGTAG, HandlerPrivateDebugString[msg.what
                            - FIRST_PRIVATE_MSG_ID]);
                } else if (msg.what >= FIRST_PACKAGE_MSG_ID
                        && msg.what <= LAST_PACKAGE_MSG_ID) {
                    Log.v(LOGTAG, HandlerPackageDebugString[msg.what
                            - FIRST_PACKAGE_MSG_ID]);
                } else {
                    Log.v(LOGTAG, Integer.toString(msg.what));
                }
            }
            if (mWebViewCore == null) {
                // after WebView's destroy() is called, skip handling messages.
                return;
            }
            if (mBlockWebkitViewMessages
                    && msg.what != WEBCORE_INITIALIZED_MSG_ID) {
                // Blocking messages from webkit
                return;
            }
            switch (msg.what) {
                case REMEMBER_PASSWORD: {
                    mDatabase.setUsernamePassword(
                            msg.getData().getString("host"),
                            msg.getData().getString("username"),
                            msg.getData().getString("password"));
                    ((Message) msg.obj).sendToTarget();
                    break;
                }
                case NEVER_REMEMBER_PASSWORD: {
                    mDatabase.setUsernamePassword(msg.getData().getString("host"), null, null);
                    ((Message) msg.obj).sendToTarget();
                    break;
                }
                case SCROLL_SELECT_TEXT: {
                    if (mAutoScrollX == 0 && mAutoScrollY == 0) {
                        mSentAutoScrollMessage = false;
                        break;
                    }
                    if (mCurrentScrollingLayerId == 0) {
                        pinScrollBy(mAutoScrollX, mAutoScrollY, true, 0);
                    } else {
                        scrollLayerTo(mScrollingLayerRect.left + mAutoScrollX,
                                mScrollingLayerRect.top + mAutoScrollY);
                    }
                    sendEmptyMessageDelayed(
                            SCROLL_SELECT_TEXT, SELECT_SCROLL_INTERVAL);
                    break;
                }
                case SCROLL_TO_MSG_ID: {
                    // arg1 = animate, arg2 = onlyIfImeIsShowing
                    // obj = Point(x, y)
                    if (msg.arg2 == 1) {
                        // This scroll is intended to bring the textfield into
                        // view, but is only necessary if the IME is showing
                        InputMethodManager imm = InputMethodManager.peekInstance();
                        if (imm == null || !imm.isAcceptingText()
                                || !imm.isActive(mWebView)) {
                            break;
                        }
                    }
                    final Point p = (Point) msg.obj;
                    contentScrollTo(p.x, p.y, msg.arg1 == 1);
                    break;
                }
                case UPDATE_ZOOM_RANGE: {
                    WebViewCore.ViewState viewState = (WebViewCore.ViewState) msg.obj;
                    // mScrollX contains the new minPrefWidth
                    mZoomManager.updateZoomRange(viewState, getViewWidth(), viewState.mScrollX);
                    break;
                }
                case UPDATE_ZOOM_DENSITY: {
                    final float density = (Float) msg.obj;
                    mZoomManager.updateDefaultZoomDensity(density);
                    break;
                }
                case NEW_PICTURE_MSG_ID: {
                    // called for new content
                    final WebViewCore.DrawData draw = (WebViewCore.DrawData) msg.obj;
                    setNewPicture(draw, true);
                    break;
                }
                case WEBCORE_INITIALIZED_MSG_ID:
                    // nativeCreate sets mNativeClass to a non-zero value
                    String drawableDir = BrowserFrame.getRawResFilename(
                            BrowserFrame.DRAWABLEDIR, mContext);
                    nativeCreate(msg.arg1, drawableDir, ActivityManager.isHighEndGfx());
                    if (mDelaySetPicture != null) {
                        setNewPicture(mDelaySetPicture, true);
                        mDelaySetPicture = null;
                    }
                    if (mIsPaused) {
                        nativeSetPauseDrawing(mNativeClass, true);
                    }
                    mInputDispatcher = new WebViewInputDispatcher(this,
                            mWebViewCore.getInputDispatcherCallbacks());
                    break;
                case UPDATE_TEXTFIELD_TEXT_MSG_ID:
                    // Make sure that the textfield is currently focused
                    // and representing the same node as the pointer.
                    if (msg.arg2 == mTextGeneration) {
                        String text = (String) msg.obj;
                        if (null == text) {
                            text = "";
                        }
                        if (mInputConnection != null &&
                                mFieldPointer == msg.arg1) {
                            mInputConnection.setTextAndKeepSelection(text);
                        }
                    }
                    break;
                case UPDATE_TEXT_SELECTION_MSG_ID:
                    updateTextSelectionFromMessage(msg.arg1, msg.arg2,
                            (WebViewCore.TextSelectionData) msg.obj);
                    break;
                case TAKE_FOCUS:
                    int direction = msg.arg1;
                    View focusSearch = mWebView.focusSearch(direction);
                    if (focusSearch != null && focusSearch != mWebView) {
                        focusSearch.requestFocus();
                    }
                    break;
                case CLEAR_TEXT_ENTRY:
                    hideSoftKeyboard();
                    break;
                case INVAL_RECT_MSG_ID: {
                    Rect r = (Rect)msg.obj;
                    if (r == null) {
                        invalidate();
                    } else {
                        // we need to scale r from content into view coords,
                        // which viewInvalidate() does for us
                        viewInvalidate(r.left, r.top, r.right, r.bottom);
                    }
                    break;
                }
                case REQUEST_FORM_DATA:
                    if (mFieldPointer == msg.arg1) {
                        ArrayAdapter<String> adapter = (ArrayAdapter<String>)msg.obj;
                        mAutoCompletePopup.setAdapter(adapter);
                    }
                    break;

                case LONG_PRESS_CENTER:
                    // as this is shared by keydown and trackballdown, reset all
                    // the states
                    mGotCenterDown = false;
                    mTrackballDown = false;
                    mWebView.performLongClick();
                    break;

                case WEBCORE_NEED_TOUCH_EVENTS:
                    mInputDispatcher.setWebKitWantsTouchEvents(msg.arg1 != 0);
                    break;

                case REQUEST_KEYBOARD:
                    if (msg.arg1 == 0) {
                        hideSoftKeyboard();
                    } else {
                        displaySoftKeyboard(false);
                    }
                    break;

                case DRAG_HELD_MOTIONLESS:
                    mHeldMotionless = MOTIONLESS_TRUE;
                    invalidate();
                    break;

                case SCREEN_ON:
                    mWebView.setKeepScreenOn(msg.arg1 == 1);
                    break;

                case EXIT_FULLSCREEN_VIDEO:
                    if (mHTML5VideoViewProxy != null) {
                        mHTML5VideoViewProxy.exitFullScreenVideo();
                    }
                    break;

                case SHOW_FULLSCREEN: {
                    View view = (View) msg.obj;
                    int orientation = msg.arg1;
                    int npp = msg.arg2;

                    if (inFullScreenMode()) {
                        Log.w(LOGTAG, "Should not have another full screen.");
                        dismissFullScreenMode();
                    }
                    mFullScreenHolder = new PluginFullScreenHolder(WebViewClassic.this, orientation, npp);
                    mFullScreenHolder.setContentView(view);
                    mFullScreenHolder.show();
                    invalidate();

                    break;
                }
                case HIDE_FULLSCREEN:
                    dismissFullScreenMode();
                    break;

                case SHOW_RECT_MSG_ID: {
                    WebViewCore.ShowRectData data = (WebViewCore.ShowRectData) msg.obj;
                    int left = contentToViewX(data.mLeft);
                    int width = contentToViewDimension(data.mWidth);
                    int maxWidth = contentToViewDimension(data.mContentWidth);
                    int viewWidth = getViewWidth();
                    int x = (int) (left + data.mXPercentInDoc * width -
                                   data.mXPercentInView * viewWidth);
                    if (DebugFlags.WEB_VIEW) {
                        Log.v(LOGTAG, "showRectMsg=(left=" + left + ",width=" +
                              width + ",maxWidth=" + maxWidth +
                              ",viewWidth=" + viewWidth + ",x="
                              + x + ",xPercentInDoc=" + data.mXPercentInDoc +
                              ",xPercentInView=" + data.mXPercentInView+ ")");
                    }
                    // use the passing content width to cap x as the current
                    // mContentWidth may not be updated yet
                    x = Math.max(0,
                            (Math.min(maxWidth, x + viewWidth)) - viewWidth);
                    int top = contentToViewY(data.mTop);
                    int height = contentToViewDimension(data.mHeight);
                    int maxHeight = contentToViewDimension(data.mContentHeight);
                    int viewHeight = getViewHeight();
                    int y = (int) (top + data.mYPercentInDoc * height -
                                   data.mYPercentInView * viewHeight);
                    if (DebugFlags.WEB_VIEW) {
                        Log.v(LOGTAG, "showRectMsg=(top=" + top + ",height=" +
                              height + ",maxHeight=" + maxHeight +
                              ",viewHeight=" + viewHeight + ",y="
                              + y + ",yPercentInDoc=" + data.mYPercentInDoc +
                              ",yPercentInView=" + data.mYPercentInView+ ")");
                    }
                    // use the passing content height to cap y as the current
                    // mContentHeight may not be updated yet
                    y = Math.max(0,
                            (Math.min(maxHeight, y + viewHeight) - viewHeight));
                    // We need to take into account the visible title height
                    // when scrolling since y is an absolute view position.
                    y = Math.max(0, y - getVisibleTitleHeightImpl());
                    mWebView.scrollTo(x, y);
                    }
                    break;

                case CENTER_FIT_RECT:
                    centerFitRect((Rect)msg.obj);
                    break;

                case SET_SCROLLBAR_MODES:
                    mHorizontalScrollBarMode = msg.arg1;
                    mVerticalScrollBarMode = msg.arg2;
                    break;

                case SELECTION_STRING_CHANGED:
                    if (isAccessibilityInjectionEnabled()) {
                        getAccessibilityInjector()
                                .handleSelectionChangedIfNecessary((String) msg.obj);
                    }
                    break;

                case FOCUS_NODE_CHANGED:
                    mIsEditingText = (msg.arg1 == mFieldPointer);
                    if (mAutoCompletePopup != null && !mIsEditingText) {
                        mAutoCompletePopup.clearAdapter();
                    }
                    // fall through to HIT_TEST_RESULT
                case HIT_TEST_RESULT:
                    WebKitHitTest hit = (WebKitHitTest) msg.obj;
                    mFocusedNode = hit;
                    setTouchHighlightRects(hit);
                    setHitTestResult(hit);
                    break;

                case SAVE_WEBARCHIVE_FINISHED:
                    SaveWebArchiveMessage saveMessage = (SaveWebArchiveMessage)msg.obj;
                    if (saveMessage.mCallback != null) {
                        saveMessage.mCallback.onReceiveValue(saveMessage.mResultFile);
                    }
                    break;

                case SET_AUTOFILLABLE:
                    mAutoFillData = (WebViewCore.AutoFillData) msg.obj;
                    if (mInputConnection != null) {
                        mInputConnection.setAutoFillable(mAutoFillData.getQueryId());
                        mAutoCompletePopup.setAutoFillQueryId(mAutoFillData.getQueryId());
                    }
                    break;

                case AUTOFILL_COMPLETE:
                    if (mAutoCompletePopup != null) {
                        ArrayList<String> pastEntries = new ArrayList<String>();
                        mAutoCompletePopup.setAdapter(new ArrayAdapter<String>(
                                mContext,
                                com.android.internal.R.layout.web_text_view_dropdown,
                                pastEntries));
                    }
                    break;

                case COPY_TO_CLIPBOARD:
                    copyToClipboard((String) msg.obj);
                    break;

                case INIT_EDIT_FIELD:
                    if (mInputConnection != null) {
                        TextFieldInitData initData = (TextFieldInitData) msg.obj;
                        mTextGeneration = 0;
                        mFieldPointer = initData.mFieldPointer;
                        mInputConnection.initEditorInfo(initData);
                        mInputConnection.setTextAndKeepSelection(initData.mText);
                        mEditTextContentBounds.set(initData.mContentBounds);
                        mEditTextLayerId = initData.mNodeLayerId;
                        nativeMapLayerRect(mNativeClass, mEditTextLayerId,
                                mEditTextContentBounds);
                        mEditTextContent.set(initData.mClientRect);
                        relocateAutoCompletePopup();
                    }
                    break;

                case REPLACE_TEXT:{
                    String text = (String)msg.obj;
                    int start = msg.arg1;
                    int end = msg.arg2;
                    int cursorPosition = start + text.length();
                    replaceTextfieldText(start, end, text,
                            cursorPosition, cursorPosition);
                    selectionDone();
                    break;
                }

                case UPDATE_MATCH_COUNT: {
                    WebViewCore.FindAllRequest request = (WebViewCore.FindAllRequest)msg.obj;
                    if (request == null) {
                        if (mFindCallback != null) {
                            mFindCallback.updateMatchCount(0, 0, true);
                        }
                    } else if (request == mFindRequest) {
                        int matchCount, matchIndex;
                        synchronized (mFindRequest) {
                            matchCount = request.mMatchCount;
                            matchIndex = request.mMatchIndex;
                        }
                        if (mFindCallback != null) {
                            mFindCallback.updateMatchCount(matchIndex, matchCount, false);
                        }
                        if (mFindListener != null) {
                            mFindListener.onFindResultReceived(matchIndex, matchCount, true);
                        }
                    }
                    break;
                }

                case CLEAR_CARET_HANDLE:
                    if (mIsCaretSelection) {
                        selectionDone();
                    }
                    break;

                case KEY_PRESS:
                    sendBatchableInputMessage(EventHub.KEY_PRESS, msg.arg1, 0, null);
                    break;

                case RELOCATE_AUTO_COMPLETE_POPUP:
                    relocateAutoCompletePopup();
                    break;

                case AUTOFILL_FORM:
                    mWebViewCore.sendMessage(EventHub.AUTOFILL_FORM,
                            msg.arg1, /* unused */0);
                    break;

                case EDIT_TEXT_SIZE_CHANGED:
                    if (msg.arg1 == mFieldPointer) {
                        mEditTextContent.set((Rect)msg.obj);
                    }
                    break;

                case SHOW_CARET_HANDLE:
                    if (!mSelectingText && mIsEditingText && mIsCaretSelection) {
                        setupWebkitSelect();
                        resetCaretTimer();
                        showPasteWindow();
                    }
                    break;

                case UPDATE_CONTENT_BOUNDS:
                    mEditTextContentBounds.set((Rect) msg.obj);
                    nativeMapLayerRect(mNativeClass, mEditTextLayerId,
                            mEditTextContentBounds);
                    break;

                case SCROLL_EDIT_TEXT:
                    scrollEditWithCursor();
                    break;

                case SCROLL_HANDLE_INTO_VIEW:
                    scrollDraggedSelectionHandleIntoView();
                    break;

                default:
                    super.handleMessage(msg);
                    break;
            }
        }

        @Override
        public Looper getUiLooper() {
            return getLooper();
        }

        @Override
        public void dispatchUiEvent(MotionEvent event, int eventType, int flags) {
            onHandleUiEvent(event, eventType, flags);
        }

        @Override
        public Context getContext() {
            return WebViewClassic.this.getContext();
        }

        @Override
        public boolean shouldInterceptTouchEvent(MotionEvent event) {
            if (!mSelectingText) {
                return false;
            }
            ensureSelectionHandles();
            int y = Math.round(event.getY() - getTitleHeight() + getScrollY());
            int x = Math.round(event.getX() + getScrollX());
            boolean isPressingHandle;
            if (mIsCaretSelection) {
                isPressingHandle = mSelectHandleCenter.getBounds()
                        .contains(x, y);
            } else {
                isPressingHandle =
                        mSelectHandleBaseBounds.contains(x, y)
                        || mSelectHandleExtentBounds.contains(x, y);
            }
            return isPressingHandle;
        }

        @Override
        public void showTapHighlight(boolean show) {
            if (mShowTapHighlight != show) {
                mShowTapHighlight = show;
                invalidate();
            }
        }

        @Override
        public void clearPreviousHitTest() {
            setHitTestResult(null);
        }
    }

    private void setHitTestTypeFromUrl(String url) {
        String substr = null;
        if (url.startsWith(SCHEME_GEO)) {
            mInitialHitTestResult.setType(HitTestResult.GEO_TYPE);
            substr = url.substring(SCHEME_GEO.length());
        } else if (url.startsWith(SCHEME_TEL)) {
            mInitialHitTestResult.setType(HitTestResult.PHONE_TYPE);
            substr = url.substring(SCHEME_TEL.length());
        } else if (url.startsWith(SCHEME_MAILTO)) {
            mInitialHitTestResult.setType(HitTestResult.EMAIL_TYPE);
            substr = url.substring(SCHEME_MAILTO.length());
        } else {
            mInitialHitTestResult.setType(HitTestResult.SRC_ANCHOR_TYPE);
            mInitialHitTestResult.setExtra(url);
            return;
        }
        try {
            mInitialHitTestResult.setExtra(URLDecoder.decode(substr, "UTF-8"));
        } catch (Throwable e) {
            Log.w(LOGTAG, "Failed to decode URL! " + substr, e);
            mInitialHitTestResult.setType(HitTestResult.UNKNOWN_TYPE);
        }
    }

    private void setHitTestResult(WebKitHitTest hit) {
        if (hit == null) {
            mInitialHitTestResult = null;
            return;
        }
        mInitialHitTestResult = new HitTestResult();
        if (hit.mLinkUrl != null) {
            setHitTestTypeFromUrl(hit.mLinkUrl);
            if (hit.mImageUrl != null
                    && mInitialHitTestResult.getType() == HitTestResult.SRC_ANCHOR_TYPE) {
                mInitialHitTestResult.setType(HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
                mInitialHitTestResult.setExtra(hit.mImageUrl);
            }
        } else if (hit.mImageUrl != null) {
            mInitialHitTestResult.setType(HitTestResult.IMAGE_TYPE);
            mInitialHitTestResult.setExtra(hit.mImageUrl);
        } else if (hit.mEditable) {
            mInitialHitTestResult.setType(HitTestResult.EDIT_TEXT_TYPE);
        } else if (hit.mIntentUrl != null) {
            setHitTestTypeFromUrl(hit.mIntentUrl);
        }
    }

    private boolean shouldDrawHighlightRect() {
        if (mFocusedNode == null || mInitialHitTestResult == null) {
            return false;
        }
        if (mTouchHighlightRegion.isEmpty()) {
            return false;
        }
        if (mFocusedNode.mHasFocus && !mWebView.isInTouchMode()) {
            return mDrawCursorRing && !mFocusedNode.mEditable;
        }
        if (mFocusedNode.mHasFocus && mFocusedNode.mEditable) {
            return false;
        }
        return mShowTapHighlight;
    }


    private FocusTransitionDrawable mFocusTransition = null;
    static class FocusTransitionDrawable extends Drawable {
        Region mPreviousRegion;
        Region mNewRegion;
        float mProgress = 0;
        WebViewClassic mWebView;
        Paint mPaint;
        int mMaxAlpha;
        Point mTranslate;

        public FocusTransitionDrawable(WebViewClassic view) {
            mWebView = view;
            mPaint = new Paint(mWebView.mTouchHightlightPaint);
            mMaxAlpha = mPaint.getAlpha();
        }

        @Override
        public void setColorFilter(ColorFilter cf) {
        }

        @Override
        public void setAlpha(int alpha) {
        }

        @Override
        public int getOpacity() {
            return 0;
        }

        public void setProgress(float p) {
            mProgress = p;
            if (mWebView.mFocusTransition == this) {
                if (mProgress == 1f)
                    mWebView.mFocusTransition = null;
                mWebView.invalidate();
            }
        }

        public float getProgress() {
            return mProgress;
        }

        @Override
        public void draw(Canvas canvas) {
            if (mTranslate == null) {
                Rect bounds = mPreviousRegion.getBounds();
                Point from = new Point(bounds.centerX(), bounds.centerY());
                mNewRegion.getBounds(bounds);
                Point to = new Point(bounds.centerX(), bounds.centerY());
                mTranslate = new Point(from.x - to.x, from.y - to.y);
            }
            int alpha = (int) (mProgress * mMaxAlpha);
            RegionIterator iter = new RegionIterator(mPreviousRegion);
            Rect r = new Rect();
            mPaint.setAlpha(mMaxAlpha - alpha);
            float tx = mTranslate.x * mProgress;
            float ty = mTranslate.y * mProgress;
            int save = canvas.save(Canvas.MATRIX_SAVE_FLAG);
            canvas.translate(-tx, -ty);
            while (iter.next(r)) {
                canvas.drawRect(r, mPaint);
            }
            canvas.restoreToCount(save);
            iter = new RegionIterator(mNewRegion);
            r = new Rect();
            mPaint.setAlpha(alpha);
            save = canvas.save(Canvas.MATRIX_SAVE_FLAG);
            tx = mTranslate.x - tx;
            ty = mTranslate.y - ty;
            canvas.translate(tx, ty);
            while (iter.next(r)) {
                canvas.drawRect(r, mPaint);
            }
            canvas.restoreToCount(save);
        }
    };

    private boolean shouldAnimateTo(WebKitHitTest hit) {
        // TODO: Don't be annoying or throw out the animation entirely
        return false;
    }

    private void setTouchHighlightRects(WebKitHitTest hit) {
        FocusTransitionDrawable transition = null;
        if (shouldAnimateTo(hit)) {
            transition = new FocusTransitionDrawable(this);
        }
        Rect[] rects = hit != null ? hit.mTouchRects : null;
        if (!mTouchHighlightRegion.isEmpty()) {
            mWebView.invalidate(mTouchHighlightRegion.getBounds());
            if (transition != null) {
                transition.mPreviousRegion = new Region(mTouchHighlightRegion);
            }
            mTouchHighlightRegion.setEmpty();
        }
        if (rects != null) {
            mTouchHightlightPaint.setColor(hit.mTapHighlightColor);
            for (Rect rect : rects) {
                Rect viewRect = contentToViewRect(rect);
                // some sites, like stories in nytimes.com, set
                // mouse event handler in the top div. It is not
                // user friendly to highlight the div if it covers
                // more than half of the screen.
                if (viewRect.width() < getWidth() >> 1
                        || viewRect.height() < getHeight() >> 1) {
                    mTouchHighlightRegion.union(viewRect);
                } else if (DebugFlags.WEB_VIEW) {
                    Log.d(LOGTAG, "Skip the huge selection rect:"
                            + viewRect);
                }
            }
            mWebView.invalidate(mTouchHighlightRegion.getBounds());
            if (transition != null && transition.mPreviousRegion != null) {
                transition.mNewRegion = new Region(mTouchHighlightRegion);
                mFocusTransition = transition;
                ObjectAnimator animator = ObjectAnimator.ofFloat(
                        mFocusTransition, "progress", 1f);
                animator.start();
            }
        }
    }

    // Interface to allow the profiled WebView to hook the page swap notifications.
    public interface PageSwapDelegate {
        void onPageSwapOccurred(boolean notifyAnimationStarted);
    }

    long mLastSwapTime;
    double mAverageSwapFps;

    /** Called by JNI when pages are swapped (only occurs with hardware
     * acceleration) */
    protected void pageSwapCallback(boolean notifyAnimationStarted) {
        if (DebugFlags.MEASURE_PAGE_SWAP_FPS) {
            long now = System.currentTimeMillis();
            long diff = now - mLastSwapTime;
            mAverageSwapFps = ((1000.0 / diff) + mAverageSwapFps) / 2;
            Log.d(LOGTAG, "page swap fps: " + mAverageSwapFps);
            mLastSwapTime = now;
        }
        mWebViewCore.resumeWebKitDraw();
        if (notifyAnimationStarted) {
            mWebViewCore.sendMessage(EventHub.NOTIFY_ANIMATION_STARTED);
        }
        if (mWebView instanceof PageSwapDelegate) {
            // This provides a hook for ProfiledWebView to observe the tile page swaps.
            ((PageSwapDelegate) mWebView).onPageSwapOccurred(notifyAnimationStarted);
        }

        if (mPictureListener != null) {
            // trigger picture listener for hardware layers. Software layers are
            // triggered in setNewPicture
            mPictureListener.onNewPicture(getWebView(), capturePicture());
        }
    }

    void setNewPicture(final WebViewCore.DrawData draw, boolean updateBaseLayer) {
        if (mNativeClass == 0) {
            if (mDelaySetPicture != null) {
                throw new IllegalStateException("Tried to setNewPicture with"
                        + " a delay picture already set! (memory leak)");
            }
            // Not initialized yet, delay set
            mDelaySetPicture = draw;
            return;
        }
        WebViewCore.ViewState viewState = draw.mViewState;
        boolean isPictureAfterFirstLayout = viewState != null;

        if (updateBaseLayer) {
            setBaseLayer(draw.mBaseLayer,
                    getSettings().getShowVisualIndicator(),
                    isPictureAfterFirstLayout);
        }
        final Point viewSize = draw.mViewSize;
        // We update the layout (i.e. request a layout from the
        // view system) if the last view size that we sent to
        // WebCore matches the view size of the picture we just
        // received in the fixed dimension.
        final boolean updateLayout = viewSize.x == mLastWidthSent
                && viewSize.y == mLastHeightSent;
        // Don't send scroll event for picture coming from webkit,
        // since the new picture may cause a scroll event to override
        // the saved history scroll position.
        mSendScrollEvent = false;
        recordNewContentSize(draw.mContentSize.x,
                draw.mContentSize.y, updateLayout);
        if (isPictureAfterFirstLayout) {
            // Reset the last sent data here since dealing with new page.
            mLastWidthSent = 0;
            mZoomManager.onFirstLayout(draw);
            int scrollX = viewState.mShouldStartScrolledRight
                    ? getContentWidth() : viewState.mScrollX;
            int scrollY = viewState.mScrollY;
            contentScrollTo(scrollX, scrollY, false);
            if (!mDrawHistory) {
                // As we are on a new page, hide the keyboard
                hideSoftKeyboard();
            }
        }
        mSendScrollEvent = true;

        int functor = 0;
        boolean forceInval = isPictureAfterFirstLayout;
        ViewRootImpl viewRoot = mWebView.getViewRootImpl();
        if (mWebView.isHardwareAccelerated()
                && mWebView.getLayerType() != View.LAYER_TYPE_SOFTWARE
                && viewRoot != null) {
            functor = nativeGetDrawGLFunction(mNativeClass);
            if (functor != 0) {
                // force an invalidate if functor attach not successful
                forceInval |= !viewRoot.attachFunctor(functor);
            }
        }

        if (functor == 0
                || forceInval
                || mWebView.getLayerType() != View.LAYER_TYPE_NONE) {
            // invalidate the screen so that the next repaint will show new content
            // TODO: partial invalidate
            mWebView.invalidate();
        }

        // update the zoom information based on the new picture
        if (mZoomManager.onNewPicture(draw))
            invalidate();

        if (isPictureAfterFirstLayout) {
            mViewManager.postReadyToDrawAll();
        }
        scrollEditWithCursor();

        if (mPictureListener != null) {
            if (!mWebView.isHardwareAccelerated()
                    || mWebView.getLayerType() == View.LAYER_TYPE_SOFTWARE) {
                // trigger picture listener for software layers. Hardware layers are
                // triggered in pageSwapCallback
                mPictureListener.onNewPicture(getWebView(), capturePicture());
            }
        }
    }

    /**
     * Used when receiving messages for REQUEST_KEYBOARD_WITH_SELECTION_MSG_ID
     * and UPDATE_TEXT_SELECTION_MSG_ID.
     */
    private void updateTextSelectionFromMessage(int nodePointer,
            int textGeneration, WebViewCore.TextSelectionData data) {
        if (textGeneration == mTextGeneration) {
            if (mInputConnection != null && mFieldPointer == nodePointer) {
                mInputConnection.setSelection(data.mStart, data.mEnd);
            }
        }
        nativeSetTextSelection(mNativeClass, data.mSelectTextPtr);

        if ((data.mSelectionReason == TextSelectionData.REASON_ACCESSIBILITY_INJECTOR)
                || (!mSelectingText && data.mStart != data.mEnd
                        && data.mSelectionReason != TextSelectionData.REASON_SELECT_WORD)) {
            selectionDone();
            mShowTextSelectionExtra = true;
            invalidate();
            return;
        }

        if (data.mSelectTextPtr != 0 &&
                (data.mStart != data.mEnd ||
                (mFieldPointer == nodePointer && mFieldPointer != 0) ||
                (nodePointer == 0 && data.mStart == 0 && data.mEnd == 0))) {
            mIsEditingText = (mFieldPointer == nodePointer) && nodePointer != 0;
            mIsCaretSelection = (data.mStart == data.mEnd && nodePointer != 0);
            if (mIsCaretSelection &&
                    (mInputConnection == null ||
                    mInputConnection.getEditable().length() == 0)) {
                // There's no text, don't show caret handle.
                selectionDone();
            } else {
                if (!mSelectingText) {
                    setupWebkitSelect();
                } else {
                    syncSelectionCursors();
                }
                animateHandles();
                if (mIsCaretSelection) {
                    resetCaretTimer();
                }
            }
        } else {
            selectionDone();
        }
        invalidate();
    }

    private void scrollEditText(int scrollX, int scrollY) {
        // Scrollable edit text. Scroll it.
        float maxScrollX = getMaxTextScrollX();
        float scrollPercentX = ((float)scrollX)/maxScrollX;
        mEditTextContent.offsetTo(-scrollX, -scrollY);
        mWebViewCore.removeMessages(EventHub.SCROLL_TEXT_INPUT);
        mWebViewCore.sendMessage(EventHub.SCROLL_TEXT_INPUT, 0,
                scrollY, (Float)scrollPercentX);
        animateHandles();
    }

    private void beginTextBatch() {
        mIsBatchingTextChanges = true;
    }

    private void commitTextBatch() {
        if (mWebViewCore != null) {
            mWebViewCore.sendMessages(mBatchedTextChanges);
        }
        mBatchedTextChanges.clear();
        mIsBatchingTextChanges = false;
    }

    void sendBatchableInputMessage(int what, int arg1, int arg2,
            Object obj) {
        if (mWebViewCore == null) {
            return;
        }
        Message message = Message.obtain(null, what, arg1, arg2, obj);
        if (mIsBatchingTextChanges) {
            mBatchedTextChanges.add(message);
        } else {
            mWebViewCore.sendMessage(message);
        }
    }

    // Class used to use a dropdown for a <select> element
    private class InvokeListBox implements Runnable {
        // Whether the listbox allows multiple selection.
        private boolean     mMultiple;
        // Passed in to a list with multiple selection to tell
        // which items are selected.
        private int[]       mSelectedArray;
        // Passed in to a list with single selection to tell
        // where the initial selection is.
        private int         mSelection;

        private Container[] mContainers;

        // Need these to provide stable ids to my ArrayAdapter,
        // which normally does not have stable ids. (Bug 1250098)
        private class Container extends Object {
            /**
             * Possible values for mEnabled.  Keep in sync with OptionStatus in
             * WebViewCore.cpp
             */
            final static int OPTGROUP = -1;
            final static int OPTION_DISABLED = 0;
            final static int OPTION_ENABLED = 1;

            String  mString;
            int     mEnabled;
            int     mId;

            @Override
            public String toString() {
                return mString;
            }
        }

        /**
         *  Subclass ArrayAdapter so we can disable OptionGroupLabels,
         *  and allow filtering.
         */
        private class MyArrayListAdapter extends ArrayAdapter<Container> {
            public MyArrayListAdapter() {
                super(WebViewClassic.this.mContext,
                        mMultiple ? com.android.internal.R.layout.select_dialog_multichoice :
                        com.android.internal.R.layout.webview_select_singlechoice,
                        mContainers);
            }

            @Override
            public View getView(int position, View convertView,
                    ViewGroup parent) {
                // Always pass in null so that we will get a new CheckedTextView
                // Otherwise, an item which was previously used as an <optgroup>
                // element (i.e. has no check), could get used as an <option>
                // element, which needs a checkbox/radio, but it would not have
                // one.
                convertView = super.getView(position, null, parent);
                Container c = item(position);
                if (c != null && Container.OPTION_ENABLED != c.mEnabled) {
                    // ListView does not draw dividers between disabled and
                    // enabled elements.  Use a LinearLayout to provide dividers
                    LinearLayout layout = new LinearLayout(mContext);
                    layout.setOrientation(LinearLayout.VERTICAL);
                    if (position > 0) {
                        View dividerTop = new View(mContext);
                        dividerTop.setBackgroundResource(
                                android.R.drawable.divider_horizontal_bright);
                        layout.addView(dividerTop);
                    }

                    if (Container.OPTGROUP == c.mEnabled) {
                        // Currently select_dialog_multichoice uses CheckedTextViews.
                        // If that changes, the class cast will no longer be valid.
                        if (mMultiple) {
                            Assert.assertTrue(convertView instanceof CheckedTextView);
                            ((CheckedTextView) convertView).setCheckMarkDrawable(null);
                        }
                    } else {
                        // c.mEnabled == Container.OPTION_DISABLED
                        // Draw the disabled element in a disabled state.
                        convertView.setEnabled(false);
                    }

                    layout.addView(convertView);
                    if (position < getCount() - 1) {
                        View dividerBottom = new View(mContext);
                        dividerBottom.setBackgroundResource(
                                android.R.drawable.divider_horizontal_bright);
                        layout.addView(dividerBottom);
                    }
                    return layout;
                }
                return convertView;
            }

            @Override
            public boolean hasStableIds() {
                // AdapterView's onChanged method uses this to determine whether
                // to restore the old state.  Return false so that the old (out
                // of date) state does not replace the new, valid state.
                return false;
            }

            private Container item(int position) {
                if (position < 0 || position >= getCount()) {
                    return null;
                }
                return getItem(position);
            }

            @Override
            public long getItemId(int position) {
                Container item = item(position);
                if (item == null) {
                    return -1;
                }
                return item.mId;
            }

            @Override
            public boolean areAllItemsEnabled() {
                return false;
            }

            @Override
            public boolean isEnabled(int position) {
                Container item = item(position);
                if (item == null) {
                    return false;
                }
                return Container.OPTION_ENABLED == item.mEnabled;
            }
        }

        private InvokeListBox(String[] array, int[] enabled, int[] selected) {
            mMultiple = true;
            mSelectedArray = selected;

            int length = array.length;
            mContainers = new Container[length];
            for (int i = 0; i < length; i++) {
                mContainers[i] = new Container();
                mContainers[i].mString = array[i];
                mContainers[i].mEnabled = enabled[i];
                mContainers[i].mId = i;
            }
        }

        private InvokeListBox(String[] array, int[] enabled, int selection) {
            mSelection = selection;
            mMultiple = false;

            int length = array.length;
            mContainers = new Container[length];
            for (int i = 0; i < length; i++) {
                mContainers[i] = new Container();
                mContainers[i].mString = array[i];
                mContainers[i].mEnabled = enabled[i];
                mContainers[i].mId = i;
            }
        }

        /*
         * Whenever the data set changes due to filtering, this class ensures
         * that the checked item remains checked.
         */
        private class SingleDataSetObserver extends DataSetObserver {
            private long        mCheckedId;
            private ListView    mListView;
            private Adapter     mAdapter;

            /*
             * Create a new observer.
             * @param id The ID of the item to keep checked.
             * @param l ListView for getting and clearing the checked states
             * @param a Adapter for getting the IDs
             */
            public SingleDataSetObserver(long id, ListView l, Adapter a) {
                mCheckedId = id;
                mListView = l;
                mAdapter = a;
            }

            @Override
            public void onChanged() {
                // The filter may have changed which item is checked.  Find the
                // item that the ListView thinks is checked.
                int position = mListView.getCheckedItemPosition();
                long id = mAdapter.getItemId(position);
                if (mCheckedId != id) {
                    // Clear the ListView's idea of the checked item, since
                    // it is incorrect
                    mListView.clearChoices();
                    // Search for mCheckedId.  If it is in the filtered list,
                    // mark it as checked
                    int count = mAdapter.getCount();
                    for (int i = 0; i < count; i++) {
                        if (mAdapter.getItemId(i) == mCheckedId) {
                            mListView.setItemChecked(i, true);
                            break;
                        }
                    }
                }
            }
        }

        @Override
        public void run() {
            if (mWebViewCore == null
                    || getWebView().getWindowToken() == null
                    || getWebView().getViewRootImpl() == null) {
                // We've been detached and/or destroyed since this was posted
                return;
            }
            final ListView listView = (ListView) LayoutInflater.from(mContext)
                    .inflate(com.android.internal.R.layout.select_dialog, null);
            final MyArrayListAdapter adapter = new MyArrayListAdapter();
            AlertDialog.Builder b = new AlertDialog.Builder(mContext)
                    .setView(listView).setCancelable(true)
                    .setInverseBackgroundForced(true);

            if (mMultiple) {
                b.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        mWebViewCore.sendMessage(
                                EventHub.LISTBOX_CHOICES,
                                adapter.getCount(), 0,
                                listView.getCheckedItemPositions());
                    }});
                b.setNegativeButton(android.R.string.cancel,
                        new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        mWebViewCore.sendMessage(
                                EventHub.SINGLE_LISTBOX_CHOICE, -2, 0);
                }});
            }
            mListBoxDialog = b.create();
            listView.setAdapter(adapter);
            listView.setFocusableInTouchMode(true);
            // There is a bug (1250103) where the checks in a ListView with
            // multiple items selected are associated with the positions, not
            // the ids, so the items do not properly retain their checks when
            // filtered.  Do not allow filtering on multiple lists until
            // that bug is fixed.

            listView.setTextFilterEnabled(!mMultiple);
            if (mMultiple) {
                listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
                int length = mSelectedArray.length;
                for (int i = 0; i < length; i++) {
                    listView.setItemChecked(mSelectedArray[i], true);
                }
            } else {
                listView.setOnItemClickListener(new OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View v,
                            int position, long id) {
                        // Rather than sending the message right away, send it
                        // after the page regains focus.
                        mListBoxMessage = Message.obtain(null,
                                EventHub.SINGLE_LISTBOX_CHOICE, (int) id, 0);
                        if (mListBoxDialog != null) {
                            mListBoxDialog.dismiss();
                            mListBoxDialog = null;
                        }
                    }
                });
                if (mSelection != -1) {
                    listView.setSelection(mSelection);
                    listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
                    listView.setItemChecked(mSelection, true);
                    DataSetObserver observer = new SingleDataSetObserver(
                            adapter.getItemId(mSelection), listView, adapter);
                    adapter.registerDataSetObserver(observer);
                }
            }
            mListBoxDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    mWebViewCore.sendMessage(
                                EventHub.SINGLE_LISTBOX_CHOICE, -2, 0);
                    mListBoxDialog = null;
                }
            });
            mListBoxDialog.show();
        }
    }

    private Message mListBoxMessage;

    /*
     * Request a dropdown menu for a listbox with multiple selection.
     *
     * @param array Labels for the listbox.
     * @param enabledArray  State for each element in the list.  See static
     *      integers in Container class.
     * @param selectedArray Which positions are initally selected.
     */
    void requestListBox(String[] array, int[] enabledArray, int[]
            selectedArray) {
        mPrivateHandler.post(
                new InvokeListBox(array, enabledArray, selectedArray));
    }

    /*
     * Request a dropdown menu for a listbox with single selection or a single
     * <select> element.
     *
     * @param array Labels for the listbox.
     * @param enabledArray  State for each element in the list.  See static
     *      integers in Container class.
     * @param selection Which position is initally selected.
     */
    void requestListBox(String[] array, int[] enabledArray, int selection) {
        mPrivateHandler.post(
                new InvokeListBox(array, enabledArray, selection));
    }

    private int getScaledMaxXScroll() {
        int width;
        if (mHeightCanMeasure == false) {
            width = getViewWidth() / 4;
        } else {
            Rect visRect = new Rect();
            calcOurVisibleRect(visRect);
            width = visRect.width() / 2;
        }
        // FIXME the divisor should be retrieved from somewhere
        return viewToContentX(width);
    }

    private int getScaledMaxYScroll() {
        int height;
        if (mHeightCanMeasure == false) {
            height = getViewHeight() / 4;
        } else {
            Rect visRect = new Rect();
            calcOurVisibleRect(visRect);
            height = visRect.height() / 2;
        }
        // FIXME the divisor should be retrieved from somewhere
        // the closest thing today is hard-coded into ScrollView.java
        // (from ScrollView.java, line 363)   int maxJump = height/2;
        return Math.round(height * mZoomManager.getInvScale());
    }

    /**
     * Called by JNI to invalidate view
     */
    private void viewInvalidate() {
        invalidate();
    }

    /**
     * Pass the key directly to the page.  This assumes that
     * nativePageShouldHandleShiftAndArrows() returned true.
     */
    private void letPageHandleNavKey(int keyCode, long time, boolean down, int metaState) {
        int keyEventAction;
        if (down) {
            keyEventAction = KeyEvent.ACTION_DOWN;
        } else {
            keyEventAction = KeyEvent.ACTION_UP;
        }

        KeyEvent event = new KeyEvent(time, time, keyEventAction, keyCode,
                1, (metaState & KeyEvent.META_SHIFT_ON)
                | (metaState & KeyEvent.META_ALT_ON)
                | (metaState & KeyEvent.META_SYM_ON)
                , KeyCharacterMap.VIRTUAL_KEYBOARD, 0, 0);
        sendKeyEvent(event);
    }

    private void sendKeyEvent(KeyEvent event) {
        int direction = 0;
        switch (event.getKeyCode()) {
        case KeyEvent.KEYCODE_DPAD_DOWN:
            direction = View.FOCUS_DOWN;
            break;
        case KeyEvent.KEYCODE_DPAD_UP:
            direction = View.FOCUS_UP;
            break;
        case KeyEvent.KEYCODE_DPAD_LEFT:
            direction = View.FOCUS_LEFT;
            break;
        case KeyEvent.KEYCODE_DPAD_RIGHT:
            direction = View.FOCUS_RIGHT;
            break;
        case KeyEvent.KEYCODE_TAB:
            direction = event.isShiftPressed() ? View.FOCUS_BACKWARD : View.FOCUS_FORWARD;
            break;
        }
        if (direction != 0 && mWebView.focusSearch(direction) == null) {
            // Can't take focus in that direction
            direction = 0;
        }
        int eventHubAction = EventHub.KEY_UP;
        if (event.getAction() == KeyEvent.ACTION_DOWN) {
            eventHubAction = EventHub.KEY_DOWN;
            int sound = keyCodeToSoundsEffect(event.getKeyCode());
            if (sound != 0) {
                mWebView.playSoundEffect(sound);
            }
        }
        sendBatchableInputMessage(eventHubAction, direction, 0, event);
    }

    /**
     * See {@link WebView#setBackgroundColor(int)}
     */
    @Override
    public void setBackgroundColor(int color) {
        mBackgroundColor = color;
        mWebViewCore.sendMessage(EventHub.SET_BACKGROUND_COLOR, color);
    }

    /**
     * Enable the communication b/t the webView and VideoViewProxy
     *
     * only used by the Browser
     */
    public void setHTML5VideoViewProxy(HTML5VideoViewProxy proxy) {
        mHTML5VideoViewProxy = proxy;
    }

    /**
     * Set the time to wait between passing touches to WebCore. See also the
     * TOUCH_SENT_INTERVAL member for further discussion.
     *
     * This is only used by the DRT test application.
     */
    public void setTouchInterval(int interval) {
        mCurrentTouchInterval = interval;
    }

    /**
     * Copy text into the clipboard. This is called indirectly from
     * WebViewCore.
     * @param text The text to put into the clipboard.
     */
    private void copyToClipboard(String text) {
        ClipboardManager cm = (ClipboardManager)mContext
                .getSystemService(Context.CLIPBOARD_SERVICE);
        ClipData clip = ClipData.newPlainText(getTitle(), text);
        cm.setPrimaryClip(clip);
    }

    /*package*/ void autoFillForm(int autoFillQueryId) {
        mPrivateHandler.obtainMessage(AUTOFILL_FORM, autoFillQueryId, 0)
            .sendToTarget();
    }

    /* package */ ViewManager getViewManager() {
        return mViewManager;
    }

    /** send content invalidate */
    protected void contentInvalidateAll() {
        if (mWebViewCore != null && !mBlockWebkitViewMessages) {
            mWebViewCore.sendMessage(EventHub.CONTENT_INVALIDATE_ALL);
        }
    }

    /** discard all textures from tiles. Used in Profiled WebView */
    public void discardAllTextures() {
        nativeDiscardAllTextures();
    }

    @Override
    public void setLayerType(int layerType, Paint paint) {
        updateHwAccelerated();
    }

    private void updateHwAccelerated() {
        if (mNativeClass == 0) {
            return;
        }
        boolean hwAccelerated = false;
        if (mWebView.isHardwareAccelerated()
                && mWebView.getLayerType() != View.LAYER_TYPE_SOFTWARE) {
            hwAccelerated = true;
        }

        // result is of type LayerAndroid::InvalidateFlags, non zero means invalidate/redraw
        int result = nativeSetHwAccelerated(mNativeClass, hwAccelerated);
        if (mWebViewCore != null && !mBlockWebkitViewMessages && result != 0) {
            mWebViewCore.contentDraw();
        }
    }

    /**
     * Begin collecting per-tile profiling data
     *
     * only used by profiling tests
     */
    public void tileProfilingStart() {
        nativeTileProfilingStart();
    }
    /**
     * Return per-tile profiling data
     *
     * only used by profiling tests
     */
    public float tileProfilingStop() {
        return nativeTileProfilingStop();
    }

    /** only used by profiling tests */
    public void tileProfilingClear() {
        nativeTileProfilingClear();
    }
    /** only used by profiling tests */
    public int tileProfilingNumFrames() {
        return nativeTileProfilingNumFrames();
    }
    /** only used by profiling tests */
    public int tileProfilingNumTilesInFrame(int frame) {
        return nativeTileProfilingNumTilesInFrame(frame);
    }
    /** only used by profiling tests */
    public int tileProfilingGetInt(int frame, int tile, String key) {
        return nativeTileProfilingGetInt(frame, tile, key);
    }
    /** only used by profiling tests */
    public float tileProfilingGetFloat(int frame, int tile, String key) {
        return nativeTileProfilingGetFloat(frame, tile, key);
    }

    /**
     * Checks the focused content for an editable text field. This can be
     * text input or ContentEditable.
     * @return true if the focused item is an editable text field.
     */
    boolean focusCandidateIsEditableText() {
        if (mFocusedNode != null) {
            return mFocusedNode.mEditable;
        }
        return false;
    }

    // Called via JNI
    private void postInvalidate() {
        mWebView.postInvalidate();
    }

    // Note: must be called before first WebViewClassic is created.
    public static void setShouldMonitorWebCoreThread() {
        WebViewCore.setShouldMonitorWebCoreThread();
    }

    @Override
    public void dumpViewHierarchyWithProperties(BufferedWriter out, int level) {
        int layer = getBaseLayer();
        if (layer != 0) {
            try {
                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                ViewStateSerializer.dumpLayerHierarchy(layer, stream, level);
                stream.close();
                byte[] buf = stream.toByteArray();
                out.write(new String(buf, "ascii"));
            } catch (IOException e) {}
        }
    }

    @Override
    public View findHierarchyView(String className, int hashCode) {
        if (mNativeClass == 0) return null;
        Picture pic = new Picture();
        if (!nativeDumpLayerContentToPicture(mNativeClass, className, hashCode, pic)) {
            return null;
        }
        return new PictureWrapperView(getContext(), pic, mWebView);
    }

    private static class PictureWrapperView extends View {
        Picture mPicture;
        WebView mWebView;

        public PictureWrapperView(Context context, Picture picture, WebView parent) {
            super(context);
            mPicture = picture;
            mWebView = parent;
            setWillNotDraw(false);
            setRight(mPicture.getWidth());
            setBottom(mPicture.getHeight());
        }

        @Override
        protected void onDraw(Canvas canvas) {
            canvas.drawPicture(mPicture);
        }

        @Override
        public boolean post(Runnable action) {
            return mWebView.post(action);
        }
    }

    private native void     nativeCreate(int ptr, String drawableDir, boolean isHighEndGfx);
    private native void     nativeDebugDump();
    private static native void nativeDestroy(int ptr);

    private native void nativeDraw(Canvas canvas, RectF visibleRect,
            int color, int extra);
    private native void     nativeDumpDisplayTree(String urlOrNull);
    private native boolean  nativeEvaluateLayersAnimations(int nativeInstance);
    private native int      nativeCreateDrawGLFunction(int nativeInstance, Rect invScreenRect,
            Rect screenRect, RectF visibleContentRect, float scale, int extras);
    private native int      nativeGetDrawGLFunction(int nativeInstance);
    private native void     nativeUpdateDrawGLFunction(int nativeInstance, Rect invScreenRect,
            Rect screenRect, RectF visibleContentRect, float scale);
    private native String   nativeGetSelection();
    private native void     nativeSetHeightCanMeasure(boolean measure);
    private native boolean  nativeSetBaseLayer(int nativeInstance,
            int layer, boolean showVisualIndicator, boolean isPictureAfterFirstLayout,
            int scrollingLayer);
    private native int      nativeGetBaseLayer(int nativeInstance);
    private native void     nativeCopyBaseContentToPicture(Picture pict);
    private native boolean     nativeDumpLayerContentToPicture(int nativeInstance,
            String className, int layerId, Picture pict);
    private native boolean  nativeHasContent();
    private native void     nativeStopGL(int ptr);
    private native void     nativeDiscardAllTextures();
    private native void     nativeTileProfilingStart();
    private native float    nativeTileProfilingStop();
    private native void     nativeTileProfilingClear();
    private native int      nativeTileProfilingNumFrames();
    private native int      nativeTileProfilingNumTilesInFrame(int frame);
    private native int      nativeTileProfilingGetInt(int frame, int tile, String key);
    private native float    nativeTileProfilingGetFloat(int frame, int tile, String key);

    private native void     nativeUseHardwareAccelSkia(boolean enabled);

    // Returns a pointer to the scrollable LayerAndroid at the given point.
    private native int      nativeScrollableLayer(int nativeInstance, int x, int y, Rect scrollRect,
            Rect scrollBounds);
    /**
     * Scroll the specified layer.
     * @param nativeInstance Native WebView instance
     * @param layer Id of the layer to scroll, as determined by nativeScrollableLayer.
     * @param newX Destination x position to which to scroll.
     * @param newY Destination y position to which to scroll.
     * @return True if the layer is successfully scrolled.
     */
    private native boolean  nativeScrollLayer(int nativeInstance, int layer, int newX, int newY);
    private native void     nativeSetIsScrolling(boolean isScrolling);
    private native int      nativeGetBackgroundColor(int nativeInstance);
    native boolean  nativeSetProperty(String key, String value);
    native String   nativeGetProperty(String key);
    /**
     * See {@link ComponentCallbacks2} for the trim levels and descriptions
     */
    private static native void     nativeOnTrimMemory(int level);
    private static native void nativeSetPauseDrawing(int instance, boolean pause);
    private static native void nativeSetTextSelection(int instance, int selection);
    private static native int nativeGetHandleLayerId(int instance, int handle,
            Point cursorLocation, QuadF textQuad);
    private static native void nativeMapLayerRect(int instance, int layerId,
            Rect rect);
    // Returns 1 if a layer sync is needed, else 0
    private static native int nativeSetHwAccelerated(int instance, boolean hwAccelerated);
    private static native void nativeFindMaxVisibleRect(int instance, int layerId,
            Rect visibleContentRect);
    private static native boolean nativeIsHandleLeft(int instance, int handleId);
    private static native boolean nativeIsPointVisible(int instance,
            int layerId, int contentX, int contentY);
}