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
|
/*
* Copyright (C) 2007 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.app.ActivityManager;
import android.content.Context;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.Cursor;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.Region;
import android.media.MediaFile;
import android.net.ProxyProperties;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.Process;
import android.provider.MediaStore;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.SurfaceView;
import android.view.View;
import android.webkit.DeviceMotionService;
import android.webkit.DeviceMotionAndOrientationManager;
import android.webkit.DeviceOrientationService;
import android.webkit.JniUtil;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
import junit.framework.Assert;
/**
* @hide
*/
public final class WebViewCore {
private static final String LOGTAG = "webcore";
static {
// Load libwebcore during static initialization. This happens in the
// zygote process so it will be shared read-only across all app
// processes.
try {
System.loadLibrary("webcore");
} catch (UnsatisfiedLinkError e) {
Log.e(LOGTAG, "Unable to load webcore library");
}
}
/*
* WebViewCore always executes in the same thread as the native webkit.
*/
// The WebView that corresponds to this WebViewCore.
private WebView mWebView;
// Proxy for handling callbacks from native code
private final CallbackProxy mCallbackProxy;
// Settings object for maintaining all settings
private final WebSettings mSettings;
// Context for initializing the BrowserFrame with the proper assets.
private final Context mContext;
// The pointer to a native view object.
private int mNativeClass;
// The BrowserFrame is an interface to the native Frame component.
private BrowserFrame mBrowserFrame;
// Custom JS interfaces to add during the initialization.
private Map<String, Object> mJavascriptInterfaces;
/*
* range is from 200 to 10,000. 0 is a special value means device-width. -1
* means undefined.
*/
private int mViewportWidth = -1;
/*
* range is from 200 to 10,000. 0 is a special value means device-height. -1
* means undefined.
*/
private int mViewportHeight = -1;
/*
* scale in percent, range is from 1 to 1000. 0 means undefined.
*/
private int mViewportInitialScale = 0;
/*
* scale in percent, range is from 1 to 1000. 0 means undefined.
*/
private int mViewportMinimumScale = 0;
/*
* scale in percent, range is from 1 to 1000. 0 means undefined.
*/
private int mViewportMaximumScale = 0;
private boolean mViewportUserScalable = true;
/*
* range is from 70 to 400.
* 0 is a special value means device-dpi. The default scale factor will be
* always 100.
* -1 means undefined. The default scale factor will be
* WebView.DEFAULT_SCALE_PERCENT.
*/
private int mViewportDensityDpi = -1;
private float mRestoredScale = 0;
private float mRestoredTextWrapScale = 0;
private int mRestoredX = 0;
private int mRestoredY = 0;
private DeviceMotionAndOrientationManager mDeviceMotionAndOrientationManager =
new DeviceMotionAndOrientationManager(this);
private DeviceMotionService mDeviceMotionService;
private DeviceOrientationService mDeviceOrientationService;
private int mLowMemoryUsageThresholdMb;
private int mHighMemoryUsageThresholdMb;
private int mHighUsageDeltaMb;
// The thread name used to identify the WebCore thread and for use in
// debugging other classes that require operation within the WebCore thread.
/* package */ static final String THREAD_NAME = "WebViewCoreThread";
public WebViewCore(Context context, WebView w, CallbackProxy proxy,
Map<String, Object> javascriptInterfaces) {
// No need to assign this in the WebCore thread.
mCallbackProxy = proxy;
mWebView = w;
mJavascriptInterfaces = javascriptInterfaces;
// This context object is used to initialize the WebViewCore during
// subwindow creation.
mContext = context;
// We need to wait for the initial thread creation before sending
// a message to the WebCore thread.
// XXX: This is the only time the UI thread will wait for the WebCore
// thread!
synchronized (WebViewCore.class) {
if (sWebCoreHandler == null) {
// Create a global thread and start it.
Thread t = new Thread(new WebCoreThread());
t.setName(THREAD_NAME);
t.start();
try {
WebViewCore.class.wait();
} catch (InterruptedException e) {
Log.e(LOGTAG, "Caught exception while waiting for thread " +
"creation.");
Log.e(LOGTAG, Log.getStackTraceString(e));
}
}
}
// Create an EventHub to handle messages before and after the thread is
// ready.
mEventHub = new EventHub();
// Create a WebSettings object for maintaining all settings
mSettings = new WebSettings(mContext, mWebView);
// The WebIconDatabase needs to be initialized within the UI thread so
// just request the instance here.
WebIconDatabase.getInstance();
// Create the WebStorage singleton and the UI handler
WebStorage.getInstance().createUIHandler();
// Create the UI handler for GeolocationPermissions
GeolocationPermissions.getInstance().createUIHandler();
// Get the memory class of the current device. V8 will use these values
// to GC more effectively.
ActivityManager manager = (ActivityManager) mContext.getSystemService(
Context.ACTIVITY_SERVICE);
ActivityManager.MemoryInfo memInfo = new ActivityManager.MemoryInfo();
manager.getMemoryInfo(memInfo);
// Allow us to use up to our memory class value before V8's GC kicks in.
// These values have been determined by experimentation.
mLowMemoryUsageThresholdMb = manager.getLargeMemoryClass();
mHighMemoryUsageThresholdMb = (int) (mLowMemoryUsageThresholdMb * 1.5);
// Avoid constant V8 GC when memory usage equals to working set estimate.
mHighUsageDeltaMb = mLowMemoryUsageThresholdMb / 32;
// Send a message to initialize the WebViewCore.
Message init = sWebCoreHandler.obtainMessage(
WebCoreThread.INITIALIZE, this);
sWebCoreHandler.sendMessage(init);
}
/* Initialize private data within the WebCore thread.
*/
private void initialize() {
/* Initialize our private BrowserFrame class to handle all
* frame-related functions. We need to create a new view which
* in turn creates a C level FrameView and attaches it to the frame.
*/
mBrowserFrame = new BrowserFrame(mContext, this, mCallbackProxy,
mSettings, mJavascriptInterfaces);
mJavascriptInterfaces = null;
// Sync the native settings and also create the WebCore thread handler.
mSettings.syncSettingsAndCreateHandler(mBrowserFrame);
// Create the handler and transfer messages for the IconDatabase
WebIconDatabase.getInstance().createHandler();
// Create the handler for WebStorage
WebStorage.getInstance().createHandler();
// Create the handler for GeolocationPermissions.
GeolocationPermissions.getInstance().createHandler();
// The transferMessages call will transfer all pending messages to the
// WebCore thread handler.
mEventHub.transferMessages();
// Send a message back to WebView to tell it that we have set up the
// WebCore thread.
if (mWebView != null) {
Message.obtain(mWebView.mPrivateHandler,
WebView.WEBCORE_INITIALIZED_MSG_ID,
mNativeClass, 0).sendToTarget();
}
}
/* Handle the initialization of WebViewCore during subwindow creation. This
* method is called from the WebCore thread but it is called before the
* INITIALIZE message can be handled.
*/
/* package */ void initializeSubwindow() {
// Go ahead and initialize the core components.
initialize();
// Remove the INITIALIZE method so we don't try to initialize twice.
sWebCoreHandler.removeMessages(WebCoreThread.INITIALIZE, this);
}
/* Get the BrowserFrame component. This is used for subwindow creation and
* is called only from BrowserFrame in the WebCore thread. */
/* package */ synchronized BrowserFrame getBrowserFrame() {
return mBrowserFrame;
}
//-------------------------------------------------------------------------
// Common methods
//-------------------------------------------------------------------------
/**
* Causes all timers to pause. This applies to all WebViews in the current
* app process.
*/
public static void pauseTimers() {
if (BrowserFrame.sJavaBridge == null) {
throw new IllegalStateException(
"No WebView has been created in this process!");
}
BrowserFrame.sJavaBridge.pause();
}
/**
* Resume all timers. This applies to all WebViews in the current process.
*/
public static void resumeTimers() {
if (BrowserFrame.sJavaBridge == null) {
throw new IllegalStateException(
"No WebView has been created in this process!");
}
BrowserFrame.sJavaBridge.resume();
}
public WebSettings getSettings() {
return mSettings;
}
/*
* Given mimeType, check whether it's supported in Android media framework.
* mimeType could be such as "audio/ogg" and "video/mp4".
*/
/* package */ static boolean isSupportedMediaMimeType(String mimeType) {
int fileType = MediaFile.getFileTypeForMimeType(mimeType);
return MediaFile.isAudioFileType(fileType)
|| MediaFile.isVideoFileType(fileType)
|| MediaFile.isPlayListFileType(fileType)
// The following is not in Media framework, but it's supported.
|| (mimeType != null && mimeType.startsWith("video/m4v"));
}
/**
* Add an error message to the client's console.
* @param message The message to add
* @param lineNumber the line on which the error occurred
* @param sourceID the filename of the source that caused the error.
* @param msgLevel the log level of this message. This is a value casted to int
* from WebCore::MessageLevel in WebCore/page/Console.h.
*/
protected void addMessageToConsole(String message, int lineNumber, String sourceID,
int msgLevel) {
mCallbackProxy.addMessageToConsole(message, lineNumber, sourceID, msgLevel);
}
/**
* Invoke a javascript alert.
* @param message The message displayed in the alert.
*/
protected void jsAlert(String url, String message) {
mCallbackProxy.onJsAlert(url, message);
}
/**
* Called by JNI. Send a message to the UI thread to hide the soft keyboard
* if the node pointed to by nodePointer is still in focus.
* @param nodePointer The node which just blurred.
*/
private void formDidBlur(int nodePointer) {
if (mWebView == null) return;
Message.obtain(mWebView.mPrivateHandler, WebView.FORM_DID_BLUR,
nodePointer, 0).sendToTarget();
}
/**
* Called by JNI. Open a file chooser to upload a file.
* @param acceptType The value of the 'accept' attribute of the
* input tag associated with this file picker.
* @return String version of the URI.
*/
private String openFileChooser(String acceptType) {
Uri uri = mCallbackProxy.openFileChooser(acceptType);
if (uri != null) {
String filePath = "";
// Note - querying for MediaStore.Images.Media.DATA
// seems to work for all content URIs, not just images
Cursor cursor = mContext.getContentResolver().query(
uri,
new String[] { MediaStore.Images.Media.DATA },
null, null, null);
if (cursor != null) {
try {
if (cursor.moveToNext()) {
filePath = cursor.getString(0);
}
} finally {
cursor.close();
}
} else {
filePath = uri.getLastPathSegment();
}
String uriString = uri.toString();
BrowserFrame.sJavaBridge.storeFilePathForContentUri(filePath, uriString);
return uriString;
}
return "";
}
/**
* Notify the browser that the origin has exceeded it's database quota.
* @param url The URL that caused the overflow.
* @param databaseIdentifier The identifier of the database.
* @param currentQuota The current quota for the origin.
* @param estimatedSize The estimated size of the database.
*/
protected void exceededDatabaseQuota(String url,
String databaseIdentifier,
long currentQuota,
long estimatedSize) {
// Inform the callback proxy of the quota overflow. Send an object
// that encapsulates a call to the nativeSetDatabaseQuota method to
// awaken the sleeping webcore thread when a decision from the
// client to allow or deny quota is available.
mCallbackProxy.onExceededDatabaseQuota(url, databaseIdentifier,
currentQuota, estimatedSize, getUsedQuota(),
new WebStorage.QuotaUpdater() {
public void updateQuota(long quota) {
nativeSetNewStorageLimit(quota);
}
});
}
/**
* Notify the browser that the appcache has exceeded its max size.
* @param spaceNeeded is the amount of disk space that would be needed
* in order for the last appcache operation to succeed.
*/
protected void reachedMaxAppCacheSize(long spaceNeeded) {
mCallbackProxy.onReachedMaxAppCacheSize(spaceNeeded, getUsedQuota(),
new WebStorage.QuotaUpdater() {
public void updateQuota(long quota) {
nativeSetNewStorageLimit(quota);
}
});
}
protected void populateVisitedLinks() {
ValueCallback callback = new ValueCallback<String[]>() {
public void onReceiveValue(String[] value) {
sendMessage(EventHub.POPULATE_VISITED_LINKS, (Object)value);
}
};
mCallbackProxy.getVisitedHistory(callback);
}
/**
* Shows a prompt to ask the user to set the Geolocation permission state
* for the given origin.
* @param origin The origin for which Geolocation permissions are
* requested.
*/
protected void geolocationPermissionsShowPrompt(String origin) {
mCallbackProxy.onGeolocationPermissionsShowPrompt(origin,
new GeolocationPermissions.Callback() {
public void invoke(String origin, boolean allow, boolean remember) {
GeolocationPermissionsData data = new GeolocationPermissionsData();
data.mOrigin = origin;
data.mAllow = allow;
data.mRemember = remember;
// Marshall to WebCore thread.
sendMessage(EventHub.GEOLOCATION_PERMISSIONS_PROVIDE, data);
}
});
}
/**
* Hides the Geolocation permissions prompt.
*/
protected void geolocationPermissionsHidePrompt() {
mCallbackProxy.onGeolocationPermissionsHidePrompt();
}
/**
* Invoke a javascript confirm dialog.
* @param message The message displayed in the dialog.
* @return True if the user confirmed or false if the user cancelled.
*/
protected boolean jsConfirm(String url, String message) {
return mCallbackProxy.onJsConfirm(url, message);
}
/**
* Invoke a javascript prompt dialog.
* @param message The message to be displayed in the dialog.
* @param defaultValue The default value in the prompt input.
* @return The input from the user or null to indicate the user cancelled
* the dialog.
*/
protected String jsPrompt(String url, String message, String defaultValue) {
return mCallbackProxy.onJsPrompt(url, message, defaultValue);
}
/**
* Invoke a javascript before unload dialog.
* @param url The url that is requesting the dialog.
* @param message The message displayed in the dialog.
* @return True if the user confirmed or false if the user cancelled. False
* will cancel the navigation.
*/
protected boolean jsUnload(String url, String message) {
return mCallbackProxy.onJsBeforeUnload(url, message);
}
/**
*
* Callback to notify that a JavaScript execution timeout has occured.
* @return True if the JavaScript execution should be interrupted. False
* will continue the execution.
*/
protected boolean jsInterrupt() {
return mCallbackProxy.onJsTimeout();
}
/**
* Notify the webview that this is an installable web app.
*/
protected void setInstallableWebApp() {
mCallbackProxy.setInstallableWebApp();
}
/**
* Notify the webview that we want to display the video layer fullscreen.
*/
protected void enterFullscreenForVideoLayer(int layerId, String url) {
if (mWebView == null) return;
Message message = Message.obtain(mWebView.mPrivateHandler,
WebView.ENTER_FULLSCREEN_VIDEO, layerId, 0);
message.obj = url;
message.sendToTarget();
}
//-------------------------------------------------------------------------
// JNI methods
//-------------------------------------------------------------------------
static native String nativeFindAddress(String addr, boolean caseInsensitive);
/**
* Empty the picture set.
*/
private native void nativeClearContent();
private native void nativeContentInvalidateAll();
/**
* Redraw a portion of the picture set. The Point wh returns the
* width and height of the overall picture.
*/
private native int nativeRecordContent(Region invalRegion, Point wh);
/**
* Update the layers' content
*/
private native int nativeUpdateLayers(Region invalRegion);
private native boolean nativeFocusBoundsChanged();
/**
* Splits slow parts of the picture set. Called from the webkit thread after
* WebView.nativeDraw() returns content to be split.
*/
private native void nativeSplitContent(int content);
private native boolean nativeKey(int keyCode, int unichar,
int repeatCount, boolean isShift, boolean isAlt, boolean isSym,
boolean isDown);
private native void nativeClick(int framePtr, int nodePtr, boolean fake);
private native void nativeSendListBoxChoices(boolean[] choices, int size);
private native void nativeSendListBoxChoice(int choice);
/* Tell webkit what its width and height are, for the purposes
of layout/line-breaking. These coordinates are in document space,
which is the same as View coords unless we have zoomed the document
(see nativeSetZoom).
textWrapWidth is used by layout to wrap column around. If viewport uses
fixed size, textWrapWidth can be different from width with zooming.
should this be called nativeSetViewPortSize?
*/
private native void nativeSetSize(int width, int height, int textWrapWidth,
float scale, int screenWidth, int screenHeight, int anchorX,
int anchorY, boolean ignoreHeight);
private native int nativeGetContentMinPrefWidth();
// Start: functions that deal with text editing
private native void nativeReplaceTextfieldText(
int oldStart, int oldEnd, String replace, int newStart, int newEnd,
int textGeneration);
private native void passToJs(int gen,
String currentText, int keyCode, int keyValue, boolean down,
boolean cap, boolean fn, boolean sym);
private native void nativeSetFocusControllerActive(boolean active);
private native void nativeSaveDocumentState(int frame);
private native void nativeMoveFocus(int framePtr, int nodePointer);
private native void nativeMoveMouse(int framePtr, int x, int y);
private native void nativeMoveMouseIfLatest(int moveGeneration,
int framePtr, int x, int y);
private native String nativeRetrieveHref(int x, int y);
private native String nativeRetrieveAnchorText(int x, int y);
private native String nativeRetrieveImageSource(int x, int y);
private native void nativeStopPaintingCaret();
private native void nativeTouchUp(int touchGeneration,
int framePtr, int nodePtr, int x, int y);
private native boolean nativeHandleTouchEvent(int action, int[] idArray,
int[] xArray, int[] yArray, int count, int actionIndex, int metaState);
private native void nativeUpdateFrameCache();
private native void nativeSetBackgroundColor(int color);
private native void nativeDumpDomTree(boolean useFile);
private native void nativeDumpRenderTree(boolean useFile);
private native void nativeDumpNavTree();
private native void nativeDumpV8Counters();
private native void nativeSetJsFlags(String flags);
/**
* 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.
* @param textGeneration Text generation number when delete was pressed.
*/
private native void nativeDeleteSelection(int start, int end,
int textGeneration);
/**
* 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.
*/
private native void nativeSetSelection(int start, int end);
// Register a scheme to be treated as local scheme so that it can access
// local asset files for resources
private native void nativeRegisterURLSchemeAsLocal(String scheme);
/*
* Inform webcore that the user has decided whether to allow or deny new
* quota for the current origin or more space for the app cache, and that
* the main thread should wake up now.
* @param limit Is the new quota for an origin or new app cache max size.
*/
private native void nativeSetNewStorageLimit(long limit);
/**
* Provide WebCore with a Geolocation permission state for the specified
* origin.
* @param origin The origin for which Geolocation permissions are provided.
* @param allow Whether Geolocation permissions are allowed.
* @param remember Whether this decision should be remembered beyond the
* life of the current page.
*/
private native void nativeGeolocationPermissionsProvide(String origin, boolean allow, boolean remember);
/**
* Provide WebCore with the previously visted links from the history database
*/
private native void nativeProvideVisitedHistory(String[] history);
/**
* Modifies the current selection.
*
* Note: Accessibility support.
*
* @param direction The direction in which to alter the selection.
* @param granularity The granularity of the selection modification.
*
* @return The selection string.
*/
private native String nativeModifySelection(int direction, int granularity);
// EventHub for processing messages
private final EventHub mEventHub;
// WebCore thread handler
private static Handler sWebCoreHandler;
// Class for providing Handler creation inside the WebCore thread.
private static class WebCoreThread implements Runnable {
// Message id for initializing a new WebViewCore.
private static final int INITIALIZE = 0;
private static final int REDUCE_PRIORITY = 1;
private static final int RESUME_PRIORITY = 2;
public void run() {
Looper.prepare();
Assert.assertNull(sWebCoreHandler);
synchronized (WebViewCore.class) {
sWebCoreHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case INITIALIZE:
WebViewCore core = (WebViewCore) msg.obj;
core.initialize();
break;
case REDUCE_PRIORITY:
// 3 is an adjustable number.
Process.setThreadPriority(
Process.THREAD_PRIORITY_DEFAULT + 3 *
Process.THREAD_PRIORITY_LESS_FAVORABLE);
break;
case RESUME_PRIORITY:
Process.setThreadPriority(
Process.THREAD_PRIORITY_DEFAULT);
break;
case EventHub.ADD_PACKAGE_NAME:
if (BrowserFrame.sJavaBridge == null) {
throw new IllegalStateException(
"No WebView has been created in this process!");
}
BrowserFrame.sJavaBridge.addPackageName((String) msg.obj);
break;
case EventHub.REMOVE_PACKAGE_NAME:
if (BrowserFrame.sJavaBridge == null) {
throw new IllegalStateException(
"No WebView has been created in this process!");
}
BrowserFrame.sJavaBridge.removePackageName((String) msg.obj);
break;
case EventHub.PROXY_CHANGED:
if (BrowserFrame.sJavaBridge == null) {
throw new IllegalStateException(
"No WebView has been created in this process!");
}
BrowserFrame.sJavaBridge.updateProxy((ProxyProperties)msg.obj);
break;
}
}
};
WebViewCore.class.notify();
}
Looper.loop();
}
}
static class BaseUrlData {
String mBaseUrl;
String mData;
String mMimeType;
String mEncoding;
String mHistoryUrl;
}
static class CursorData {
CursorData() {}
CursorData(int frame, int node, int x, int y) {
mFrame = frame;
mNode = node;
mX = x;
mY = y;
}
int mMoveGeneration;
int mFrame;
int mNode;
int mX;
int mY;
}
static class JSInterfaceData {
Object mObject;
String mInterfaceName;
}
static class JSKeyData {
String mCurrentText;
KeyEvent mEvent;
}
static class MotionUpData {
int mFrame;
int mNode;
Rect mBounds;
int mX;
int mY;
}
static class GetUrlData {
String mUrl;
Map<String, String> mExtraHeaders;
}
static class PostUrlData {
String mUrl;
byte[] mPostData;
}
static class ReplaceTextData {
String mReplace;
int mNewStart;
int mNewEnd;
int mTextGeneration;
}
static class TextSelectionData {
public TextSelectionData(int start, int end) {
mStart = start;
mEnd = end;
}
int mStart;
int mEnd;
}
static class TouchUpData {
int mMoveGeneration;
int mFrame;
int mNode;
int mX;
int mY;
int mNativeLayer;
Rect mNativeLayerRect = new Rect();
}
static class TouchHighlightData {
int mX;
int mY;
int mSlop;
int mNativeLayer;
Rect mNativeLayerRect;
}
static class AutoFillData {
public AutoFillData() {
mQueryId = WebTextView.FORM_NOT_AUTOFILLABLE;
mPreview = "";
}
public AutoFillData(int queryId, String preview) {
mQueryId = queryId;
mPreview = preview;
}
public int getQueryId() {
return mQueryId;
}
public String getPreviewString() {
return mPreview;
}
private int mQueryId;
private String mPreview;
}
// mAction of TouchEventData can be MotionEvent.getAction() which uses the
// last two bytes or one of the following values
static final int ACTION_LONGPRESS = 0x100;
static final int ACTION_DOUBLETAP = 0x200;
static class TouchEventData {
int mAction;
int[] mIds; // Ids of the touch points
Point[] mPoints;
Point[] mPointsInView; // the point coordinates in view axis.
int mActionIndex; // Associated pointer index for ACTION_POINTER_DOWN/UP
int mMetaState;
boolean mReprocess;
MotionEvent mMotionEvent;
int mNativeLayer;
Rect mNativeLayerRect = new Rect();
long mSequence;
boolean mNativeResult;
}
static class GeolocationPermissionsData {
String mOrigin;
boolean mAllow;
boolean mRemember;
}
static final String[] HandlerDebugString = {
"REVEAL_SELECTION", // 96
"REQUEST_LABEL", // 97
"UPDATE_FRAME_CACHE_IF_LOADING", // = 98
"SCROLL_TEXT_INPUT", // = 99
"LOAD_URL", // = 100;
"STOP_LOADING", // = 101;
"RELOAD", // = 102;
"KEY_DOWN", // = 103;
"KEY_UP", // = 104;
"VIEW_SIZE_CHANGED", // = 105;
"GO_BACK_FORWARD", // = 106;
"SET_SCROLL_OFFSET", // = 107;
"RESTORE_STATE", // = 108;
"PAUSE_TIMERS", // = 109;
"RESUME_TIMERS", // = 110;
"CLEAR_CACHE", // = 111;
"CLEAR_HISTORY", // = 112;
"SET_SELECTION", // = 113;
"REPLACE_TEXT", // = 114;
"PASS_TO_JS", // = 115;
"SET_GLOBAL_BOUNDS", // = 116;
"UPDATE_CACHE_AND_TEXT_ENTRY", // = 117;
"CLICK", // = 118;
"SET_NETWORK_STATE", // = 119;
"DOC_HAS_IMAGES", // = 120;
"FAKE_CLICK", // = 121;
"DELETE_SELECTION", // = 122;
"LISTBOX_CHOICES", // = 123;
"SINGLE_LISTBOX_CHOICE", // = 124;
"MESSAGE_RELAY", // = 125;
"SET_BACKGROUND_COLOR", // = 126;
"SET_MOVE_FOCUS", // = 127
"SAVE_DOCUMENT_STATE", // = 128;
"129", // = 129;
"WEBKIT_DRAW", // = 130;
"131", // = 131;
"POST_URL", // = 132;
"SPLIT_PICTURE_SET", // = 133;
"CLEAR_CONTENT", // = 134;
"SET_MOVE_MOUSE", // = 135;
"SET_MOVE_MOUSE_IF_LATEST", // = 136;
"REQUEST_CURSOR_HREF", // = 137;
"ADD_JS_INTERFACE", // = 138;
"LOAD_DATA", // = 139;
"TOUCH_UP", // = 140;
"TOUCH_EVENT", // = 141;
"SET_ACTIVE", // = 142;
"ON_PAUSE", // = 143
"ON_RESUME", // = 144
"FREE_MEMORY", // = 145
"VALID_NODE_BOUNDS", // = 146
"SAVE_WEBARCHIVE", // = 147
"WEBKIT_DRAW_LAYERS", // = 148;
"REMOVE_JS_INTERFACE", // = 149;
};
/**
* @hide
*/
public class EventHub {
// Message Ids
static final int REVEAL_SELECTION = 96;
static final int REQUEST_LABEL = 97;
static final int UPDATE_FRAME_CACHE_IF_LOADING = 98;
static final int SCROLL_TEXT_INPUT = 99;
static final int LOAD_URL = 100;
static final int STOP_LOADING = 101;
static final int RELOAD = 102;
static final int KEY_DOWN = 103;
static final int KEY_UP = 104;
static final int VIEW_SIZE_CHANGED = 105;
static final int GO_BACK_FORWARD = 106;
static final int SET_SCROLL_OFFSET = 107;
static final int RESTORE_STATE = 108;
static final int PAUSE_TIMERS = 109;
static final int RESUME_TIMERS = 110;
static final int CLEAR_CACHE = 111;
static final int CLEAR_HISTORY = 112;
static final int SET_SELECTION = 113;
static final int REPLACE_TEXT = 114;
static final int PASS_TO_JS = 115;
static final int SET_GLOBAL_BOUNDS = 116;
static final int UPDATE_CACHE_AND_TEXT_ENTRY = 117;
static final int CLICK = 118;
static final int SET_NETWORK_STATE = 119;
static final int DOC_HAS_IMAGES = 120;
static final int FAKE_CLICK = 121;
static final int DELETE_SELECTION = 122;
static final int LISTBOX_CHOICES = 123;
static final int SINGLE_LISTBOX_CHOICE = 124;
public static final int MESSAGE_RELAY = 125;
static final int SET_BACKGROUND_COLOR = 126;
static final int SET_MOVE_FOCUS = 127;
static final int SAVE_DOCUMENT_STATE = 128;
static final int WEBKIT_DRAW = 130;
static final int POST_URL = 132;
static final int SPLIT_PICTURE_SET = 133;
static final int CLEAR_CONTENT = 134;
// UI nav messages
static final int SET_MOVE_MOUSE = 135;
static final int SET_MOVE_MOUSE_IF_LATEST = 136;
static final int REQUEST_CURSOR_HREF = 137;
static final int ADD_JS_INTERFACE = 138;
static final int LOAD_DATA = 139;
// motion
static final int TOUCH_UP = 140;
// message used to pass UI touch events to WebCore
static final int TOUCH_EVENT = 141;
// Used to tell the focus controller not to draw the blinking cursor,
// based on whether the WebView has focus and whether the WebView's
// cursor matches the webpage's focus.
static final int SET_ACTIVE = 142;
// lifecycle activities for just this DOM (unlike pauseTimers, which
// is global)
static final int ON_PAUSE = 143;
static final int ON_RESUME = 144;
static final int FREE_MEMORY = 145;
static final int VALID_NODE_BOUNDS = 146;
// Load and save web archives
static final int SAVE_WEBARCHIVE = 147;
// Update layers
static final int WEBKIT_DRAW_LAYERS = 148;
static final int REMOVE_JS_INTERFACE = 149;
// Network-based messaging
static final int CLEAR_SSL_PREF_TABLE = 150;
// Test harness messages
static final int REQUEST_EXT_REPRESENTATION = 160;
static final int REQUEST_DOC_AS_TEXT = 161;
// debugging
static final int DUMP_DOMTREE = 170;
static final int DUMP_RENDERTREE = 171;
static final int DUMP_NAVTREE = 172;
static final int DUMP_V8COUNTERS = 173;
static final int SET_JS_FLAGS = 174;
static final int CONTENT_INVALIDATE_ALL = 175;
// Geolocation
static final int GEOLOCATION_PERMISSIONS_PROVIDE = 180;
static final int POPULATE_VISITED_LINKS = 181;
static final int HIDE_FULLSCREEN = 182;
static final int SET_NETWORK_TYPE = 183;
// navigator.isApplicationInstalled()
static final int ADD_PACKAGE_NAMES = 184;
static final int ADD_PACKAGE_NAME = 185;
static final int REMOVE_PACKAGE_NAME = 186;
static final int GET_TOUCH_HIGHLIGHT_RECTS = 187;
// accessibility support
static final int MODIFY_SELECTION = 190;
static final int USE_MOCK_DEVICE_ORIENTATION = 191;
static final int AUTOFILL_FORM = 192;
static final int PROXY_CHANGED = 193;
static final int EXECUTE_JS = 194;
// private message ids
private static final int DESTROY = 200;
// Private handler for WebCore messages.
private Handler mHandler;
// Message queue for containing messages before the WebCore thread is
// ready.
private ArrayList<Message> mMessages = new ArrayList<Message>();
// Flag for blocking messages. This is used during DESTROY to avoid
// posting more messages to the EventHub or to WebView's event handler.
private boolean mBlockMessages;
private int mTid;
private int mSavedPriority;
/**
* Prevent other classes from creating an EventHub.
*/
private EventHub() {}
private static final int FIRST_PACKAGE_MSG_ID = REVEAL_SELECTION;
private static final int LAST_PACKAGE_MSG_ID = VALID_NODE_BOUNDS;
/**
* Transfer all messages to the newly created webcore thread handler.
*/
private void transferMessages() {
mTid = Process.myTid();
mSavedPriority = Process.getThreadPriority(mTid);
mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (DebugFlags.WEB_VIEW_CORE) {
Log.v(LOGTAG, (msg.what < FIRST_PACKAGE_MSG_ID
|| msg.what > LAST_PACKAGE_MSG_ID
? Integer.toString(msg.what)
: HandlerDebugString[msg.what
- FIRST_PACKAGE_MSG_ID])
+ " arg1=" + msg.arg1 + " arg2=" + msg.arg2
+ " obj=" + msg.obj);
}
if (mWebView == null
&& msg.what != EventHub.RESUME_TIMERS
&& msg.what != EventHub.PAUSE_TIMERS) {
if (DebugFlags.WEB_VIEW_CORE) {
Log.v(LOGTAG, "Rejecting message " + msg.what
+ " because we are destroyed");
}
return;
}
switch (msg.what) {
case WEBKIT_DRAW:
webkitDraw();
break;
case WEBKIT_DRAW_LAYERS:
webkitDrawLayers();
break;
case DESTROY:
// Time to take down the world. Cancel all pending
// loads and destroy the native view and frame.
synchronized (WebViewCore.this) {
mBrowserFrame.destroy();
mBrowserFrame = null;
mSettings.onDestroyed();
mNativeClass = 0;
mWebView = null;
}
break;
case REVEAL_SELECTION:
nativeRevealSelection();
break;
case REQUEST_LABEL:
if (mWebView != null) {
int nodePointer = msg.arg2;
String label = nativeRequestLabel(msg.arg1,
nodePointer);
if (label != null && label.length() > 0) {
Message.obtain(mWebView.mPrivateHandler,
WebView.RETURN_LABEL, nodePointer,
0, label).sendToTarget();
}
}
break;
case UPDATE_FRAME_CACHE_IF_LOADING:
nativeUpdateFrameCacheIfLoading();
break;
case SCROLL_TEXT_INPUT:
float xPercent;
if (msg.obj == null) {
xPercent = 0f;
} else {
xPercent = ((Float) msg.obj).floatValue();
}
nativeScrollFocusedTextInput(xPercent, msg.arg2);
break;
case LOAD_URL: {
CookieManager.getInstance().waitForCookieOperationsToComplete();
GetUrlData param = (GetUrlData) msg.obj;
loadUrl(param.mUrl, param.mExtraHeaders);
break;
}
case POST_URL: {
CookieManager.getInstance().waitForCookieOperationsToComplete();
PostUrlData param = (PostUrlData) msg.obj;
mBrowserFrame.postUrl(param.mUrl, param.mPostData);
break;
}
case LOAD_DATA:
CookieManager.getInstance().waitForCookieOperationsToComplete();
BaseUrlData loadParams = (BaseUrlData) msg.obj;
String baseUrl = loadParams.mBaseUrl;
if (baseUrl != null) {
int i = baseUrl.indexOf(':');
if (i > 0) {
// In 1.0, WebView.loadDataWithBaseURL() could access local
// asset files using 'file' scheme URLs as long as the data is
// valid. Later versions of WebKit have tightened the
// restriction around when pages can access such local URLs.
// To maintain compatibility with 1.0, we register the scheme of
// the baseUrl to be considered local, as long as it is not
// http(s)/ftp(s)/about/javascript.
String scheme = baseUrl.substring(0, i);
if (!scheme.startsWith("http") &&
!scheme.startsWith("ftp") &&
!scheme.startsWith("about") &&
!scheme.startsWith("javascript")) {
nativeRegisterURLSchemeAsLocal(scheme);
}
}
}
mBrowserFrame.loadData(baseUrl,
loadParams.mData,
loadParams.mMimeType,
loadParams.mEncoding,
loadParams.mHistoryUrl);
nativeContentInvalidateAll();
break;
case STOP_LOADING:
// If the WebCore has committed the load, but not
// finished the first layout yet, we need to set
// first layout done to trigger the interpreted side sync
// up with native side
if (mBrowserFrame.committed()
&& !mBrowserFrame.firstLayoutDone()) {
mBrowserFrame.didFirstLayout();
}
// Do this after syncing up the layout state.
stopLoading();
break;
case RELOAD:
mBrowserFrame.reload(false);
break;
case KEY_DOWN:
key((KeyEvent) msg.obj, true);
break;
case KEY_UP:
key((KeyEvent) msg.obj, false);
break;
case FAKE_CLICK:
nativeClick(msg.arg1, msg.arg2, true);
break;
case CLICK:
nativeClick(msg.arg1, msg.arg2, false);
break;
case VIEW_SIZE_CHANGED: {
viewSizeChanged((WebView.ViewSizeData) msg.obj);
break;
}
case SET_SCROLL_OFFSET:
// note: these are in document coordinates
// (inv-zoom)
Point pt = (Point) msg.obj;
nativeSetScrollOffset(msg.arg1, msg.arg2 == 1,
pt.x, pt.y);
break;
case SET_GLOBAL_BOUNDS:
Rect r = (Rect) msg.obj;
nativeSetGlobalBounds(r.left, r.top, r.width(),
r.height());
break;
case GO_BACK_FORWARD:
// If it is a standard load and the load is not
// committed yet, we interpret BACK as RELOAD
if (!mBrowserFrame.committed() && msg.arg1 == -1 &&
(mBrowserFrame.loadType() ==
BrowserFrame.FRAME_LOADTYPE_STANDARD)) {
mBrowserFrame.reload(true);
} else {
mBrowserFrame.goBackOrForward(msg.arg1);
}
break;
case RESTORE_STATE:
stopLoading();
restoreState(msg.arg1);
break;
case PAUSE_TIMERS:
mSavedPriority = Process.getThreadPriority(mTid);
Process.setThreadPriority(mTid,
Process.THREAD_PRIORITY_BACKGROUND);
pauseTimers();
if (!JniUtil.useChromiumHttpStack()) {
WebViewWorker.getHandler().sendEmptyMessage(
WebViewWorker.MSG_PAUSE_CACHE_TRANSACTION);
}
break;
case RESUME_TIMERS:
Process.setThreadPriority(mTid, mSavedPriority);
resumeTimers();
if (!JniUtil.useChromiumHttpStack()) {
WebViewWorker.getHandler().sendEmptyMessage(
WebViewWorker.MSG_RESUME_CACHE_TRANSACTION);
}
break;
case ON_PAUSE:
nativePause();
break;
case ON_RESUME:
nativeResume();
break;
case FREE_MEMORY:
clearCache(false);
nativeFreeMemory();
break;
case SET_NETWORK_STATE:
if (BrowserFrame.sJavaBridge == null) {
throw new IllegalStateException("No WebView " +
"has been created in this process!");
}
BrowserFrame.sJavaBridge
.setNetworkOnLine(msg.arg1 == 1);
break;
case SET_NETWORK_TYPE:
if (BrowserFrame.sJavaBridge == null) {
throw new IllegalStateException("No WebView " +
"has been created in this process!");
}
Map<String, String> map = (Map<String, String>) msg.obj;
BrowserFrame.sJavaBridge
.setNetworkType(map.get("type"), map.get("subtype"));
break;
case CLEAR_CACHE:
clearCache(msg.arg1 == 1);
break;
case CLEAR_HISTORY:
mCallbackProxy.getBackForwardList().
close(mBrowserFrame.mNativeFrame);
break;
case REPLACE_TEXT:
ReplaceTextData rep = (ReplaceTextData) msg.obj;
nativeReplaceTextfieldText(msg.arg1, msg.arg2,
rep.mReplace, rep.mNewStart, rep.mNewEnd,
rep.mTextGeneration);
break;
case PASS_TO_JS: {
JSKeyData jsData = (JSKeyData) msg.obj;
KeyEvent evt = jsData.mEvent;
int keyCode = evt.getKeyCode();
int keyValue = evt.getUnicodeChar();
int generation = msg.arg1;
passToJs(generation,
jsData.mCurrentText,
keyCode,
keyValue,
evt.isDown(),
evt.isShiftPressed(), evt.isAltPressed(),
evt.isSymPressed());
break;
}
case SAVE_DOCUMENT_STATE: {
CursorData cDat = (CursorData) msg.obj;
nativeSaveDocumentState(cDat.mFrame);
break;
}
case CLEAR_SSL_PREF_TABLE:
Network.getInstance(mContext)
.clearUserSslPrefTable();
break;
case TOUCH_UP:
TouchUpData touchUpData = (TouchUpData) msg.obj;
if (touchUpData.mNativeLayer != 0) {
nativeScrollLayer(touchUpData.mNativeLayer,
touchUpData.mNativeLayerRect);
}
nativeTouchUp(touchUpData.mMoveGeneration,
touchUpData.mFrame, touchUpData.mNode,
touchUpData.mX, touchUpData.mY);
break;
case TOUCH_EVENT: {
TouchEventData ted = (TouchEventData) msg.obj;
final int count = ted.mPoints.length;
int[] xArray = new int[count];
int[] yArray = new int[count];
for (int c = 0; c < count; c++) {
xArray[c] = ted.mPoints[c].x;
yArray[c] = ted.mPoints[c].y;
}
if (ted.mNativeLayer != 0) {
nativeScrollLayer(ted.mNativeLayer,
ted.mNativeLayerRect);
}
ted.mNativeResult = nativeHandleTouchEvent(ted.mAction, ted.mIds,
xArray, yArray, count, ted.mActionIndex, ted.mMetaState);
Message.obtain(
mWebView.mPrivateHandler,
WebView.PREVENT_TOUCH_ID,
ted.mAction,
ted.mNativeResult ? 1 : 0,
ted).sendToTarget();
break;
}
case SET_ACTIVE:
nativeSetFocusControllerActive(msg.arg1 == 1);
break;
case ADD_JS_INTERFACE:
JSInterfaceData jsData = (JSInterfaceData) msg.obj;
mBrowserFrame.addJavascriptInterface(jsData.mObject,
jsData.mInterfaceName);
break;
case REMOVE_JS_INTERFACE:
jsData = (JSInterfaceData) msg.obj;
mBrowserFrame.removeJavascriptInterface(
jsData.mInterfaceName);
break;
case REQUEST_EXT_REPRESENTATION:
mBrowserFrame.externalRepresentation(
(Message) msg.obj);
break;
case REQUEST_DOC_AS_TEXT:
mBrowserFrame.documentAsText((Message) msg.obj);
break;
case SET_MOVE_FOCUS:
CursorData focusData = (CursorData) msg.obj;
nativeMoveFocus(focusData.mFrame, focusData.mNode);
break;
case SET_MOVE_MOUSE:
CursorData cursorData = (CursorData) msg.obj;
nativeMoveMouse(cursorData.mFrame,
cursorData.mX, cursorData.mY);
break;
case SET_MOVE_MOUSE_IF_LATEST:
CursorData cData = (CursorData) msg.obj;
nativeMoveMouseIfLatest(cData.mMoveGeneration,
cData.mFrame,
cData.mX, cData.mY);
if (msg.arg1 == 1) {
nativeStopPaintingCaret();
}
break;
case REQUEST_CURSOR_HREF: {
Message hrefMsg = (Message) msg.obj;
hrefMsg.getData().putString("url",
nativeRetrieveHref(msg.arg1, msg.arg2));
hrefMsg.getData().putString("title",
nativeRetrieveAnchorText(msg.arg1, msg.arg2));
hrefMsg.getData().putString("src",
nativeRetrieveImageSource(msg.arg1, msg.arg2));
hrefMsg.sendToTarget();
break;
}
case UPDATE_CACHE_AND_TEXT_ENTRY:
nativeUpdateFrameCache();
// FIXME: this should provide a minimal rectangle
if (mWebView != null) {
mWebView.postInvalidate();
}
sendUpdateTextEntry();
break;
case DOC_HAS_IMAGES:
Message imageResult = (Message) msg.obj;
imageResult.arg1 =
mBrowserFrame.documentHasImages() ? 1 : 0;
imageResult.sendToTarget();
break;
case DELETE_SELECTION:
TextSelectionData deleteSelectionData
= (TextSelectionData) msg.obj;
nativeDeleteSelection(deleteSelectionData.mStart,
deleteSelectionData.mEnd, msg.arg1);
break;
case SET_SELECTION:
nativeSetSelection(msg.arg1, msg.arg2);
break;
case MODIFY_SELECTION:
String modifiedSelectionString = nativeModifySelection(msg.arg1,
msg.arg2);
mWebView.mPrivateHandler.obtainMessage(WebView.SELECTION_STRING_CHANGED,
modifiedSelectionString).sendToTarget();
break;
case LISTBOX_CHOICES:
SparseBooleanArray choices = (SparseBooleanArray)
msg.obj;
int choicesSize = msg.arg1;
boolean[] choicesArray = new boolean[choicesSize];
for (int c = 0; c < choicesSize; c++) {
choicesArray[c] = choices.get(c);
}
nativeSendListBoxChoices(choicesArray,
choicesSize);
break;
case SINGLE_LISTBOX_CHOICE:
nativeSendListBoxChoice(msg.arg1);
break;
case SET_BACKGROUND_COLOR:
nativeSetBackgroundColor(msg.arg1);
break;
case DUMP_DOMTREE:
nativeDumpDomTree(msg.arg1 == 1);
break;
case DUMP_RENDERTREE:
nativeDumpRenderTree(msg.arg1 == 1);
break;
case DUMP_NAVTREE:
nativeDumpNavTree();
break;
case DUMP_V8COUNTERS:
nativeDumpV8Counters();
break;
case SET_JS_FLAGS:
nativeSetJsFlags((String)msg.obj);
break;
case CONTENT_INVALIDATE_ALL:
nativeContentInvalidateAll();
break;
case SAVE_WEBARCHIVE:
WebView.SaveWebArchiveMessage saveMessage =
(WebView.SaveWebArchiveMessage)msg.obj;
saveMessage.mResultFile =
saveWebArchive(saveMessage.mBasename, saveMessage.mAutoname);
mWebView.mPrivateHandler.obtainMessage(
WebView.SAVE_WEBARCHIVE_FINISHED, saveMessage).sendToTarget();
break;
case GEOLOCATION_PERMISSIONS_PROVIDE:
GeolocationPermissionsData data =
(GeolocationPermissionsData) msg.obj;
nativeGeolocationPermissionsProvide(data.mOrigin,
data.mAllow, data.mRemember);
break;
case SPLIT_PICTURE_SET:
nativeSplitContent(msg.arg1);
mWebView.mPrivateHandler.obtainMessage(
WebView.REPLACE_BASE_CONTENT, msg.arg1, 0);
mSplitPictureIsScheduled = false;
break;
case CLEAR_CONTENT:
// Clear the view so that onDraw() will draw nothing
// but white background
// (See public method WebView.clearView)
nativeClearContent();
break;
case MESSAGE_RELAY:
((Message) msg.obj).sendToTarget();
break;
case POPULATE_VISITED_LINKS:
nativeProvideVisitedHistory((String[])msg.obj);
break;
case VALID_NODE_BOUNDS: {
MotionUpData motionUpData = (MotionUpData) msg.obj;
if (!nativeValidNodeAndBounds(
motionUpData.mFrame, motionUpData.mNode,
motionUpData.mBounds)) {
nativeUpdateFrameCache();
}
Message message = mWebView.mPrivateHandler
.obtainMessage(WebView.DO_MOTION_UP,
motionUpData.mX, motionUpData.mY);
mWebView.mPrivateHandler.sendMessageAtFrontOfQueue(
message);
break;
}
case HIDE_FULLSCREEN:
nativeFullScreenPluginHidden(msg.arg1);
break;
case ADD_PACKAGE_NAMES:
if (BrowserFrame.sJavaBridge == null) {
throw new IllegalStateException("No WebView " +
"has been created in this process!");
}
BrowserFrame.sJavaBridge.addPackageNames(
(Set<String>) msg.obj);
break;
case GET_TOUCH_HIGHLIGHT_RECTS:
TouchHighlightData d = (TouchHighlightData) msg.obj;
if (d.mNativeLayer != 0) {
nativeScrollLayer(d.mNativeLayer,
d.mNativeLayerRect);
}
ArrayList<Rect> rects = nativeGetTouchHighlightRects
(d.mX, d.mY, d.mSlop);
mWebView.mPrivateHandler.obtainMessage(
WebView.SET_TOUCH_HIGHLIGHT_RECTS, rects)
.sendToTarget();
break;
case USE_MOCK_DEVICE_ORIENTATION:
useMockDeviceOrientation();
break;
case AUTOFILL_FORM:
nativeAutoFillForm(msg.arg1);
mWebView.mPrivateHandler.obtainMessage(WebView.AUTOFILL_COMPLETE, null)
.sendToTarget();
break;
case EXECUTE_JS:
if (msg.obj instanceof String) {
if (DebugFlags.WEB_VIEW_CORE) {
Log.d(LOGTAG, "Executing JS : " + msg.obj);
}
mBrowserFrame.stringByEvaluatingJavaScriptFromString((String) msg.obj);
}
break;
}
}
};
// Take all queued messages and resend them to the new handler.
synchronized (this) {
int size = mMessages.size();
for (int i = 0; i < size; i++) {
mHandler.sendMessage(mMessages.get(i));
}
mMessages = null;
}
}
/**
* Send a message internally to the queue or to the handler
*/
private synchronized void sendMessage(Message msg) {
if (mBlockMessages) {
return;
}
if (mMessages != null) {
mMessages.add(msg);
} else {
mHandler.sendMessage(msg);
}
}
private synchronized void removeMessages(int what) {
if (mBlockMessages) {
return;
}
if (what == EventHub.WEBKIT_DRAW) {
mDrawIsScheduled = false;
}
if (mMessages != null) {
Log.w(LOGTAG, "Not supported in this case.");
} else {
mHandler.removeMessages(what);
}
}
private synchronized boolean hasMessages(int what) {
if (mBlockMessages) {
return false;
}
if (mMessages != null) {
Log.w(LOGTAG, "hasMessages() is not supported in this case.");
return false;
} else {
return mHandler.hasMessages(what);
}
}
private synchronized void sendMessageDelayed(Message msg, long delay) {
if (mBlockMessages) {
return;
}
mHandler.sendMessageDelayed(msg, delay);
}
/**
* Send a message internally to the front of the queue.
*/
private synchronized void sendMessageAtFrontOfQueue(Message msg) {
if (mBlockMessages) {
return;
}
if (mMessages != null) {
mMessages.add(0, msg);
} else {
mHandler.sendMessageAtFrontOfQueue(msg);
}
}
/**
* Remove all the messages.
*/
private synchronized void removeMessages() {
// reset mDrawIsScheduled flag as WEBKIT_DRAW may be removed
mDrawIsScheduled = false;
mSplitPictureIsScheduled = false;
if (mMessages != null) {
mMessages.clear();
} else {
mHandler.removeCallbacksAndMessages(null);
}
}
/**
* Block sending messages to the EventHub.
*/
private synchronized void blockMessages() {
mBlockMessages = true;
}
}
//-------------------------------------------------------------------------
// Methods called by host activity (in the same thread)
//-------------------------------------------------------------------------
void stopLoading() {
if (DebugFlags.WEB_VIEW_CORE) Log.v(LOGTAG, "CORE stopLoading");
if (mBrowserFrame != null) {
mBrowserFrame.stopLoading();
}
}
//-------------------------------------------------------------------------
// Methods called by WebView
// If it refers to local variable, it needs synchronized().
// If it needs WebCore, it has to send message.
//-------------------------------------------------------------------------
/**
* @hide
*/
public void sendMessage(Message msg) {
mEventHub.sendMessage(msg);
}
void sendMessage(int what) {
mEventHub.sendMessage(Message.obtain(null, what));
}
void sendMessage(int what, Object obj) {
mEventHub.sendMessage(Message.obtain(null, what, obj));
}
void sendMessage(int what, int arg1) {
// just ignore the second argument (make it 0)
mEventHub.sendMessage(Message.obtain(null, what, arg1, 0));
}
void sendMessage(int what, int arg1, int arg2) {
mEventHub.sendMessage(Message.obtain(null, what, arg1, arg2));
}
void sendMessage(int what, int arg1, Object obj) {
// just ignore the second argument (make it 0)
mEventHub.sendMessage(Message.obtain(null, what, arg1, 0, obj));
}
void sendMessage(int what, int arg1, int arg2, Object obj) {
mEventHub.sendMessage(Message.obtain(null, what, arg1, arg2, obj));
}
void sendMessageAtFrontOfQueue(int what, Object obj) {
mEventHub.sendMessageAtFrontOfQueue(Message.obtain(
null, what, obj));
}
void sendMessageDelayed(int what, Object obj, long delay) {
mEventHub.sendMessageDelayed(Message.obtain(null, what, obj), delay);
}
void removeMessages(int what) {
mEventHub.removeMessages(what);
}
void removeMessages() {
mEventHub.removeMessages();
}
/**
* Sends a DESTROY message to WebCore.
* Called from UI thread.
*/
void destroy() {
synchronized (mEventHub) {
// Do not call removeMessages as then we risk removing PAUSE_TIMERS
// or RESUME_TIMERS messages, which we must still handle as they
// are per process. DESTROY will instead trigger a white list in
// mEventHub, skipping any remaining messages in the queue
mEventHub.sendMessageAtFrontOfQueue(
Message.obtain(null, EventHub.DESTROY));
mEventHub.blockMessages();
}
}
//-------------------------------------------------------------------------
// WebViewCore private methods
//-------------------------------------------------------------------------
private void clearCache(boolean includeDiskFiles) {
mBrowserFrame.clearCache();
if (includeDiskFiles) {
CacheManager.removeAllCacheFiles();
}
}
private void loadUrl(String url, Map<String, String> extraHeaders) {
if (DebugFlags.WEB_VIEW_CORE) Log.v(LOGTAG, " CORE loadUrl " + url);
mBrowserFrame.loadUrl(url, extraHeaders);
}
private String saveWebArchive(String filename, boolean autoname) {
if (DebugFlags.WEB_VIEW_CORE) {
Log.v(LOGTAG, " CORE saveWebArchive " + filename + " " + autoname);
}
return mBrowserFrame.saveWebArchive(filename, autoname);
}
private void key(KeyEvent evt, boolean isDown) {
if (DebugFlags.WEB_VIEW_CORE) {
Log.v(LOGTAG, "CORE key at " + System.currentTimeMillis() + ", "
+ evt);
}
int keyCode = evt.getKeyCode();
int unicodeChar = evt.getUnicodeChar();
if (keyCode == KeyEvent.KEYCODE_UNKNOWN && evt.getCharacters() != null
&& evt.getCharacters().length() > 0) {
// we should only receive individual complex characters
unicodeChar = evt.getCharacters().codePointAt(0);
}
if (!nativeKey(keyCode, unicodeChar, evt.getRepeatCount(), evt.isShiftPressed(),
evt.isAltPressed(), evt.isSymPressed(),
isDown) && keyCode != KeyEvent.KEYCODE_ENTER) {
if (keyCode >= KeyEvent.KEYCODE_DPAD_UP
&& keyCode <= KeyEvent.KEYCODE_DPAD_RIGHT) {
if (DebugFlags.WEB_VIEW_CORE) {
Log.v(LOGTAG, "key: arrow unused by page: " + keyCode);
}
if (mWebView != null && evt.isDown()) {
Message.obtain(mWebView.mPrivateHandler,
WebView.UNHANDLED_NAV_KEY, keyCode,
0).sendToTarget();
}
return;
}
// bubble up the event handling
// but do not bubble up the ENTER key, which would open the search
// bar without any text.
mCallbackProxy.onUnhandledKeyEvent(evt);
}
}
// These values are used to avoid requesting a layout based on old values
private int mCurrentViewWidth = 0;
private int mCurrentViewHeight = 0;
private float mCurrentViewScale = 1.0f;
// notify webkit that our virtual view size changed size (after inv-zoom)
private void viewSizeChanged(WebView.ViewSizeData data) {
int w = data.mWidth;
int h = data.mHeight;
int textwrapWidth = data.mTextWrapWidth;
float scale = data.mScale;
if (DebugFlags.WEB_VIEW_CORE) {
Log.v(LOGTAG, "viewSizeChanged w=" + w + "; h=" + h
+ "; textwrapWidth=" + textwrapWidth + "; scale=" + scale);
}
if (w == 0) {
Log.w(LOGTAG, "skip viewSizeChanged as w is 0");
return;
}
int width = calculateWindowWidth(w);
int height = h;
if (width != w) {
float heightWidthRatio = data.mHeightWidthRatio;
float ratio = (heightWidthRatio > 0) ? heightWidthRatio : (float) h / w;
height = Math.round(ratio * width);
}
nativeSetSize(width, height, textwrapWidth, scale, w,
data.mActualViewHeight > 0 ? data.mActualViewHeight : h,
data.mAnchorX, data.mAnchorY, data.mIgnoreHeight);
// Remember the current width and height
boolean needInvalidate = (mCurrentViewWidth == 0);
mCurrentViewWidth = w;
mCurrentViewHeight = h;
mCurrentViewScale = scale;
if (needInvalidate) {
// ensure {@link #webkitDraw} is called as we were blocking in
// {@link #contentDraw} when mCurrentViewWidth is 0
if (DebugFlags.WEB_VIEW_CORE) Log.v(LOGTAG, "viewSizeChanged");
contentDraw();
}
mEventHub.sendMessage(Message.obtain(null,
EventHub.UPDATE_CACHE_AND_TEXT_ENTRY));
}
// Calculate width to be used in webkit window.
private int calculateWindowWidth(int viewWidth) {
int width = viewWidth;
if (mSettings.getUseWideViewPort()) {
if (mViewportWidth == -1) {
// Fixed viewport width.
width = WebView.DEFAULT_VIEWPORT_WIDTH;
} else if (mViewportWidth > 0) {
// Use website specified or desired fixed viewport width.
width = mViewportWidth;
} else {
// For mobile web site.
width = Math.round(mWebView.getViewWidth() / mWebView.getDefaultZoomScale());
}
}
return width;
}
private void sendUpdateTextEntry() {
if (mWebView != null) {
Message.obtain(mWebView.mPrivateHandler,
WebView.UPDATE_TEXT_ENTRY_MSG_ID).sendToTarget();
}
}
// Utility method for exceededDatabaseQuota and reachedMaxAppCacheSize
// callbacks. Computes the sum of database quota for all origins.
private long getUsedQuota() {
WebStorage webStorage = WebStorage.getInstance();
Collection<WebStorage.Origin> origins = webStorage.getOriginsSync();
if (origins == null) {
return 0;
}
long usedQuota = 0;
for (WebStorage.Origin website : origins) {
usedQuota += website.getQuota();
}
return usedQuota;
}
// called from UI thread
void splitContent(int content) {
if (!mSplitPictureIsScheduled) {
mSplitPictureIsScheduled = true;
sendMessage(EventHub.SPLIT_PICTURE_SET, content, 0);
}
}
// Used to avoid posting more than one draw message.
private boolean mDrawIsScheduled;
private boolean mDrawLayersIsScheduled;
// Used to avoid posting more than one split picture message.
private boolean mSplitPictureIsScheduled;
// Used to suspend drawing.
private boolean mDrawIsPaused;
// mInitialViewState is set by didFirstLayout() and then reset in the
// next webkitDraw after passing the state to the UI thread.
private ViewState mInitialViewState = null;
private boolean mFirstLayoutForNonStandardLoad;
static class ViewState {
float mMinScale;
float mMaxScale;
float mViewScale;
float mTextWrapScale;
float mDefaultScale;
int mScrollX;
int mScrollY;
boolean mMobileSite;
boolean mIsRestored;
}
static class DrawData {
DrawData() {
mBaseLayer = 0;
mInvalRegion = new Region();
mContentSize = new Point();
}
int mBaseLayer;
Region mInvalRegion;
// view size that was used by webkit during the most recent layout
Point mViewSize;
Point mContentSize;
int mMinPrefWidth;
// only non-null if it is for the first picture set after the first layout
ViewState mViewState;
boolean mFirstLayoutForNonStandardLoad;
boolean mFocusSizeChanged;
}
// Only update the layers' content, not the base surface
// PictureSet.
private void webkitDrawLayers() {
mDrawLayersIsScheduled = false;
if (mDrawIsScheduled) {
removeMessages(EventHub.WEBKIT_DRAW);
webkitDraw();
return;
}
DrawData draw = new DrawData();
draw.mBaseLayer = nativeUpdateLayers(draw.mInvalRegion);
webkitDraw(draw);
}
private void webkitDraw() {
mDrawIsScheduled = false;
DrawData draw = new DrawData();
if (DebugFlags.WEB_VIEW_CORE) Log.v(LOGTAG, "webkitDraw start");
draw.mBaseLayer = nativeRecordContent(draw.mInvalRegion, draw.mContentSize);
if (draw.mBaseLayer == 0) {
if (mWebView != null && !mWebView.isPaused()) {
if (DebugFlags.WEB_VIEW_CORE) Log.v(LOGTAG, "webkitDraw abort, resending draw message");
mEventHub.sendMessage(Message.obtain(null, EventHub.WEBKIT_DRAW));
} else {
if (DebugFlags.WEB_VIEW_CORE) Log.v(LOGTAG, "webkitDraw abort, webview paused");
}
return;
}
webkitDraw(draw);
}
private void webkitDraw(DrawData draw) {
if (mWebView != null) {
draw.mFocusSizeChanged = nativeFocusBoundsChanged();
draw.mViewSize = new Point(mCurrentViewWidth, mCurrentViewHeight);
if (mSettings.getUseWideViewPort()) {
draw.mMinPrefWidth = Math.max(
mViewportWidth == -1 ? WebView.DEFAULT_VIEWPORT_WIDTH
: (mViewportWidth == 0 ? mCurrentViewWidth
: mViewportWidth),
nativeGetContentMinPrefWidth());
}
if (mInitialViewState != null) {
draw.mViewState = mInitialViewState;
mInitialViewState = null;
}
if (mFirstLayoutForNonStandardLoad) {
draw.mFirstLayoutForNonStandardLoad = true;
mFirstLayoutForNonStandardLoad = false;
}
if (DebugFlags.WEB_VIEW_CORE) Log.v(LOGTAG, "webkitDraw NEW_PICTURE_MSG_ID");
Message.obtain(mWebView.mPrivateHandler,
WebView.NEW_PICTURE_MSG_ID, draw).sendToTarget();
}
}
static void reducePriority() {
// remove the pending REDUCE_PRIORITY and RESUME_PRIORITY messages
sWebCoreHandler.removeMessages(WebCoreThread.REDUCE_PRIORITY);
sWebCoreHandler.removeMessages(WebCoreThread.RESUME_PRIORITY);
sWebCoreHandler.sendMessageAtFrontOfQueue(sWebCoreHandler
.obtainMessage(WebCoreThread.REDUCE_PRIORITY));
}
static void resumePriority() {
// remove the pending REDUCE_PRIORITY and RESUME_PRIORITY messages
sWebCoreHandler.removeMessages(WebCoreThread.REDUCE_PRIORITY);
sWebCoreHandler.removeMessages(WebCoreThread.RESUME_PRIORITY);
sWebCoreHandler.sendMessageAtFrontOfQueue(sWebCoreHandler
.obtainMessage(WebCoreThread.RESUME_PRIORITY));
}
static void sendStaticMessage(int messageType, Object argument) {
if (sWebCoreHandler == null)
return;
sWebCoreHandler.sendMessage(sWebCoreHandler.obtainMessage(messageType, argument));
}
static void pauseUpdatePicture(WebViewCore core) {
// Note: there is one possible failure mode. If pauseUpdatePicture() is
// called from UI thread while WEBKIT_DRAW is just pulled out of the
// queue in WebCore thread to be executed. Then update won't be blocked.
if (core != null) {
if (!core.getSettings().enableSmoothTransition()) return;
synchronized (core) {
core.nativeSetIsPaused(true);
core.mDrawIsPaused = true;
}
}
}
static void resumeUpdatePicture(WebViewCore core) {
if (core != null) {
// if mDrawIsPaused is true, ignore the setting, continue to resume
if (!core.mDrawIsPaused)
return;
synchronized (core) {
core.nativeSetIsPaused(false);
core.mDrawIsPaused = false;
// always redraw on resume to reenable gif animations
core.mDrawIsScheduled = false;
}
}
}
//////////////////////////////////////////////////////////////////////////
private void restoreState(int index) {
WebBackForwardList list = mCallbackProxy.getBackForwardList();
int size = list.getSize();
for (int i = 0; i < size; i++) {
list.getItemAtIndex(i).inflate(mBrowserFrame.mNativeFrame);
}
mBrowserFrame.mLoadInitFromJava = true;
list.restoreIndex(mBrowserFrame.mNativeFrame, index);
mBrowserFrame.mLoadInitFromJava = false;
}
//-------------------------------------------------------------------------
// Implement abstract methods in WebViewCore, native WebKit callback part
//-------------------------------------------------------------------------
// called from JNI or WebView thread
/* package */ void contentDraw() {
synchronized (this) {
if (mWebView == null || mBrowserFrame == null) {
// We were destroyed
return;
}
// don't update the Picture until we have an initial width and finish
// the first layout
if (mCurrentViewWidth == 0 || !mBrowserFrame.firstLayoutDone()) {
return;
}
// only fire an event if this is our first request
if (mDrawIsScheduled) return;
mDrawIsScheduled = true;
mEventHub.sendMessage(Message.obtain(null, EventHub.WEBKIT_DRAW));
}
}
// called from JNI
void layersDraw() {
synchronized (this) {
if (mDrawLayersIsScheduled) return;
mDrawLayersIsScheduled = true;
mEventHub.sendMessage(Message.obtain(null, EventHub.WEBKIT_DRAW_LAYERS));
}
}
// called by JNI
private void contentScrollTo(int x, int y, boolean animate,
boolean onlyIfImeIsShowing) {
if (!mBrowserFrame.firstLayoutDone()) {
/*
* WebKit restore state will be called before didFirstLayout(),
* remember the position as it has to be applied after restoring
* zoom factor which is controlled by screenWidth.
*/
mRestoredX = x;
mRestoredY = y;
return;
}
if (mWebView != null) {
Message msg = Message.obtain(mWebView.mPrivateHandler,
WebView.SCROLL_TO_MSG_ID, animate ? 1 : 0,
onlyIfImeIsShowing ? 1 : 0, new Point(x, y));
if (mDrawIsScheduled) {
mEventHub.sendMessage(Message.obtain(null,
EventHub.MESSAGE_RELAY, msg));
} else {
msg.sendToTarget();
}
}
}
// called by JNI
private void sendNotifyProgressFinished() {
sendUpdateTextEntry();
if (!JniUtil.useChromiumHttpStack()) {
// as CacheManager can behave based on database transaction, we need to
// call tick() to trigger endTransaction
WebViewWorker.getHandler().removeMessages(
WebViewWorker.MSG_CACHE_TRANSACTION_TICKER);
WebViewWorker.getHandler().sendEmptyMessage(
WebViewWorker.MSG_CACHE_TRANSACTION_TICKER);
}
contentDraw();
}
/* Called by JNI. The coordinates are in doc coordinates, so they need to
be scaled before they can be used by the view system, which happens
in WebView since it (and its thread) know the current scale factor.
*/
private void sendViewInvalidate(int left, int top, int right, int bottom) {
if (mWebView != null) {
Message.obtain(mWebView.mPrivateHandler,
WebView.INVAL_RECT_MSG_ID,
new Rect(left, top, right, bottom)).sendToTarget();
}
}
private static boolean mRepaintScheduled = false;
/*
* Called by the WebView thread
*/
/* package */ void signalRepaintDone() {
mRepaintScheduled = false;
}
/* package */ WebView getWebView() {
return mWebView;
}
private native void setViewportSettingsFromNative();
// called by JNI
private void didFirstLayout(boolean standardLoad) {
if (DebugFlags.WEB_VIEW_CORE) {
Log.v(LOGTAG, "didFirstLayout standardLoad =" + standardLoad);
}
mBrowserFrame.didFirstLayout();
if (mWebView == null) return;
boolean updateViewState = standardLoad || mRestoredScale > 0;
setupViewport(updateViewState);
// if updateRestoreState is true, ViewManager.postReadyToDrawAll() will
// be called after the WebView updates its state. If updateRestoreState
// is false, start to draw now as it is ready.
if (!updateViewState) {
mWebView.mViewManager.postReadyToDrawAll();
}
// remove the touch highlight when moving to a new page
if (WebView.USE_WEBKIT_RINGS || getSettings().supportTouchOnly()) {
mWebView.mPrivateHandler.sendEmptyMessage(
WebView.SET_TOUCH_HIGHLIGHT_RECTS);
}
// reset the scroll position, the restored offset and scales
mRestoredX = mRestoredY = 0;
mRestoredScale = mRestoredTextWrapScale = 0;
}
// called by JNI
private void updateViewport() {
// Update viewport asap to make sure we get correct one.
setupViewport(true);
}
private void setupViewport(boolean updateViewState) {
if (mWebView == null || mSettings == null) {
// We've been destroyed or are being destroyed, return early
return;
}
// set the viewport settings from WebKit
setViewportSettingsFromNative();
if (mSettings.forceUserScalable()) {
mViewportUserScalable = true;
if (mViewportInitialScale > 0) {
if (mViewportMinimumScale > 0) {
mViewportMinimumScale = Math.min(mViewportMinimumScale,
mViewportInitialScale / 2);
}
if (mViewportMaximumScale > 0) {
mViewportMaximumScale = Math.max(mViewportMaximumScale,
mViewportInitialScale * 2);
}
} else {
if (mViewportMinimumScale > 0) {
mViewportMinimumScale = Math.min(mViewportMinimumScale, 50);
}
if (mViewportMaximumScale > 0) {
mViewportMaximumScale = Math.max(mViewportMaximumScale, 200);
}
}
}
// adjust the default scale to match the densityDpi
float adjust = 1.0f;
if (mViewportDensityDpi == -1) {
// convert default zoom scale to a integer (percentage) to avoid any
// issues with floating point comparisons
if (mWebView != null && (int)(mWebView.getDefaultZoomScale() * 100) != 100) {
adjust = mWebView.getDefaultZoomScale();
}
} else if (mViewportDensityDpi > 0) {
adjust = (float) mContext.getResources().getDisplayMetrics().densityDpi
/ mViewportDensityDpi;
}
int defaultScale = (int) (adjust * 100);
if (mViewportInitialScale > 0) {
mViewportInitialScale *= adjust;
}
if (mViewportMinimumScale > 0) {
mViewportMinimumScale *= adjust;
}
if (mViewportMaximumScale > 0) {
mViewportMaximumScale *= adjust;
}
// infer the values if they are not defined.
if (mViewportWidth == 0) {
if (mViewportInitialScale == 0) {
mViewportInitialScale = defaultScale;
}
}
if (mViewportUserScalable == false) {
mViewportInitialScale = defaultScale;
mViewportMinimumScale = defaultScale;
mViewportMaximumScale = defaultScale;
}
if (mViewportMinimumScale > mViewportInitialScale
&& mViewportInitialScale != 0) {
mViewportMinimumScale = mViewportInitialScale;
}
if (mViewportMaximumScale > 0
&& mViewportMaximumScale < mViewportInitialScale) {
mViewportMaximumScale = mViewportInitialScale;
}
if (mViewportWidth < 0 && mViewportInitialScale == defaultScale) {
mViewportWidth = 0;
}
// if mViewportWidth is 0, it means device-width, always update.
if (mViewportWidth != 0 && !updateViewState) {
// For non standard load, since updateViewState will be false.
mFirstLayoutForNonStandardLoad = true;
ViewState viewState = new ViewState();
viewState.mMinScale = mViewportMinimumScale / 100.0f;
viewState.mMaxScale = mViewportMaximumScale / 100.0f;
viewState.mDefaultScale = adjust;
// as mViewportWidth is not 0, it is not mobile site.
viewState.mMobileSite = false;
// for non-mobile site, we don't need minPrefWidth, set it as 0
viewState.mScrollX = 0;
Message.obtain(mWebView.mPrivateHandler,
WebView.UPDATE_ZOOM_RANGE, viewState).sendToTarget();
return;
}
// now notify webview
// webViewWidth refers to the width in the view system
int webViewWidth;
// viewportWidth refers to the width in the document system
int viewportWidth = mCurrentViewWidth;
if (viewportWidth == 0) {
// this may happen when WebView just starts. This is not perfect as
// we call WebView method from WebCore thread. But not perfect
// reference is better than no reference.
webViewWidth = mWebView.getViewWidth();
viewportWidth = (int) (webViewWidth / adjust);
if (viewportWidth == 0) {
if (DebugFlags.WEB_VIEW_CORE) {
Log.v(LOGTAG, "Can't get the viewWidth yet");
}
}
} else {
webViewWidth = Math.round(viewportWidth * mCurrentViewScale);
}
mInitialViewState = new ViewState();
mInitialViewState.mMinScale = mViewportMinimumScale / 100.0f;
mInitialViewState.mMaxScale = mViewportMaximumScale / 100.0f;
mInitialViewState.mDefaultScale = adjust;
mInitialViewState.mScrollX = mRestoredX;
mInitialViewState.mScrollY = mRestoredY;
mInitialViewState.mMobileSite = (0 == mViewportWidth);
if (mRestoredScale > 0) {
mInitialViewState.mIsRestored = true;
mInitialViewState.mViewScale = mRestoredScale;
if (mRestoredTextWrapScale > 0) {
mInitialViewState.mTextWrapScale = mRestoredTextWrapScale;
} else {
mInitialViewState.mTextWrapScale = mInitialViewState.mViewScale;
}
} else {
if (mViewportInitialScale > 0) {
mInitialViewState.mViewScale = mInitialViewState.mTextWrapScale =
mViewportInitialScale / 100.0f;
} else if (mViewportWidth > 0 && mViewportWidth < webViewWidth &&
!getSettings().getUseFixedViewport()) {
mInitialViewState.mViewScale = mInitialViewState.mTextWrapScale =
(float) webViewWidth / mViewportWidth;
} else {
mInitialViewState.mTextWrapScale = adjust;
if (mSettings.getUseWideViewPort()) {
// 0 will trigger WebView to turn on zoom overview mode
mInitialViewState.mViewScale = 0;
} else {
mInitialViewState.mViewScale = adjust;
}
}
}
if (mWebView.mHeightCanMeasure) {
// Trick to ensure that the Picture has the exact height for the
// content by forcing to layout with 0 height after the page is
// ready, which is indicated by didFirstLayout. This is essential to
// get rid of the white space in the GMail which uses WebView for
// message view.
mWebView.mLastHeightSent = 0;
// Send a negative scale to indicate that WebCore should reuse
// the current scale
WebView.ViewSizeData data = new WebView.ViewSizeData();
data.mWidth = mWebView.mLastWidthSent;
data.mHeight = 0;
// if mHeightCanMeasure is true, getUseWideViewPort() can't be
// true. It is safe to use mWidth for mTextWrapWidth.
data.mTextWrapWidth = data.mWidth;
data.mScale = -1.0f;
data.mIgnoreHeight = false;
data.mAnchorX = data.mAnchorY = 0;
// send VIEW_SIZE_CHANGED to the front of the queue so that we can
// avoid pushing the wrong picture to the WebView side. If there is
// a VIEW_SIZE_CHANGED in the queue, probably from WebView side,
// ignore it as we have a new size. If we leave VIEW_SIZE_CHANGED
// in the queue, as mLastHeightSent has been updated here, we may
// miss the requestLayout in WebView side after the new picture.
mEventHub.removeMessages(EventHub.VIEW_SIZE_CHANGED);
mEventHub.sendMessageAtFrontOfQueue(Message.obtain(null,
EventHub.VIEW_SIZE_CHANGED, data));
} else {
if (viewportWidth == 0) {
// Trick to ensure VIEW_SIZE_CHANGED will be sent from WebView
// to WebViewCore
mWebView.mLastWidthSent = 0;
} else {
WebView.ViewSizeData data = new WebView.ViewSizeData();
// mViewScale as 0 means it is in zoom overview mode. So we don't
// know the exact scale. If mRestoredScale is non-zero, use it;
// otherwise just use mTextWrapScale as the initial scale.
float tentativeScale = mInitialViewState.mViewScale;
if (tentativeScale == 0) {
// The following tries to figure out more correct view scale
// and text wrap scale to be sent to webkit, by using some
// knowledge from web settings and zoom manager.
// Calculated window width will be used to guess the scale
// in zoom overview mode.
tentativeScale = mInitialViewState.mTextWrapScale;
int tentativeViewWidth = Math.round(webViewWidth / tentativeScale);
int windowWidth = calculateWindowWidth(tentativeViewWidth);
// In viewport setup time, since no content width is known, we assume
// the windowWidth will be the content width, to get a more likely
// zoom overview scale.
data.mScale = (float) webViewWidth / windowWidth;
if (!mSettings.getLoadWithOverviewMode()) {
// If user choose non-overview mode.
data.mScale = Math.max(data.mScale, tentativeScale);
}
if (mSettings.isNarrowColumnLayout()) {
// In case of automatic text reflow in fixed view port mode.
mInitialViewState.mTextWrapScale =
ZoomManager.computeReadingLevelScale(data.mScale);
}
} else {
// Scale is given such as when page is restored, use it.
data.mScale = tentativeScale;
}
if (DebugFlags.WEB_VIEW_CORE) {
Log.v(LOGTAG, "setupViewport"
+ " mRestoredScale=" + mRestoredScale
+ " mViewScale=" + mInitialViewState.mViewScale
+ " mTextWrapScale=" + mInitialViewState.mTextWrapScale
+ " data.mScale= " + data.mScale
);
}
data.mWidth = Math.round(webViewWidth / data.mScale);
// We may get a call here when mCurrentViewHeight == 0 if webcore completes the
// first layout before we sync our webview dimensions to it. In that case, we
// request the real height of the webview. This is not a perfect solution as we
// are calling a WebView method from the WebCore thread. But this is preferable
// to syncing an incorrect height.
data.mHeight = mCurrentViewHeight == 0 ?
Math.round(mWebView.getViewHeight() / data.mScale)
: Math.round((float) mCurrentViewHeight * data.mWidth / viewportWidth);
data.mTextWrapWidth = Math.round(webViewWidth
/ mInitialViewState.mTextWrapScale);
data.mIgnoreHeight = false;
data.mAnchorX = data.mAnchorY = 0;
// send VIEW_SIZE_CHANGED to the front of the queue so that we
// can avoid pushing the wrong picture to the WebView side.
mEventHub.removeMessages(EventHub.VIEW_SIZE_CHANGED);
// Let webkit know the scale and inner width/height immediately
// in viewport setup time to avoid wrong information.
viewSizeChanged(data);
}
}
}
// called by JNI
private void restoreScale(float scale, float textWrapScale) {
if (mBrowserFrame.firstLayoutDone() == false) {
final float defaultScale = mWebView.getDefaultZoomScale();
mRestoredScale = (scale <= 0.0) ? defaultScale : scale;
if (mSettings.getUseWideViewPort()) {
mRestoredTextWrapScale = (textWrapScale <= 0.0) ? defaultScale : textWrapScale;
}
}
}
// called by JNI
private void needTouchEvents(boolean need) {
if (mWebView != null) {
Message.obtain(mWebView.mPrivateHandler,
WebView.WEBCORE_NEED_TOUCH_EVENTS, need ? 1 : 0, 0)
.sendToTarget();
}
}
// called by JNI
private void updateTextfield(int ptr, boolean changeToPassword,
String text, int textGeneration) {
if (mWebView != null) {
Message msg = Message.obtain(mWebView.mPrivateHandler,
WebView.UPDATE_TEXTFIELD_TEXT_MSG_ID, ptr,
textGeneration, text);
msg.getData().putBoolean("password", changeToPassword);
msg.sendToTarget();
}
}
// called by JNI
private void updateTextSelection(int pointer, int start, int end,
int textGeneration) {
if (mWebView != null) {
Message.obtain(mWebView.mPrivateHandler,
WebView.UPDATE_TEXT_SELECTION_MSG_ID, pointer, textGeneration,
new TextSelectionData(start, end)).sendToTarget();
}
}
// called by JNI
private void clearTextEntry() {
if (mWebView == null) return;
Message.obtain(mWebView.mPrivateHandler,
WebView.CLEAR_TEXT_ENTRY).sendToTarget();
}
// called by JNI
private void sendFindAgain() {
if (mWebView == null) return;
Message.obtain(mWebView.mPrivateHandler,
WebView.FIND_AGAIN).sendToTarget();
}
private native void nativeUpdateFrameCacheIfLoading();
private native void nativeRevealSelection();
private native String nativeRequestLabel(int framePtr, int nodePtr);
/**
* Scroll the focused textfield to (xPercent, y) in document space
*/
private native void nativeScrollFocusedTextInput(float xPercent, int y);
// these must be in document space (i.e. not scaled/zoomed).
private native void nativeSetScrollOffset(int gen, boolean sendScrollEvent, int dx, int dy);
private native void nativeSetGlobalBounds(int x, int y, int w, int h);
// called by JNI
private void requestListBox(String[] array, int[] enabledArray,
int[] selectedArray) {
if (mWebView != null) {
mWebView.requestListBox(array, enabledArray, selectedArray);
}
}
// called by JNI
private void requestListBox(String[] array, int[] enabledArray,
int selection) {
if (mWebView != null) {
mWebView.requestListBox(array, enabledArray, selection);
}
}
// called by JNI
private void requestKeyboardWithSelection(int pointer, int selStart,
int selEnd, int textGeneration) {
if (mWebView != null) {
Message.obtain(mWebView.mPrivateHandler,
WebView.REQUEST_KEYBOARD_WITH_SELECTION_MSG_ID, pointer,
textGeneration, new TextSelectionData(selStart, selEnd))
.sendToTarget();
}
}
// called by JNI
private void requestKeyboard(boolean showKeyboard) {
if (mWebView != null) {
Message.obtain(mWebView.mPrivateHandler,
WebView.REQUEST_KEYBOARD, showKeyboard ? 1 : 0, 0)
.sendToTarget();
}
}
private void setWebTextViewAutoFillable(int queryId, String preview) {
if (mWebView != null) {
Message.obtain(mWebView.mPrivateHandler, WebView.SET_AUTOFILLABLE,
new AutoFillData(queryId, preview))
.sendToTarget();
}
}
// called by JNI
private Context getContext() {
return mContext;
}
// called by JNI
private void keepScreenOn(boolean screenOn) {
if (mWebView != null) {
Message message = mWebView.mPrivateHandler.obtainMessage(WebView.SCREEN_ON);
message.arg1 = screenOn ? 1 : 0;
message.sendToTarget();
}
}
// called by JNI
private Class<?> getPluginClass(String libName, String clsName) {
if (mWebView == null) {
return null;
}
PluginManager pluginManager = PluginManager.getInstance(null);
String pkgName = pluginManager.getPluginsAPKName(libName);
if (pkgName == null) {
Log.w(LOGTAG, "Unable to resolve " + libName + " to a plugin APK");
return null;
}
try {
return pluginManager.getPluginClass(pkgName, clsName);
} catch (NameNotFoundException e) {
Log.e(LOGTAG, "Unable to find plugin classloader for the apk (" + pkgName + ")");
} catch (ClassNotFoundException e) {
Log.e(LOGTAG, "Unable to find plugin class (" + clsName +
") in the apk (" + pkgName + ")");
}
return null;
}
// called by JNI. PluginWidget function to launch a full-screen view using a
// View object provided by the plugin class.
private void showFullScreenPlugin(ViewManager.ChildView childView, int orientation, int npp) {
if (mWebView == null) {
return;
}
Message message = mWebView.mPrivateHandler.obtainMessage(WebView.SHOW_FULLSCREEN);
message.obj = childView.mView;
message.arg1 = orientation;
message.arg2 = npp;
message.sendToTarget();
}
// called by JNI
private void hideFullScreenPlugin() {
if (mWebView == null) {
return;
}
mWebView.mPrivateHandler.obtainMessage(WebView.HIDE_FULLSCREEN)
.sendToTarget();
}
private ViewManager.ChildView createSurface(View pluginView) {
if (mWebView == null) {
return null;
}
if (pluginView == null) {
Log.e(LOGTAG, "Attempted to add an empty plugin view to the view hierarchy");
return null;
}
// ensures the view system knows the view can redraw itself
pluginView.setWillNotDraw(false);
if(pluginView instanceof SurfaceView)
((SurfaceView)pluginView).setZOrderOnTop(true);
ViewManager.ChildView view = mWebView.mViewManager.createView();
view.mView = pluginView;
return view;
}
// called by JNI. PluginWidget functions for creating an embedded View for
// the surface drawing model.
private ViewManager.ChildView addSurface(View pluginView, int x, int y,
int width, int height) {
ViewManager.ChildView view = createSurface(pluginView);
view.attachView(x, y, width, height);
return view;
}
private void updateSurface(ViewManager.ChildView childView, int x, int y,
int width, int height) {
childView.attachView(x, y, width, height);
}
private void destroySurface(ViewManager.ChildView childView) {
childView.removeView();
}
// called by JNI
static class ShowRectData {
int mLeft;
int mTop;
int mWidth;
int mHeight;
int mContentWidth;
int mContentHeight;
float mXPercentInDoc;
float mXPercentInView;
float mYPercentInDoc;
float mYPercentInView;
}
private void showRect(int left, int top, int width, int height,
int contentWidth, int contentHeight, float xPercentInDoc,
float xPercentInView, float yPercentInDoc, float yPercentInView) {
if (mWebView != null) {
ShowRectData data = new ShowRectData();
data.mLeft = left;
data.mTop = top;
data.mWidth = width;
data.mHeight = height;
data.mContentWidth = contentWidth;
data.mContentHeight = contentHeight;
data.mXPercentInDoc = xPercentInDoc;
data.mXPercentInView = xPercentInView;
data.mYPercentInDoc = yPercentInDoc;
data.mYPercentInView = yPercentInView;
Message.obtain(mWebView.mPrivateHandler, WebView.SHOW_RECT_MSG_ID,
data).sendToTarget();
}
}
// called by JNI
private void centerFitRect(int x, int y, int width, int height) {
if (mWebView == null) {
return;
}
mWebView.mPrivateHandler.obtainMessage(WebView.CENTER_FIT_RECT,
new Rect(x, y, x + width, y + height)).sendToTarget();
}
// called by JNI
private void setScrollbarModes(int hMode, int vMode) {
if (mWebView == null) {
return;
}
mWebView.mPrivateHandler.obtainMessage(WebView.SET_SCROLLBAR_MODES,
hMode, vMode).sendToTarget();
}
// called by JNI
@SuppressWarnings("unused")
private void selectAt(int x, int y) {
if (mWebView != null) {
mWebView.mPrivateHandler.obtainMessage(WebView.SELECT_AT, x, y).sendToTarget();
}
}
private void useMockDeviceOrientation() {
mDeviceMotionAndOrientationManager.useMock();
}
public void setMockDeviceOrientation(boolean canProvideAlpha, double alpha,
boolean canProvideBeta, double beta, boolean canProvideGamma, double gamma) {
mDeviceMotionAndOrientationManager.setMockOrientation(canProvideAlpha, alpha,
canProvideBeta, beta, canProvideGamma, gamma);
}
protected DeviceMotionService getDeviceMotionService() {
if (mDeviceMotionService == null) {
mDeviceMotionService =
new DeviceMotionService(mDeviceMotionAndOrientationManager, mContext);
}
return mDeviceMotionService;
}
protected DeviceOrientationService getDeviceOrientationService() {
if (mDeviceOrientationService == null) {
mDeviceOrientationService =
new DeviceOrientationService(mDeviceMotionAndOrientationManager, mContext);
}
return mDeviceOrientationService;
}
private native void nativeSetIsPaused(boolean isPaused);
private native void nativePause();
private native void nativeResume();
private native void nativeFreeMemory();
private native void nativeFullScreenPluginHidden(int npp);
private native boolean nativeValidNodeAndBounds(int frame, int node,
Rect bounds);
private native ArrayList<Rect> nativeGetTouchHighlightRects(int x, int y,
int slop);
private native void nativeAutoFillForm(int queryId);
private native void nativeScrollLayer(int layer, Rect rect);
}
|