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
|
/*
* 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.widget;
import android.annotation.AttrRes;
import android.annotation.ColorInt;
import android.annotation.ColorRes;
import android.annotation.DimenRes;
import android.annotation.DrawableRes;
import android.annotation.IdRes;
import android.annotation.IntDef;
import android.annotation.LayoutRes;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.Px;
import android.annotation.StringRes;
import android.annotation.StyleRes;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityOptions;
import android.app.ActivityThread;
import android.app.Application;
import android.app.LoadedApk;
import android.app.PendingIntent;
import android.app.RemoteInput;
import android.appwidget.AppWidgetHostView;
import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.IntentSender;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.ColorStateList;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.content.res.loader.ResourcesLoader;
import android.content.res.loader.ResourcesProvider;
import android.graphics.Bitmap;
import android.graphics.BlendMode;
import android.graphics.Outline;
import android.graphics.PorterDuff;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.Icon;
import android.graphics.drawable.RippleDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Binder;
import android.os.Build;
import android.os.Bundle;
import android.os.CancellationSignal;
import android.os.Parcel;
import android.os.ParcelFileDescriptor;
import android.os.Parcelable;
import android.os.Process;
import android.os.StrictMode;
import android.os.UserHandle;
import android.system.Os;
import android.text.TextUtils;
import android.util.ArrayMap;
import android.util.DisplayMetrics;
import android.util.IntArray;
import android.util.Log;
import android.util.LongArray;
import android.util.Pair;
import android.util.SizeF;
import android.util.SparseIntArray;
import android.util.TypedValue;
import android.util.TypedValue.ComplexDimensionUnit;
import android.view.ContextThemeWrapper;
import android.view.LayoutInflater;
import android.view.LayoutInflater.Filter;
import android.view.RemotableViewMethod;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.MarginLayoutParams;
import android.view.ViewManager;
import android.view.ViewOutlineProvider;
import android.view.ViewParent;
import android.view.ViewStub;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CompoundButton.OnCheckedChangeListener;
import com.android.internal.R;
import com.android.internal.util.ContrastColorUtil;
import com.android.internal.util.Preconditions;
import java.io.ByteArrayOutputStream;
import java.io.FileDescriptor;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.reflect.Method;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Stack;
import java.util.concurrent.Executor;
import java.util.function.Consumer;
import java.util.function.Predicate;
/**
* A class that describes a view hierarchy that can be displayed in
* another process. The hierarchy is inflated from a layout resource
* file, and this class provides some basic operations for modifying
* the content of the inflated hierarchy.
*
* <p>{@code RemoteViews} is limited to support for the following layouts:</p>
* <ul>
* <li>{@link android.widget.AdapterViewFlipper}</li>
* <li>{@link android.widget.FrameLayout}</li>
* <li>{@link android.widget.GridLayout}</li>
* <li>{@link android.widget.GridView}</li>
* <li>{@link android.widget.LinearLayout}</li>
* <li>{@link android.widget.ListView}</li>
* <li>{@link android.widget.RelativeLayout}</li>
* <li>{@link android.widget.StackView}</li>
* <li>{@link android.widget.ViewFlipper}</li>
* </ul>
* <p>And the following widgets:</p>
* <ul>
* <li>{@link android.widget.AnalogClock}</li>
* <li>{@link android.widget.Button}</li>
* <li>{@link android.widget.Chronometer}</li>
* <li>{@link android.widget.ImageButton}</li>
* <li>{@link android.widget.ImageView}</li>
* <li>{@link android.widget.ProgressBar}</li>
* <li>{@link android.widget.TextClock}</li>
* <li>{@link android.widget.TextView}</li>
* </ul>
* <p>As of API 31, the following widgets and layouts may also be used:</p>
* <ul>
* <li>{@link android.widget.CheckBox}</li>
* <li>{@link android.widget.RadioButton}</li>
* <li>{@link android.widget.RadioGroup}</li>
* <li>{@link android.widget.Switch}</li>
* </ul>
* <p>Descendants of these classes are not supported.</p>
*/
public class RemoteViews implements Parcelable, Filter {
private static final String LOG_TAG = "RemoteViews";
/** The intent extra for whether the view whose checked state changed is currently checked. */
public static final String EXTRA_CHECKED = "android.widget.extra.CHECKED";
/**
* The intent extra that contains the appWidgetId.
* @hide
*/
static final String EXTRA_REMOTEADAPTER_APPWIDGET_ID = "remoteAdapterAppWidgetId";
/**
* The intent extra that contains {@code true} if inflating as dak text theme.
* @hide
*/
static final String EXTRA_REMOTEADAPTER_ON_LIGHT_BACKGROUND = "remoteAdapterOnLightBackground";
/**
* The intent extra that contains the bounds for all shared elements.
*/
public static final String EXTRA_SHARED_ELEMENT_BOUNDS =
"android.widget.extra.SHARED_ELEMENT_BOUNDS";
/**
* Maximum depth of nested views calls from {@link #addView(int, RemoteViews)} and
* {@link #RemoteViews(RemoteViews, RemoteViews)}.
*/
private static final int MAX_NESTED_VIEWS = 10;
/**
* Maximum number of RemoteViews that can be specified in constructor.
*/
private static final int MAX_INIT_VIEW_COUNT = 16;
// The unique identifiers for each custom {@link Action}.
private static final int SET_ON_CLICK_RESPONSE_TAG = 1;
private static final int REFLECTION_ACTION_TAG = 2;
private static final int SET_DRAWABLE_TINT_TAG = 3;
private static final int VIEW_GROUP_ACTION_ADD_TAG = 4;
private static final int VIEW_CONTENT_NAVIGATION_TAG = 5;
private static final int SET_EMPTY_VIEW_ACTION_TAG = 6;
private static final int VIEW_GROUP_ACTION_REMOVE_TAG = 7;
private static final int SET_PENDING_INTENT_TEMPLATE_TAG = 8;
private static final int SET_REMOTE_VIEW_ADAPTER_INTENT_TAG = 10;
private static final int TEXT_VIEW_DRAWABLE_ACTION_TAG = 11;
private static final int BITMAP_REFLECTION_ACTION_TAG = 12;
private static final int TEXT_VIEW_SIZE_ACTION_TAG = 13;
private static final int VIEW_PADDING_ACTION_TAG = 14;
private static final int SET_REMOTE_VIEW_ADAPTER_LIST_TAG = 15;
private static final int SET_REMOTE_INPUTS_ACTION_TAG = 18;
private static final int LAYOUT_PARAM_ACTION_TAG = 19;
private static final int OVERRIDE_TEXT_COLORS_TAG = 20;
private static final int SET_RIPPLE_DRAWABLE_COLOR_TAG = 21;
private static final int SET_INT_TAG_TAG = 22;
private static final int REMOVE_FROM_PARENT_ACTION_TAG = 23;
private static final int RESOURCE_REFLECTION_ACTION_TAG = 24;
private static final int COMPLEX_UNIT_DIMENSION_REFLECTION_ACTION_TAG = 25;
private static final int SET_COMPOUND_BUTTON_CHECKED_TAG = 26;
private static final int SET_RADIO_GROUP_CHECKED = 27;
private static final int SET_VIEW_OUTLINE_RADIUS_TAG = 28;
private static final int SET_ON_CHECKED_CHANGE_RESPONSE_TAG = 29;
private static final int NIGHT_MODE_REFLECTION_ACTION_TAG = 30;
private static final int SET_REMOTE_COLLECTION_ITEMS_ADAPTER_TAG = 31;
private static final int ATTRIBUTE_REFLECTION_ACTION_TAG = 32;
/** @hide **/
@IntDef(prefix = "MARGIN_", value = {
MARGIN_LEFT,
MARGIN_TOP,
MARGIN_RIGHT,
MARGIN_BOTTOM,
MARGIN_START,
MARGIN_END
})
@Retention(RetentionPolicy.SOURCE)
public @interface MarginType {}
/** The value will apply to the marginLeft. */
public static final int MARGIN_LEFT = 0;
/** The value will apply to the marginTop. */
public static final int MARGIN_TOP = 1;
/** The value will apply to the marginRight. */
public static final int MARGIN_RIGHT = 2;
/** The value will apply to the marginBottom. */
public static final int MARGIN_BOTTOM = 3;
/** The value will apply to the marginStart. */
public static final int MARGIN_START = 4;
/** The value will apply to the marginEnd. */
public static final int MARGIN_END = 5;
@IntDef(prefix = "VALUE_TYPE_", value = {
VALUE_TYPE_RAW,
VALUE_TYPE_COMPLEX_UNIT,
VALUE_TYPE_RESOURCE,
VALUE_TYPE_ATTRIBUTE
})
@Retention(RetentionPolicy.SOURCE)
@interface ValueType {}
static final int VALUE_TYPE_RAW = 1;
static final int VALUE_TYPE_COMPLEX_UNIT = 2;
static final int VALUE_TYPE_RESOURCE = 3;
static final int VALUE_TYPE_ATTRIBUTE = 4;
/** @hide **/
@IntDef(flag = true, value = {
FLAG_REAPPLY_DISALLOWED,
FLAG_WIDGET_IS_COLLECTION_CHILD,
FLAG_USE_LIGHT_BACKGROUND_LAYOUT
})
@Retention(RetentionPolicy.SOURCE)
public @interface ApplyFlags {}
/**
* Whether reapply is disallowed on this remoteview. This maybe be true if some actions modify
* the layout in a way that isn't recoverable, since views are being removed.
* @hide
*/
public static final int FLAG_REAPPLY_DISALLOWED = 1;
/**
* This flag indicates whether this RemoteViews object is being created from a
* RemoteViewsService for use as a child of a widget collection. This flag is used
* to determine whether or not certain features are available, in particular,
* setting on click extras and setting on click pending intents. The former is enabled,
* and the latter disabled when this flag is true.
* @hide
*/
public static final int FLAG_WIDGET_IS_COLLECTION_CHILD = 2;
/**
* When this flag is set, the views is inflated with {@link #mLightBackgroundLayoutId} instead
* of {link #mLayoutId}
* @hide
*/
public static final int FLAG_USE_LIGHT_BACKGROUND_LAYOUT = 4;
/**
* This mask determines which flags are propagated to nested RemoteViews (either added by
* addView, or set as portrait/landscape/sized RemoteViews).
*/
static final int FLAG_MASK_TO_PROPAGATE =
FLAG_WIDGET_IS_COLLECTION_CHILD | FLAG_USE_LIGHT_BACKGROUND_LAYOUT;
/**
* A ReadWriteHelper which has the same behavior as ReadWriteHelper.DEFAULT, but which is
* intentionally a different instance in order to trick Bundle reader so that it doesn't allow
* lazy initialization.
*/
private static final Parcel.ReadWriteHelper ALTERNATIVE_DEFAULT = new Parcel.ReadWriteHelper();
/**
* Used to restrict the views which can be inflated
*
* @see android.view.LayoutInflater.Filter#onLoadClass(java.lang.Class)
*/
private static final LayoutInflater.Filter INFLATER_FILTER =
(clazz) -> clazz.isAnnotationPresent(RemoteViews.RemoteView.class);
/**
* Application that hosts the remote views.
*
* @hide
*/
@UnsupportedAppUsage
public ApplicationInfo mApplication;
/**
* The resource ID of the layout file. (Added to the parcel)
*/
@UnsupportedAppUsage
private int mLayoutId;
/**
* The resource ID of the layout file in dark text mode. (Added to the parcel)
*/
private int mLightBackgroundLayoutId = 0;
/**
* An array of actions to perform on the view tree once it has been
* inflated
*/
@UnsupportedAppUsage
private ArrayList<Action> mActions;
/**
* Maps bitmaps to unique indicies to avoid Bitmap duplication.
*/
@UnsupportedAppUsage
private BitmapCache mBitmapCache = new BitmapCache();
/** Cache of ApplicationInfos used by collection items. */
private ApplicationInfoCache mApplicationInfoCache = new ApplicationInfoCache();
/**
* Indicates whether or not this RemoteViews object is contained as a child of any other
* RemoteViews.
*/
private boolean mIsRoot = true;
/**
* Constants to whether or not this RemoteViews is composed of a landscape and portrait
* RemoteViews.
*/
private static final int MODE_NORMAL = 0;
private static final int MODE_HAS_LANDSCAPE_AND_PORTRAIT = 1;
private static final int MODE_HAS_SIZED_REMOTEVIEWS = 2;
/**
* Used in conjunction with the special constructor
* {@link #RemoteViews(RemoteViews, RemoteViews)} to keep track of the landscape and portrait
* RemoteViews.
*/
private RemoteViews mLandscape = null;
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
private RemoteViews mPortrait = null;
/**
* List of RemoteViews with their ideal size. There must be at least two if the map is not null.
*
* The smallest remote view is always the last element in the list.
*/
private List<RemoteViews> mSizedRemoteViews = null;
/**
* Ideal size for this RemoteViews.
*
* Only to be used on children views used in a {@link RemoteViews} with
* {@link RemoteViews#hasSizedRemoteViews()}.
*/
private SizeF mIdealSize = null;
@ApplyFlags
private int mApplyFlags = 0;
/**
* Id to use to override the ID of the top-level view in this RemoteViews.
*
* Only used if this RemoteViews is defined from a XML layout value.
*/
private int mViewId = View.NO_ID;
/**
* Id used to uniquely identify a {@link RemoteViews} instance coming from a given provider.
*/
private long mProviderInstanceId = -1;
/** Class cookies of the Parcel this instance was read from. */
private Map<Class, Object> mClassCookies;
private static final InteractionHandler DEFAULT_INTERACTION_HANDLER =
(view, pendingIntent, response) ->
startPendingIntent(view, pendingIntent, response.getLaunchOptions(view));
private static final ArrayMap<MethodKey, MethodArgs> sMethods = new ArrayMap<>();
/**
* This key is used to perform lookups in sMethods without causing allocations.
*/
private static final MethodKey sLookupKey = new MethodKey();
/**
* @hide
*/
public void setRemoteInputs(@IdRes int viewId, RemoteInput[] remoteInputs) {
mActions.add(new SetRemoteInputsAction(viewId, remoteInputs));
}
/**
* Reduces all images and ensures that they are all below the given sizes.
*
* @param maxWidth the maximum width allowed
* @param maxHeight the maximum height allowed
*
* @hide
*/
public void reduceImageSizes(int maxWidth, int maxHeight) {
ArrayList<Bitmap> cache = mBitmapCache.mBitmaps;
for (int i = 0; i < cache.size(); i++) {
Bitmap bitmap = cache.get(i);
cache.set(i, Icon.scaleDownIfNecessary(bitmap, maxWidth, maxHeight));
}
}
/**
* Override all text colors in this layout and replace them by the given text color.
*
* @param textColor The color to use.
*
* @hide
*/
public void overrideTextColors(int textColor) {
addAction(new OverrideTextColorsAction(textColor));
}
/**
* Sets an integer tag to the view.
*
* @hide
*/
public void setIntTag(@IdRes int viewId, @IdRes int key, int tag) {
addAction(new SetIntTagAction(viewId, key, tag));
}
/**
* Set that it is disallowed to reapply another remoteview with the same layout as this view.
* This should be done if an action is destroying the view tree of the base layout.
*
* @hide
*/
public void addFlags(@ApplyFlags int flags) {
mApplyFlags = mApplyFlags | flags;
int flagsToPropagate = flags & FLAG_MASK_TO_PROPAGATE;
if (flagsToPropagate != 0) {
if (hasSizedRemoteViews()) {
for (RemoteViews remoteView : mSizedRemoteViews) {
remoteView.addFlags(flagsToPropagate);
}
} else if (hasLandscapeAndPortraitLayouts()) {
mLandscape.addFlags(flagsToPropagate);
mPortrait.addFlags(flagsToPropagate);
}
}
}
/**
* @hide
*/
public boolean hasFlags(@ApplyFlags int flag) {
return (mApplyFlags & flag) == flag;
}
/**
* Stores information related to reflection method lookup.
*/
static class MethodKey {
public Class targetClass;
public Class paramClass;
public String methodName;
@Override
public boolean equals(@Nullable Object o) {
if (!(o instanceof MethodKey)) {
return false;
}
MethodKey p = (MethodKey) o;
return Objects.equals(p.targetClass, targetClass)
&& Objects.equals(p.paramClass, paramClass)
&& Objects.equals(p.methodName, methodName);
}
@Override
public int hashCode() {
return Objects.hashCode(targetClass) ^ Objects.hashCode(paramClass)
^ Objects.hashCode(methodName);
}
public void set(Class targetClass, Class paramClass, String methodName) {
this.targetClass = targetClass;
this.paramClass = paramClass;
this.methodName = methodName;
}
}
/**
* Stores information related to reflection method lookup result.
*/
static class MethodArgs {
public MethodHandle syncMethod;
public MethodHandle asyncMethod;
public String asyncMethodName;
}
/**
* This annotation indicates that a subclass of View is allowed to be used
* with the {@link RemoteViews} mechanism.
*/
@Target({ ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
public @interface RemoteView {
}
/**
* Exception to send when something goes wrong executing an action
*
*/
public static class ActionException extends RuntimeException {
public ActionException(Exception ex) {
super(ex);
}
public ActionException(String message) {
super(message);
}
/**
* @hide
*/
public ActionException(Throwable t) {
super(t);
}
}
/**
* Handler for view interactions (such as clicks) within a RemoteViews.
*
* @hide
*/
public interface InteractionHandler {
/**
* Invoked when the user performs an interaction on the View.
*
* @param view the View with which the user interacted
* @param pendingIntent the base PendingIntent associated with the view
* @param response the response to the interaction, which knows how to fill in the
* attached PendingIntent
*
* @hide
*/
boolean onInteraction(
View view,
PendingIntent pendingIntent,
RemoteResponse response);
}
/**
* Base class for all actions that can be performed on an
* inflated view.
*
* SUBCLASSES MUST BE IMMUTABLE SO CLONE WORKS!!!!!
*/
private abstract static class Action implements Parcelable {
public abstract void apply(View root, ViewGroup rootParent, ActionApplyParams params)
throws ActionException;
public static final int MERGE_REPLACE = 0;
public static final int MERGE_APPEND = 1;
public static final int MERGE_IGNORE = 2;
public int describeContents() {
return 0;
}
public void setHierarchyRootData(HierarchyRootData root) {
// Do nothing
}
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
public int mergeBehavior() {
return MERGE_REPLACE;
}
public abstract int getActionTag();
public String getUniqueKey() {
return (getActionTag() + "_" + viewId);
}
/**
* This is called on the background thread. It should perform any non-ui computations
* and return the final action which will run on the UI thread.
* Override this if some of the tasks can be performed async.
*/
public Action initActionAsync(ViewTree root, ViewGroup rootParent,
ActionApplyParams params) {
return this;
}
public boolean prefersAsyncApply() {
return false;
}
public void visitUris(@NonNull Consumer<Uri> visitor) {
// Nothing to visit by default
}
@IdRes
@UnsupportedAppUsage
int viewId;
}
/**
* Action class used during async inflation of RemoteViews. Subclasses are not parcelable.
*/
private static abstract class RuntimeAction extends Action {
@Override
public final int getActionTag() {
return 0;
}
@Override
public final void writeToParcel(Parcel dest, int flags) {
throw new UnsupportedOperationException();
}
}
// Constant used during async execution. It is not parcelable.
private static final Action ACTION_NOOP = new RuntimeAction() {
@Override
public void apply(View root, ViewGroup rootParent, ActionApplyParams params) { }
};
/**
* Merges the passed RemoteViews actions with this RemoteViews actions according to
* action-specific merge rules.
*
* @param newRv
*
* @hide
*/
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
public void mergeRemoteViews(RemoteViews newRv) {
if (newRv == null) return;
// We first copy the new RemoteViews, as the process of merging modifies the way the actions
// reference the bitmap cache. We don't want to modify the object as it may need to
// be merged and applied multiple times.
RemoteViews copy = new RemoteViews(newRv);
HashMap<String, Action> map = new HashMap<String, Action>();
if (mActions == null) {
mActions = new ArrayList<Action>();
}
int count = mActions.size();
for (int i = 0; i < count; i++) {
Action a = mActions.get(i);
map.put(a.getUniqueKey(), a);
}
ArrayList<Action> newActions = copy.mActions;
if (newActions == null) return;
count = newActions.size();
for (int i = 0; i < count; i++) {
Action a = newActions.get(i);
String key = newActions.get(i).getUniqueKey();
int mergeBehavior = newActions.get(i).mergeBehavior();
if (map.containsKey(key) && mergeBehavior == Action.MERGE_REPLACE) {
mActions.remove(map.get(key));
map.remove(key);
}
// If the merge behavior is ignore, we don't bother keeping the extra action
if (mergeBehavior == Action.MERGE_REPLACE || mergeBehavior == Action.MERGE_APPEND) {
mActions.add(a);
}
}
// Because pruning can remove the need for bitmaps, we reconstruct the caches.
reconstructCaches();
}
/**
* Note all {@link Uri} that are referenced internally, with the expectation
* that Uri permission grants will need to be issued to ensure the recipient
* of this object is able to render its contents.
*
* @hide
*/
public void visitUris(@NonNull Consumer<Uri> visitor) {
if (mActions != null) {
for (int i = 0; i < mActions.size(); i++) {
mActions.get(i).visitUris(visitor);
}
}
}
private static void visitIconUri(Icon icon, @NonNull Consumer<Uri> visitor) {
if (icon != null && (icon.getType() == Icon.TYPE_URI
|| icon.getType() == Icon.TYPE_URI_ADAPTIVE_BITMAP)) {
visitor.accept(icon.getUri());
}
}
private static class RemoteViewsContextWrapper extends ContextWrapper {
private final Context mContextForResources;
RemoteViewsContextWrapper(Context context, Context contextForResources) {
super(context);
mContextForResources = contextForResources;
}
@Override
public Resources getResources() {
return mContextForResources.getResources();
}
@Override
public Resources.Theme getTheme() {
return mContextForResources.getTheme();
}
@Override
public String getPackageName() {
return mContextForResources.getPackageName();
}
@Override
public UserHandle getUser() {
return mContextForResources.getUser();
}
@Override
public int getUserId() {
return mContextForResources.getUserId();
}
@Override
public boolean isRestricted() {
// Override isRestricted and direct to resource's implementation. The isRestricted is
// used for determining the risky resources loading, e.g. fonts, thus direct to context
// for resource.
return mContextForResources.isRestricted();
}
}
private class SetEmptyView extends Action {
int emptyViewId;
SetEmptyView(@IdRes int viewId, @IdRes int emptyViewId) {
this.viewId = viewId;
this.emptyViewId = emptyViewId;
}
SetEmptyView(Parcel in) {
this.viewId = in.readInt();
this.emptyViewId = in.readInt();
}
public void writeToParcel(Parcel out, int flags) {
out.writeInt(this.viewId);
out.writeInt(this.emptyViewId);
}
@Override
public void apply(View root, ViewGroup rootParent, ActionApplyParams params) {
final View view = root.findViewById(viewId);
if (!(view instanceof AdapterView<?>)) return;
AdapterView<?> adapterView = (AdapterView<?>) view;
final View emptyView = root.findViewById(emptyViewId);
if (emptyView == null) return;
adapterView.setEmptyView(emptyView);
}
@Override
public int getActionTag() {
return SET_EMPTY_VIEW_ACTION_TAG;
}
}
private class SetPendingIntentTemplate extends Action {
public SetPendingIntentTemplate(@IdRes int id, PendingIntent pendingIntentTemplate) {
this.viewId = id;
this.pendingIntentTemplate = pendingIntentTemplate;
}
public SetPendingIntentTemplate(Parcel parcel) {
viewId = parcel.readInt();
pendingIntentTemplate = PendingIntent.readPendingIntentOrNullFromParcel(parcel);
}
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(viewId);
PendingIntent.writePendingIntentOrNullToParcel(pendingIntentTemplate, dest);
}
@Override
public void apply(View root, ViewGroup rootParent, ActionApplyParams params) {
final View target = root.findViewById(viewId);
if (target == null) return;
// If the view isn't an AdapterView, setting a PendingIntent template doesn't make sense
if (target instanceof AdapterView<?>) {
AdapterView<?> av = (AdapterView<?>) target;
// The PendingIntent template is stored in the view's tag.
OnItemClickListener listener = (parent, view, position, id) -> {
RemoteResponse response = findRemoteResponseTag(view);
if (response != null) {
response.handleViewInteraction(view, params.handler);
}
};
av.setOnItemClickListener(listener);
av.setTag(pendingIntentTemplate);
} else {
Log.e(LOG_TAG, "Cannot setPendingIntentTemplate on a view which is not" +
"an AdapterView (id: " + viewId + ")");
return;
}
}
@Nullable
private RemoteResponse findRemoteResponseTag(@Nullable View rootView) {
if (rootView == null) return null;
ArrayDeque<View> viewsToCheck = new ArrayDeque<>();
viewsToCheck.addLast(rootView);
while (!viewsToCheck.isEmpty()) {
View view = viewsToCheck.removeFirst();
Object tag = view.getTag(R.id.fillInIntent);
if (tag instanceof RemoteResponse) return (RemoteResponse) tag;
if (!(view instanceof ViewGroup)) continue;
ViewGroup viewGroup = (ViewGroup) view;
for (int i = 0; i < viewGroup.getChildCount(); i++) {
viewsToCheck.addLast(viewGroup.getChildAt(i));
}
}
return null;
}
@Override
public int getActionTag() {
return SET_PENDING_INTENT_TEMPLATE_TAG;
}
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
PendingIntent pendingIntentTemplate;
}
private class SetRemoteViewsAdapterList extends Action {
public SetRemoteViewsAdapterList(@IdRes int id, ArrayList<RemoteViews> list,
int viewTypeCount) {
this.viewId = id;
this.list = list;
this.viewTypeCount = viewTypeCount;
}
public SetRemoteViewsAdapterList(Parcel parcel) {
viewId = parcel.readInt();
viewTypeCount = parcel.readInt();
list = parcel.createTypedArrayList(RemoteViews.CREATOR);
}
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(viewId);
dest.writeInt(viewTypeCount);
dest.writeTypedList(list, flags);
}
@Override
public void apply(View root, ViewGroup rootParent, ActionApplyParams params) {
final View target = root.findViewById(viewId);
if (target == null) return;
// Ensure that we are applying to an AppWidget root
if (!(rootParent instanceof AppWidgetHostView)) {
Log.e(LOG_TAG, "SetRemoteViewsAdapterIntent action can only be used for " +
"AppWidgets (root id: " + viewId + ")");
return;
}
// Ensure that we are calling setRemoteAdapter on an AdapterView that supports it
if (!(target instanceof AbsListView) && !(target instanceof AdapterViewAnimator)) {
Log.e(LOG_TAG, "Cannot setRemoteViewsAdapter on a view which is not " +
"an AbsListView or AdapterViewAnimator (id: " + viewId + ")");
return;
}
if (target instanceof AbsListView) {
AbsListView v = (AbsListView) target;
Adapter a = v.getAdapter();
if (a instanceof RemoteViewsListAdapter && viewTypeCount <= a.getViewTypeCount()) {
((RemoteViewsListAdapter) a).setViewsList(list);
} else {
v.setAdapter(new RemoteViewsListAdapter(v.getContext(), list, viewTypeCount,
params.colorResources));
}
} else if (target instanceof AdapterViewAnimator) {
AdapterViewAnimator v = (AdapterViewAnimator) target;
Adapter a = v.getAdapter();
if (a instanceof RemoteViewsListAdapter && viewTypeCount <= a.getViewTypeCount()) {
((RemoteViewsListAdapter) a).setViewsList(list);
} else {
v.setAdapter(new RemoteViewsListAdapter(v.getContext(), list, viewTypeCount,
params.colorResources));
}
}
}
@Override
public int getActionTag() {
return SET_REMOTE_VIEW_ADAPTER_LIST_TAG;
}
int viewTypeCount;
ArrayList<RemoteViews> list;
}
/**
* Cache of {@link ApplicationInfo}s that can be used to ensure that the same
* {@link ApplicationInfo} instance is used throughout the RemoteViews.
*/
private static class ApplicationInfoCache {
private final Map<Pair<String, Integer>, ApplicationInfo> mPackageUserToApplicationInfo;
ApplicationInfoCache() {
mPackageUserToApplicationInfo = new ArrayMap<>();
}
/**
* Adds the {@link ApplicationInfo} to the cache if it's not present. Returns either the
* provided {@code applicationInfo} or a previously added value with the same package name
* and uid.
*/
@Nullable
ApplicationInfo getOrPut(@Nullable ApplicationInfo applicationInfo) {
Pair<String, Integer> key = getPackageUserKey(applicationInfo);
if (key == null) return null;
return mPackageUserToApplicationInfo.computeIfAbsent(key, ignored -> applicationInfo);
}
/** Puts the {@link ApplicationInfo} in the cache, replacing any previously stored value. */
void put(@Nullable ApplicationInfo applicationInfo) {
Pair<String, Integer> key = getPackageUserKey(applicationInfo);
if (key == null) return;
mPackageUserToApplicationInfo.put(key, applicationInfo);
}
/**
* Returns the currently stored {@link ApplicationInfo} from the cache matching
* {@code applicationInfo}, or null if there wasn't any.
*/
@Nullable ApplicationInfo get(@Nullable ApplicationInfo applicationInfo) {
Pair<String, Integer> key = getPackageUserKey(applicationInfo);
if (key == null) return null;
return mPackageUserToApplicationInfo.get(key);
}
}
private class SetRemoteCollectionItemListAdapterAction extends Action {
private final RemoteCollectionItems mItems;
SetRemoteCollectionItemListAdapterAction(@IdRes int id, RemoteCollectionItems items) {
viewId = id;
mItems = items;
mItems.setHierarchyRootData(getHierarchyRootData());
}
SetRemoteCollectionItemListAdapterAction(Parcel parcel) {
viewId = parcel.readInt();
mItems = new RemoteCollectionItems(parcel, getHierarchyRootData());
}
@Override
public void setHierarchyRootData(HierarchyRootData rootData) {
mItems.setHierarchyRootData(rootData);
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(viewId);
mItems.writeToParcel(dest, flags, /* attached= */ true);
}
@Override
public void apply(View root, ViewGroup rootParent, ActionApplyParams params)
throws ActionException {
View target = root.findViewById(viewId);
if (target == null) return;
// Ensure that we are applying to an AppWidget root
if (!(rootParent instanceof AppWidgetHostView)) {
Log.e(LOG_TAG, "setRemoteAdapter can only be used for "
+ "AppWidgets (root id: " + viewId + ")");
return;
}
if (!(target instanceof AdapterView)) {
Log.e(LOG_TAG, "Cannot call setRemoteAdapter on a view which is not "
+ "an AdapterView (id: " + viewId + ")");
return;
}
AdapterView adapterView = (AdapterView) target;
Adapter adapter = adapterView.getAdapter();
// We can reuse the adapter if it's a RemoteCollectionItemsAdapter and the view type
// count hasn't increased. Note that AbsListView allocates a fixed size array for view
// recycling in setAdapter, so we must call setAdapter again if the number of view types
// increases.
if (adapter instanceof RemoteCollectionItemsAdapter
&& adapter.getViewTypeCount() >= mItems.getViewTypeCount()) {
try {
((RemoteCollectionItemsAdapter) adapter).setData(
mItems, params.handler, params.colorResources);
} catch (Throwable throwable) {
// setData should never failed with the validation in the items builder, but if
// it does, catch and rethrow.
throw new ActionException(throwable);
}
return;
}
try {
adapterView.setAdapter(new RemoteCollectionItemsAdapter(mItems,
params.handler, params.colorResources));
} catch (Throwable throwable) {
// This could throw if the AdapterView somehow doesn't accept BaseAdapter due to
// a type error.
throw new ActionException(throwable);
}
}
@Override
public int getActionTag() {
return SET_REMOTE_COLLECTION_ITEMS_ADAPTER_TAG;
}
}
private class SetRemoteViewsAdapterIntent extends Action {
public SetRemoteViewsAdapterIntent(@IdRes int id, Intent intent) {
this.viewId = id;
this.intent = intent;
}
public SetRemoteViewsAdapterIntent(Parcel parcel) {
viewId = parcel.readInt();
intent = parcel.readTypedObject(Intent.CREATOR);
}
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(viewId);
dest.writeTypedObject(intent, flags);
}
@Override
public void apply(View root, ViewGroup rootParent, ActionApplyParams params) {
final View target = root.findViewById(viewId);
if (target == null) return;
// Ensure that we are applying to an AppWidget root
if (!(rootParent instanceof AppWidgetHostView)) {
Log.e(LOG_TAG, "setRemoteAdapter can only be used for "
+ "AppWidgets (root id: " + viewId + ")");
return;
}
// Ensure that we are calling setRemoteAdapter on an AdapterView that supports it
if (!(target instanceof AbsListView) && !(target instanceof AdapterViewAnimator)) {
Log.e(LOG_TAG, "Cannot setRemoteAdapter on a view which is not "
+ "an AbsListView or AdapterViewAnimator (id: " + viewId + ")");
return;
}
// Embed the AppWidget Id for use in RemoteViewsAdapter when connecting to the intent
// RemoteViewsService
AppWidgetHostView host = (AppWidgetHostView) rootParent;
intent.putExtra(EXTRA_REMOTEADAPTER_APPWIDGET_ID, host.getAppWidgetId())
.putExtra(EXTRA_REMOTEADAPTER_ON_LIGHT_BACKGROUND,
hasFlags(FLAG_USE_LIGHT_BACKGROUND_LAYOUT));
if (target instanceof AbsListView) {
AbsListView v = (AbsListView) target;
v.setRemoteViewsAdapter(intent, isAsync);
v.setRemoteViewsInteractionHandler(params.handler);
} else if (target instanceof AdapterViewAnimator) {
AdapterViewAnimator v = (AdapterViewAnimator) target;
v.setRemoteViewsAdapter(intent, isAsync);
v.setRemoteViewsOnClickHandler(params.handler);
}
}
@Override
public Action initActionAsync(ViewTree root, ViewGroup rootParent,
ActionApplyParams params) {
SetRemoteViewsAdapterIntent copy = new SetRemoteViewsAdapterIntent(viewId, intent);
copy.isAsync = true;
return copy;
}
@Override
public int getActionTag() {
return SET_REMOTE_VIEW_ADAPTER_INTENT_TAG;
}
Intent intent;
boolean isAsync = false;
}
/**
* Equivalent to calling
* {@link android.view.View#setOnClickListener(android.view.View.OnClickListener)}
* to launch the provided {@link PendingIntent}.
*/
private class SetOnClickResponse extends Action {
SetOnClickResponse(@IdRes int id, RemoteResponse response) {
this.viewId = id;
this.mResponse = response;
}
SetOnClickResponse(Parcel parcel) {
viewId = parcel.readInt();
mResponse = new RemoteResponse();
mResponse.readFromParcel(parcel);
}
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(viewId);
mResponse.writeToParcel(dest, flags);
}
@Override
public void apply(View root, ViewGroup rootParent, ActionApplyParams params) {
final View target = root.findViewById(viewId);
if (target == null) return;
if (mResponse.mPendingIntent != null) {
// If the view is an AdapterView, setting a PendingIntent on click doesn't make
// much sense, do they mean to set a PendingIntent template for the
// AdapterView's children?
if (hasFlags(FLAG_WIDGET_IS_COLLECTION_CHILD)) {
Log.w(LOG_TAG, "Cannot SetOnClickResponse for collection item "
+ "(id: " + viewId + ")");
ApplicationInfo appInfo = root.getContext().getApplicationInfo();
// We let this slide for HC and ICS so as to not break compatibility. It should
// have been disabled from the outset, but was left open by accident.
if (appInfo != null
&& appInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
return;
}
}
target.setTagInternal(R.id.pending_intent_tag, mResponse.mPendingIntent);
} else if (mResponse.mFillIntent != null) {
if (!hasFlags(FLAG_WIDGET_IS_COLLECTION_CHILD)) {
Log.e(LOG_TAG, "The method setOnClickFillInIntent is available "
+ "only from RemoteViewsFactory (ie. on collection items).");
return;
}
if (target == root) {
// Target is a root node of an AdapterView child. Set the response in the tag.
// Actual click handling is done by OnItemClickListener in
// SetPendingIntentTemplate, which uses this tag information.
target.setTagInternal(com.android.internal.R.id.fillInIntent, mResponse);
return;
}
} else {
// No intent to apply, clear the listener and any tags that were previously set.
target.setOnClickListener(null);
target.setTagInternal(R.id.pending_intent_tag, null);
target.setTagInternal(com.android.internal.R.id.fillInIntent, null);
return;
}
target.setOnClickListener(v -> mResponse.handleViewInteraction(v, params.handler));
}
@Override
public int getActionTag() {
return SET_ON_CLICK_RESPONSE_TAG;
}
final RemoteResponse mResponse;
}
/**
* Equivalent to calling
* {@link android.widget.CompoundButton#setOnCheckedChangeListener(
* android.widget.CompoundButton.OnCheckedChangeListener)}
* to launch the provided {@link PendingIntent}.
*/
private class SetOnCheckedChangeResponse extends Action {
private final RemoteResponse mResponse;
SetOnCheckedChangeResponse(@IdRes int id, RemoteResponse response) {
this.viewId = id;
this.mResponse = response;
}
SetOnCheckedChangeResponse(Parcel parcel) {
viewId = parcel.readInt();
mResponse = new RemoteResponse();
mResponse.readFromParcel(parcel);
}
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(viewId);
mResponse.writeToParcel(dest, flags);
}
@Override
public void apply(View root, ViewGroup rootParent, ActionApplyParams params) {
final View target = root.findViewById(viewId);
if (target == null) return;
if (!(target instanceof CompoundButton)) {
Log.w(LOG_TAG, "setOnCheckedChange methods cannot be used on "
+ "non-CompoundButton child (id: " + viewId + ")");
return;
}
CompoundButton button = (CompoundButton) target;
if (mResponse.mPendingIntent != null) {
// setOnCheckedChangePendingIntent cannot be used with collection children, which
// must use setOnCheckedChangeFillInIntent instead.
if (hasFlags(FLAG_WIDGET_IS_COLLECTION_CHILD)) {
Log.w(LOG_TAG, "Cannot setOnCheckedChangePendingIntent for collection item "
+ "(id: " + viewId + ")");
return;
}
target.setTagInternal(R.id.pending_intent_tag, mResponse.mPendingIntent);
} else if (mResponse.mFillIntent != null) {
if (!hasFlags(FLAG_WIDGET_IS_COLLECTION_CHILD)) {
Log.e(LOG_TAG, "The method setOnCheckedChangeFillInIntent is available "
+ "only from RemoteViewsFactory (ie. on collection items).");
return;
}
} else {
// No intent to apply, clear any existing listener or tag.
button.setOnCheckedChangeListener(null);
button.setTagInternal(R.id.remote_checked_change_listener_tag, null);
return;
}
OnCheckedChangeListener onCheckedChangeListener =
(v, isChecked) -> mResponse.handleViewInteraction(v, params.handler);
button.setTagInternal(R.id.remote_checked_change_listener_tag, onCheckedChangeListener);
button.setOnCheckedChangeListener(onCheckedChangeListener);
}
@Override
public int getActionTag() {
return SET_ON_CHECKED_CHANGE_RESPONSE_TAG;
}
}
/** @hide **/
public static Rect getSourceBounds(View v) {
final float appScale = v.getContext().getResources()
.getCompatibilityInfo().applicationScale;
final int[] pos = new int[2];
v.getLocationOnScreen(pos);
final Rect rect = new Rect();
rect.left = (int) (pos[0] * appScale + 0.5f);
rect.top = (int) (pos[1] * appScale + 0.5f);
rect.right = (int) ((pos[0] + v.getWidth()) * appScale + 0.5f);
rect.bottom = (int) ((pos[1] + v.getHeight()) * appScale + 0.5f);
return rect;
}
@Nullable
private static Class<?> getParameterType(int type) {
switch (type) {
case BaseReflectionAction.BOOLEAN:
return boolean.class;
case BaseReflectionAction.BYTE:
return byte.class;
case BaseReflectionAction.SHORT:
return short.class;
case BaseReflectionAction.INT:
return int.class;
case BaseReflectionAction.LONG:
return long.class;
case BaseReflectionAction.FLOAT:
return float.class;
case BaseReflectionAction.DOUBLE:
return double.class;
case BaseReflectionAction.CHAR:
return char.class;
case BaseReflectionAction.STRING:
return String.class;
case BaseReflectionAction.CHAR_SEQUENCE:
return CharSequence.class;
case BaseReflectionAction.URI:
return Uri.class;
case BaseReflectionAction.BITMAP:
return Bitmap.class;
case BaseReflectionAction.BUNDLE:
return Bundle.class;
case BaseReflectionAction.INTENT:
return Intent.class;
case BaseReflectionAction.COLOR_STATE_LIST:
return ColorStateList.class;
case BaseReflectionAction.ICON:
return Icon.class;
case BaseReflectionAction.BLEND_MODE:
return BlendMode.class;
default:
return null;
}
}
@Nullable
private MethodHandle getMethod(View view, String methodName, Class<?> paramType,
boolean async) {
MethodArgs result;
Class<? extends View> klass = view.getClass();
synchronized (sMethods) {
// The key is defined by the view class, param class and method name.
sLookupKey.set(klass, paramType, methodName);
result = sMethods.get(sLookupKey);
if (result == null) {
Method method;
try {
if (paramType == null) {
method = klass.getMethod(methodName);
} else {
method = klass.getMethod(methodName, paramType);
}
if (!method.isAnnotationPresent(RemotableViewMethod.class)) {
throw new ActionException("view: " + klass.getName()
+ " can't use method with RemoteViews: "
+ methodName + getParameters(paramType));
}
result = new MethodArgs();
result.syncMethod = MethodHandles.publicLookup().unreflect(method);
result.asyncMethodName =
method.getAnnotation(RemotableViewMethod.class).asyncImpl();
} catch (NoSuchMethodException | IllegalAccessException ex) {
throw new ActionException("view: " + klass.getName() + " doesn't have method: "
+ methodName + getParameters(paramType));
}
MethodKey key = new MethodKey();
key.set(klass, paramType, methodName);
sMethods.put(key, result);
}
if (!async) {
return result.syncMethod;
}
// Check this so see if async method is implemented or not.
if (result.asyncMethodName.isEmpty()) {
return null;
}
// Async method is lazily loaded. If it is not yet loaded, load now.
if (result.asyncMethod == null) {
MethodType asyncType = result.syncMethod.type()
.dropParameterTypes(0, 1).changeReturnType(Runnable.class);
try {
result.asyncMethod = MethodHandles.publicLookup().findVirtual(
klass, result.asyncMethodName, asyncType);
} catch (NoSuchMethodException | IllegalAccessException ex) {
throw new ActionException("Async implementation declared as "
+ result.asyncMethodName + " but not defined for " + methodName
+ ": public Runnable " + result.asyncMethodName + " ("
+ TextUtils.join(",", asyncType.parameterArray()) + ")");
}
}
return result.asyncMethod;
}
}
private static String getParameters(Class<?> paramType) {
if (paramType == null) return "()";
return "(" + paramType + ")";
}
/**
* Equivalent to calling
* {@link Drawable#setColorFilter(int, android.graphics.PorterDuff.Mode)},
* on the {@link Drawable} of a given view.
* <p>
* The operation will be performed on the {@link Drawable} returned by the
* target {@link View#getBackground()} by default. If targetBackground is false,
* we assume the target is an {@link ImageView} and try applying the operations
* to {@link ImageView#getDrawable()}.
* <p>
*/
private class SetDrawableTint extends Action {
SetDrawableTint(@IdRes int id, boolean targetBackground,
@ColorInt int colorFilter, @NonNull PorterDuff.Mode mode) {
this.viewId = id;
this.targetBackground = targetBackground;
this.colorFilter = colorFilter;
this.filterMode = mode;
}
SetDrawableTint(Parcel parcel) {
viewId = parcel.readInt();
targetBackground = parcel.readInt() != 0;
colorFilter = parcel.readInt();
filterMode = PorterDuff.intToMode(parcel.readInt());
}
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(viewId);
dest.writeInt(targetBackground ? 1 : 0);
dest.writeInt(colorFilter);
dest.writeInt(PorterDuff.modeToInt(filterMode));
}
@Override
public void apply(View root, ViewGroup rootParent, ActionApplyParams params) {
final View target = root.findViewById(viewId);
if (target == null) return;
// Pick the correct drawable to modify for this view
Drawable targetDrawable = null;
if (targetBackground) {
targetDrawable = target.getBackground();
} else if (target instanceof ImageView) {
ImageView imageView = (ImageView) target;
targetDrawable = imageView.getDrawable();
}
if (targetDrawable != null) {
targetDrawable.mutate().setColorFilter(colorFilter, filterMode);
}
}
@Override
public int getActionTag() {
return SET_DRAWABLE_TINT_TAG;
}
boolean targetBackground;
@ColorInt int colorFilter;
PorterDuff.Mode filterMode;
}
/**
* Equivalent to calling
* {@link RippleDrawable#setColor(ColorStateList)},
* on the {@link Drawable} of a given view.
* <p>
* The operation will be performed on the {@link Drawable} returned by the
* target {@link View#getBackground()}.
* <p>
*/
private class SetRippleDrawableColor extends Action {
ColorStateList mColorStateList;
SetRippleDrawableColor(@IdRes int id, ColorStateList colorStateList) {
this.viewId = id;
this.mColorStateList = colorStateList;
}
SetRippleDrawableColor(Parcel parcel) {
viewId = parcel.readInt();
mColorStateList = parcel.readParcelable(null, android.content.res.ColorStateList.class);
}
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(viewId);
dest.writeParcelable(mColorStateList, 0);
}
@Override
public void apply(View root, ViewGroup rootParent, ActionApplyParams params) {
final View target = root.findViewById(viewId);
if (target == null) return;
// Pick the correct drawable to modify for this view
Drawable targetDrawable = target.getBackground();
if (targetDrawable instanceof RippleDrawable) {
((RippleDrawable) targetDrawable.mutate()).setColor(mColorStateList);
}
}
@Override
public int getActionTag() {
return SET_RIPPLE_DRAWABLE_COLOR_TAG;
}
}
/**
* @deprecated As RemoteViews may be reapplied frequently, it is preferable to call
* {@link #setDisplayedChild(int, int)} to ensure that the adapter index does not change
* unexpectedly.
*/
@Deprecated
private final class ViewContentNavigation extends Action {
final boolean mNext;
ViewContentNavigation(@IdRes int viewId, boolean next) {
this.viewId = viewId;
this.mNext = next;
}
ViewContentNavigation(Parcel in) {
this.viewId = in.readInt();
this.mNext = in.readBoolean();
}
public void writeToParcel(Parcel out, int flags) {
out.writeInt(this.viewId);
out.writeBoolean(this.mNext);
}
@Override
public void apply(View root, ViewGroup rootParent, ActionApplyParams params) {
final View view = root.findViewById(viewId);
if (view == null) return;
try {
getMethod(view,
mNext ? "showNext" : "showPrevious", null, false /* async */).invoke(view);
} catch (Throwable ex) {
throw new ActionException(ex);
}
}
public int mergeBehavior() {
return MERGE_IGNORE;
}
@Override
public int getActionTag() {
return VIEW_CONTENT_NAVIGATION_TAG;
}
}
private static class BitmapCache {
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
ArrayList<Bitmap> mBitmaps;
SparseIntArray mBitmapHashes;
int mBitmapMemory = -1;
public BitmapCache() {
mBitmaps = new ArrayList<>();
mBitmapHashes = new SparseIntArray();
}
public BitmapCache(Parcel source) {
mBitmaps = source.createTypedArrayList(Bitmap.CREATOR);
mBitmapHashes = new SparseIntArray();
for (int i = 0; i < mBitmaps.size(); i++) {
Bitmap b = mBitmaps.get(i);
if (b != null) {
mBitmapHashes.put(b.hashCode(), i);
}
}
}
public int getBitmapId(Bitmap b) {
if (b == null) {
return -1;
} else {
int hash = b.hashCode();
int hashId = mBitmapHashes.get(hash, -1);
if (hashId != -1) {
return hashId;
} else {
if (b.isMutable()) {
b = b.asShared();
}
mBitmaps.add(b);
mBitmapHashes.put(hash, mBitmaps.size() - 1);
mBitmapMemory = -1;
return (mBitmaps.size() - 1);
}
}
}
@Nullable
public Bitmap getBitmapForId(int id) {
if (id == -1 || id >= mBitmaps.size()) {
return null;
}
return mBitmaps.get(id);
}
public void writeBitmapsToParcel(Parcel dest, int flags) {
dest.writeTypedList(mBitmaps, flags);
}
public int getBitmapMemory() {
if (mBitmapMemory < 0) {
mBitmapMemory = 0;
int count = mBitmaps.size();
for (int i = 0; i < count; i++) {
mBitmapMemory += mBitmaps.get(i).getAllocationByteCount();
}
}
return mBitmapMemory;
}
}
private class BitmapReflectionAction extends Action {
int bitmapId;
@UnsupportedAppUsage
Bitmap bitmap;
@UnsupportedAppUsage
String methodName;
BitmapReflectionAction(@IdRes int viewId, String methodName, Bitmap bitmap) {
this.bitmap = bitmap;
this.viewId = viewId;
this.methodName = methodName;
bitmapId = mBitmapCache.getBitmapId(bitmap);
}
BitmapReflectionAction(Parcel in) {
viewId = in.readInt();
methodName = in.readString8();
bitmapId = in.readInt();
bitmap = mBitmapCache.getBitmapForId(bitmapId);
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(viewId);
dest.writeString8(methodName);
dest.writeInt(bitmapId);
}
@Override
public void apply(View root, ViewGroup rootParent, ActionApplyParams params)
throws ActionException {
ReflectionAction ra = new ReflectionAction(viewId, methodName,
BaseReflectionAction.BITMAP,
bitmap);
ra.apply(root, rootParent, params);
}
@Override
public void setHierarchyRootData(HierarchyRootData rootData) {
bitmapId = rootData.mBitmapCache.getBitmapId(bitmap);
}
@Override
public int getActionTag() {
return BITMAP_REFLECTION_ACTION_TAG;
}
}
/**
* Base class for the reflection actions.
*/
private abstract class BaseReflectionAction extends Action {
static final int BOOLEAN = 1;
static final int BYTE = 2;
static final int SHORT = 3;
static final int INT = 4;
static final int LONG = 5;
static final int FLOAT = 6;
static final int DOUBLE = 7;
static final int CHAR = 8;
static final int STRING = 9;
static final int CHAR_SEQUENCE = 10;
static final int URI = 11;
// BITMAP actions are never stored in the list of actions. They are only used locally
// to implement BitmapReflectionAction, which eliminates duplicates using BitmapCache.
static final int BITMAP = 12;
static final int BUNDLE = 13;
static final int INTENT = 14;
static final int COLOR_STATE_LIST = 15;
static final int ICON = 16;
static final int BLEND_MODE = 17;
@UnsupportedAppUsage
String methodName;
int type;
BaseReflectionAction(@IdRes int viewId, String methodName, int type) {
this.viewId = viewId;
this.methodName = methodName;
this.type = type;
}
BaseReflectionAction(Parcel in) {
this.viewId = in.readInt();
this.methodName = in.readString8();
this.type = in.readInt();
//noinspection ConstantIfStatement
if (false) {
Log.d(LOG_TAG, "read viewId=0x" + Integer.toHexString(this.viewId)
+ " methodName=" + this.methodName + " type=" + this.type);
}
}
public void writeToParcel(Parcel out, int flags) {
out.writeInt(this.viewId);
out.writeString8(this.methodName);
out.writeInt(this.type);
}
/**
* Returns the value to use as parameter for the method.
*
* The view might be passed as {@code null} if the parameter value is requested outside of
* inflation. If the parameter cannot be determined at that time, the method should return
* {@code null} but not raise any exception.
*/
@Nullable
protected abstract Object getParameterValue(@Nullable View view) throws ActionException;
@Override
public final void apply(View root, ViewGroup rootParent, ActionApplyParams params) {
final View view = root.findViewById(viewId);
if (view == null) return;
Class<?> param = getParameterType(this.type);
if (param == null) {
throw new ActionException("bad type: " + this.type);
}
Object value = getParameterValue(view);
try {
getMethod(view, this.methodName, param, false /* async */).invoke(view, value);
} catch (Throwable ex) {
throw new ActionException(ex);
}
}
@Override
public final Action initActionAsync(ViewTree root, ViewGroup rootParent,
ActionApplyParams params) {
final View view = root.findViewById(viewId);
if (view == null) return ACTION_NOOP;
Class<?> param = getParameterType(this.type);
if (param == null) {
throw new ActionException("bad type: " + this.type);
}
Object value = getParameterValue(view);
try {
MethodHandle method = getMethod(view, this.methodName, param, true /* async */);
if (method != null) {
Runnable endAction = (Runnable) method.invoke(view, value);
if (endAction == null) {
return ACTION_NOOP;
}
// Special case view stub
if (endAction instanceof ViewStub.ViewReplaceRunnable) {
root.createTree();
// Replace child tree
root.findViewTreeById(viewId).replaceView(
((ViewStub.ViewReplaceRunnable) endAction).view);
}
return new RunnableAction(endAction);
}
} catch (Throwable ex) {
throw new ActionException(ex);
}
return this;
}
public final int mergeBehavior() {
// smoothScrollBy is cumulative, everything else overwites.
if (methodName.equals("smoothScrollBy")) {
return MERGE_APPEND;
} else {
return MERGE_REPLACE;
}
}
@Override
public final String getUniqueKey() {
// Each type of reflection action corresponds to a setter, so each should be seen as
// unique from the standpoint of merging.
return super.getUniqueKey() + this.methodName + this.type;
}
@Override
public final boolean prefersAsyncApply() {
return this.type == URI || this.type == ICON;
}
@Override
public final void visitUris(@NonNull Consumer<Uri> visitor) {
switch (this.type) {
case URI:
final Uri uri = (Uri) getParameterValue(null);
if (uri != null) visitor.accept(uri);
break;
case ICON:
final Icon icon = (Icon) getParameterValue(null);
if (icon != null) visitIconUri(icon, visitor);
break;
}
}
}
/** Class for the reflection actions. */
private final class ReflectionAction extends BaseReflectionAction {
@UnsupportedAppUsage
Object value;
ReflectionAction(@IdRes int viewId, String methodName, int type, Object value) {
super(viewId, methodName, type);
this.value = value;
}
ReflectionAction(Parcel in) {
super(in);
// For some values that may have been null, we first check a flag to see if they were
// written to the parcel.
switch (this.type) {
case BOOLEAN:
this.value = in.readBoolean();
break;
case BYTE:
this.value = in.readByte();
break;
case SHORT:
this.value = (short) in.readInt();
break;
case INT:
this.value = in.readInt();
break;
case LONG:
this.value = in.readLong();
break;
case FLOAT:
this.value = in.readFloat();
break;
case DOUBLE:
this.value = in.readDouble();
break;
case CHAR:
this.value = (char) in.readInt();
break;
case STRING:
this.value = in.readString8();
break;
case CHAR_SEQUENCE:
this.value = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(in);
break;
case URI:
this.value = in.readTypedObject(Uri.CREATOR);
break;
case BITMAP:
this.value = in.readTypedObject(Bitmap.CREATOR);
break;
case BUNDLE:
// Because we use Parcel.allowSquashing() when writing, and that affects
// how the contents of Bundles are written, we need to ensure the bundle is
// unparceled immediately, not lazily. Setting a custom ReadWriteHelper
// just happens to have that effect on Bundle.readFromParcel().
// TODO(b/212731590): build this state tracking into Bundle
if (in.hasReadWriteHelper()) {
this.value = in.readBundle();
} else {
in.setReadWriteHelper(ALTERNATIVE_DEFAULT);
this.value = in.readBundle();
in.setReadWriteHelper(null);
}
break;
case INTENT:
this.value = in.readTypedObject(Intent.CREATOR);
break;
case COLOR_STATE_LIST:
this.value = in.readTypedObject(ColorStateList.CREATOR);
break;
case ICON:
this.value = in.readTypedObject(Icon.CREATOR);
break;
case BLEND_MODE:
this.value = BlendMode.fromValue(in.readInt());
break;
default:
break;
}
}
public void writeToParcel(Parcel out, int flags) {
super.writeToParcel(out, flags);
// For some values which are null, we record an integer flag to indicate whether
// we have written a valid value to the parcel.
switch (this.type) {
case BOOLEAN:
out.writeBoolean((Boolean) this.value);
break;
case BYTE:
out.writeByte((Byte) this.value);
break;
case SHORT:
out.writeInt((Short) this.value);
break;
case INT:
out.writeInt((Integer) this.value);
break;
case LONG:
out.writeLong((Long) this.value);
break;
case FLOAT:
out.writeFloat((Float) this.value);
break;
case DOUBLE:
out.writeDouble((Double) this.value);
break;
case CHAR:
out.writeInt((int) ((Character) this.value).charValue());
break;
case STRING:
out.writeString8((String) this.value);
break;
case CHAR_SEQUENCE:
TextUtils.writeToParcel((CharSequence) this.value, out, flags);
break;
case BUNDLE:
out.writeBundle((Bundle) this.value);
break;
case BLEND_MODE:
out.writeInt(BlendMode.toValue((BlendMode) this.value));
break;
case URI:
case BITMAP:
case INTENT:
case COLOR_STATE_LIST:
case ICON:
out.writeTypedObject((Parcelable) this.value, flags);
break;
default:
break;
}
}
@Nullable
@Override
protected Object getParameterValue(@Nullable View view) throws ActionException {
return this.value;
}
@Override
public int getActionTag() {
return REFLECTION_ACTION_TAG;
}
}
private final class ResourceReflectionAction extends BaseReflectionAction {
static final int DIMEN_RESOURCE = 1;
static final int COLOR_RESOURCE = 2;
static final int STRING_RESOURCE = 3;
private final int mResourceType;
private final int mResId;
ResourceReflectionAction(@IdRes int viewId, String methodName, int parameterType,
int resourceType, int resId) {
super(viewId, methodName, parameterType);
this.mResourceType = resourceType;
this.mResId = resId;
}
ResourceReflectionAction(Parcel in) {
super(in);
this.mResourceType = in.readInt();
this.mResId = in.readInt();
}
@Override
public void writeToParcel(Parcel dest, int flags) {
super.writeToParcel(dest, flags);
dest.writeInt(this.mResourceType);
dest.writeInt(this.mResId);
}
@Nullable
@Override
protected Object getParameterValue(@Nullable View view) throws ActionException {
if (view == null) return null;
Resources resources = view.getContext().getResources();
try {
switch (this.mResourceType) {
case DIMEN_RESOURCE:
switch (this.type) {
case BaseReflectionAction.INT:
return mResId == 0 ? 0 : resources.getDimensionPixelSize(mResId);
case BaseReflectionAction.FLOAT:
return mResId == 0 ? 0f : resources.getDimension(mResId);
default:
throw new ActionException(
"dimen resources must be used as INT or FLOAT, "
+ "not " + this.type);
}
case COLOR_RESOURCE:
switch (this.type) {
case BaseReflectionAction.INT:
return mResId == 0 ? 0 : view.getContext().getColor(mResId);
case BaseReflectionAction.COLOR_STATE_LIST:
return mResId == 0
? null : view.getContext().getColorStateList(mResId);
default:
throw new ActionException(
"color resources must be used as INT or COLOR_STATE_LIST,"
+ " not " + this.type);
}
case STRING_RESOURCE:
switch (this.type) {
case BaseReflectionAction.CHAR_SEQUENCE:
return mResId == 0 ? null : resources.getText(mResId);
case BaseReflectionAction.STRING:
return mResId == 0 ? null : resources.getString(mResId);
default:
throw new ActionException(
"string resources must be used as STRING or CHAR_SEQUENCE,"
+ " not " + this.type);
}
default:
throw new ActionException("unknown resource type: " + this.mResourceType);
}
} catch (ActionException ex) {
throw ex;
} catch (Throwable t) {
throw new ActionException(t);
}
}
@Override
public int getActionTag() {
return RESOURCE_REFLECTION_ACTION_TAG;
}
}
private final class AttributeReflectionAction extends BaseReflectionAction {
static final int DIMEN_RESOURCE = 1;
static final int COLOR_RESOURCE = 2;
static final int STRING_RESOURCE = 3;
private final int mResourceType;
private final int mAttrId;
AttributeReflectionAction(@IdRes int viewId, String methodName, int parameterType,
int resourceType, int attrId) {
super(viewId, methodName, parameterType);
this.mResourceType = resourceType;
this.mAttrId = attrId;
}
AttributeReflectionAction(Parcel in) {
super(in);
this.mResourceType = in.readInt();
this.mAttrId = in.readInt();
}
@Override
public void writeToParcel(Parcel dest, int flags) {
super.writeToParcel(dest, flags);
dest.writeInt(this.mResourceType);
dest.writeInt(this.mAttrId);
}
@Override
protected Object getParameterValue(View view) throws ActionException {
TypedArray typedArray = view.getContext().obtainStyledAttributes(new int[]{mAttrId});
try {
// When mAttrId == 0, we will depend on the default values below
if (mAttrId != 0 && typedArray.getType(0) == TypedValue.TYPE_NULL) {
throw new ActionException("Attribute 0x" + Integer.toHexString(this.mAttrId)
+ " is not defined");
}
switch (this.mResourceType) {
case DIMEN_RESOURCE:
switch (this.type) {
case BaseReflectionAction.INT:
return typedArray.getDimensionPixelSize(0, 0);
case BaseReflectionAction.FLOAT:
return typedArray.getDimension(0, 0);
default:
throw new ActionException(
"dimen attribute 0x" + Integer.toHexString(this.mAttrId)
+ " must be used as INT or FLOAT,"
+ " not " + this.type);
}
case COLOR_RESOURCE:
switch (this.type) {
case BaseReflectionAction.INT:
return typedArray.getColor(0, 0);
case BaseReflectionAction.COLOR_STATE_LIST:
return typedArray.getColorStateList(0);
default:
throw new ActionException(
"color attribute 0x" + Integer.toHexString(this.mAttrId)
+ " must be used as INT or COLOR_STATE_LIST,"
+ " not " + this.type);
}
case STRING_RESOURCE:
switch (this.type) {
case BaseReflectionAction.CHAR_SEQUENCE:
return typedArray.getText(0);
case BaseReflectionAction.STRING:
return typedArray.getString(0);
default:
throw new ActionException(
"string attribute 0x" + Integer.toHexString(this.mAttrId)
+ " must be used as STRING or CHAR_SEQUENCE,"
+ " not " + this.type);
}
default:
// Note: This can only be an implementation error.
throw new ActionException(
"Unknown resource type: " + this.mResourceType);
}
} catch (ActionException ex) {
throw ex;
} catch (Throwable t) {
throw new ActionException(t);
} finally {
typedArray.recycle();
}
}
@Override
public int getActionTag() {
return ATTRIBUTE_REFLECTION_ACTION_TAG;
}
}
private final class ComplexUnitDimensionReflectionAction extends BaseReflectionAction {
private final float mValue;
@ComplexDimensionUnit
private final int mUnit;
ComplexUnitDimensionReflectionAction(int viewId, String methodName, int parameterType,
float value, @ComplexDimensionUnit int unit) {
super(viewId, methodName, parameterType);
this.mValue = value;
this.mUnit = unit;
}
ComplexUnitDimensionReflectionAction(Parcel in) {
super(in);
this.mValue = in.readFloat();
this.mUnit = in.readInt();
}
@Override
public void writeToParcel(Parcel dest, int flags) {
super.writeToParcel(dest, flags);
dest.writeFloat(this.mValue);
dest.writeInt(this.mUnit);
}
@Nullable
@Override
protected Object getParameterValue(@Nullable View view) throws ActionException {
if (view == null) return null;
DisplayMetrics dm = view.getContext().getResources().getDisplayMetrics();
try {
int data = TypedValue.createComplexDimension(this.mValue, this.mUnit);
switch (this.type) {
case ReflectionAction.INT:
return TypedValue.complexToDimensionPixelSize(data, dm);
case ReflectionAction.FLOAT:
return TypedValue.complexToDimension(data, dm);
default:
throw new ActionException(
"parameter type must be INT or FLOAT, not " + this.type);
}
} catch (ActionException ex) {
throw ex;
} catch (Throwable t) {
throw new ActionException(t);
}
}
@Override
public int getActionTag() {
return COMPLEX_UNIT_DIMENSION_REFLECTION_ACTION_TAG;
}
}
private final class NightModeReflectionAction extends BaseReflectionAction {
private final Object mLightValue;
private final Object mDarkValue;
NightModeReflectionAction(
@IdRes int viewId,
String methodName,
int type,
Object lightValue,
Object darkValue) {
super(viewId, methodName, type);
mLightValue = lightValue;
mDarkValue = darkValue;
}
NightModeReflectionAction(Parcel in) {
super(in);
switch (this.type) {
case ICON:
mLightValue = in.readTypedObject(Icon.CREATOR);
mDarkValue = in.readTypedObject(Icon.CREATOR);
break;
case COLOR_STATE_LIST:
mLightValue = in.readTypedObject(ColorStateList.CREATOR);
mDarkValue = in.readTypedObject(ColorStateList.CREATOR);
break;
case INT:
mLightValue = in.readInt();
mDarkValue = in.readInt();
break;
default:
throw new ActionException("Unexpected night mode action type: " + this.type);
}
}
@Override
public void writeToParcel(Parcel out, int flags) {
super.writeToParcel(out, flags);
switch (this.type) {
case ICON:
case COLOR_STATE_LIST:
out.writeTypedObject((Parcelable) mLightValue, flags);
out.writeTypedObject((Parcelable) mDarkValue, flags);
break;
case INT:
out.writeInt((int) mLightValue);
out.writeInt((int) mDarkValue);
break;
}
}
@Nullable
@Override
protected Object getParameterValue(@Nullable View view) throws ActionException {
if (view == null) return null;
Configuration configuration = view.getResources().getConfiguration();
return configuration.isNightModeActive() ? mDarkValue : mLightValue;
}
@Override
public int getActionTag() {
return NIGHT_MODE_REFLECTION_ACTION_TAG;
}
}
/**
* This is only used for async execution of actions and it not parcelable.
*/
private static final class RunnableAction extends RuntimeAction {
private final Runnable mRunnable;
RunnableAction(Runnable r) {
mRunnable = r;
}
@Override
public void apply(View root, ViewGroup rootParent, ActionApplyParams params) {
mRunnable.run();
}
}
private static boolean hasStableId(View view) {
Object tag = view.getTag(com.android.internal.R.id.remote_views_stable_id);
return tag != null;
}
private static int getStableId(View view) {
Integer id = (Integer) view.getTag(com.android.internal.R.id.remote_views_stable_id);
return id == null ? ViewGroupActionAdd.NO_ID : id;
}
private static void setStableId(View view, int stableId) {
view.setTagInternal(com.android.internal.R.id.remote_views_stable_id, stableId);
}
// Returns the next recyclable child of the view group, or -1 if there are none.
private static int getNextRecyclableChild(ViewGroup vg) {
Integer tag = (Integer) vg.getTag(com.android.internal.R.id.remote_views_next_child);
return tag == null ? -1 : tag;
}
private static int getViewLayoutId(View v) {
return (Integer) v.getTag(R.id.widget_frame);
}
private static void setNextRecyclableChild(ViewGroup vg, int nextChild, int numChildren) {
if (nextChild < 0 || nextChild >= numChildren) {
vg.setTagInternal(com.android.internal.R.id.remote_views_next_child, -1);
} else {
vg.setTagInternal(com.android.internal.R.id.remote_views_next_child, nextChild);
}
}
private void finalizeViewRecycling(ViewGroup root) {
// Remove any recyclable children that were not used. nextChild should either be -1 or point
// to the next recyclable child that hasn't been recycled.
int nextChild = getNextRecyclableChild(root);
if (nextChild >= 0 && nextChild < root.getChildCount()) {
root.removeViews(nextChild, root.getChildCount() - nextChild);
}
// Make sure on the next round, we don't try to recycle if removeAllViews is not called.
setNextRecyclableChild(root, -1, 0);
// Traverse the view tree.
for (int i = 0; i < root.getChildCount(); i++) {
View child = root.getChildAt(i);
if (child instanceof ViewGroup && !child.isRootNamespace()) {
finalizeViewRecycling((ViewGroup) child);
}
}
}
/**
* ViewGroup methods that are related to adding Views.
*/
private class ViewGroupActionAdd extends Action {
static final int NO_ID = -1;
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
private RemoteViews mNestedViews;
private int mIndex;
private int mStableId;
ViewGroupActionAdd(@IdRes int viewId, RemoteViews nestedViews) {
this(viewId, nestedViews, -1 /* index */, NO_ID /* nestedViewId */);
}
ViewGroupActionAdd(@IdRes int viewId, RemoteViews nestedViews, int index) {
this(viewId, nestedViews, index, NO_ID /* nestedViewId */);
}
ViewGroupActionAdd(@IdRes int viewId, RemoteViews nestedViews, int index, int stableId) {
this.viewId = viewId;
mNestedViews = nestedViews;
mIndex = index;
mStableId = stableId;
nestedViews.configureAsChild(getHierarchyRootData());
}
ViewGroupActionAdd(Parcel parcel, ApplicationInfo info, int depth) {
viewId = parcel.readInt();
mIndex = parcel.readInt();
mStableId = parcel.readInt();
mNestedViews = new RemoteViews(parcel, getHierarchyRootData(), info, depth);
mNestedViews.addFlags(mApplyFlags);
}
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(viewId);
dest.writeInt(mIndex);
dest.writeInt(mStableId);
mNestedViews.writeToParcel(dest, flags);
}
@Override
public void setHierarchyRootData(HierarchyRootData root) {
mNestedViews.configureAsChild(root);
}
private int findViewIndexToRecycle(ViewGroup target, RemoteViews newContent) {
for (int nextChild = getNextRecyclableChild(target); nextChild < target.getChildCount();
nextChild++) {
View child = target.getChildAt(nextChild);
if (getStableId(child) == mStableId) {
return nextChild;
}
}
return -1;
}
@Override
public void apply(View root, ViewGroup rootParent, ActionApplyParams params) {
final Context context = root.getContext();
final ViewGroup target = root.findViewById(viewId);
if (target == null) {
return;
}
// If removeAllViews was called, this returns the next potential recycled view.
// If there are no more views to recycle (or removeAllViews was not called), this
// will return -1.
final int nextChild = getNextRecyclableChild(target);
RemoteViews rvToApply = mNestedViews.getRemoteViewsToApply(context);
int flagsToPropagate = mApplyFlags & FLAG_MASK_TO_PROPAGATE;
if (flagsToPropagate != 0) rvToApply.addFlags(flagsToPropagate);
if (nextChild >= 0 && mStableId != NO_ID) {
// At that point, the views starting at index nextChild are the ones recyclable but
// not yet recycled. All views added on that round of application are placed before.
// Find the next view with the same stable id, or -1.
int recycledViewIndex = findViewIndexToRecycle(target, rvToApply);
if (recycledViewIndex >= 0) {
View child = target.getChildAt(recycledViewIndex);
if (rvToApply.canRecycleView(child)) {
if (nextChild < recycledViewIndex) {
target.removeViews(nextChild, recycledViewIndex - nextChild);
}
setNextRecyclableChild(target, nextChild + 1, target.getChildCount());
rvToApply.reapplyNestedViews(context, child, rootParent, params);
return;
}
// If we cannot recycle the views, we still remove all views in between to
// avoid weird behaviors and insert the new view in place of the old one.
target.removeViews(nextChild, recycledViewIndex - nextChild + 1);
}
}
// If we cannot recycle, insert the new view before the next recyclable child.
// Inflate nested views and add as children
View nestedView = rvToApply.apply(context, target, rootParent, null /* size */, params);
if (mStableId != NO_ID) {
setStableId(nestedView, mStableId);
}
target.addView(nestedView, mIndex >= 0 ? mIndex : nextChild);
if (nextChild >= 0) {
// If we are at the end, there is no reason to try to recycle anymore
setNextRecyclableChild(target, nextChild + 1, target.getChildCount());
}
}
@Override
public Action initActionAsync(ViewTree root, ViewGroup rootParent,
ActionApplyParams params) {
// In the async implementation, update the view tree so that subsequent calls to
// findViewById return the current view.
root.createTree();
ViewTree target = root.findViewTreeById(viewId);
if ((target == null) || !(target.mRoot instanceof ViewGroup)) {
return ACTION_NOOP;
}
final ViewGroup targetVg = (ViewGroup) target.mRoot;
// Inflate nested views and perform all the async tasks for the child remoteView.
final Context context = root.mRoot.getContext();
// If removeAllViews was called, this returns the next potential recycled view.
// If there are no more views to recycle (or removeAllViews was not called), this
// will return -1.
final int nextChild = getNextRecyclableChild(targetVg);
if (nextChild >= 0 && mStableId != NO_ID) {
RemoteViews rvToApply = mNestedViews.getRemoteViewsToApply(context);
final int recycledViewIndex = target.findChildIndex(nextChild,
view -> getStableId(view) == mStableId);
if (recycledViewIndex >= 0) {
// At that point, the views starting at index nextChild are the ones
// recyclable but not yet recycled. All views added on that round of
// application are placed before.
ViewTree recycled = target.mChildren.get(recycledViewIndex);
// We can only recycle the view if the layout id is the same.
if (rvToApply.canRecycleView(recycled.mRoot)) {
if (recycledViewIndex > nextChild) {
target.removeChildren(nextChild, recycledViewIndex - nextChild);
}
setNextRecyclableChild(targetVg, nextChild + 1, target.mChildren.size());
final AsyncApplyTask reapplyTask = rvToApply.getInternalAsyncApplyTask(
context,
targetVg, null /* listener */, params, null /* size */,
recycled.mRoot);
final ViewTree tree = reapplyTask.doInBackground();
if (tree == null) {
throw new ActionException(reapplyTask.mError);
}
return new RuntimeAction() {
@Override
public void apply(View root, ViewGroup rootParent,
ActionApplyParams params) throws ActionException {
reapplyTask.onPostExecute(tree);
if (recycledViewIndex > nextChild) {
targetVg.removeViews(nextChild, recycledViewIndex - nextChild);
}
}
};
}
// If the layout id is different, still remove the children as if we recycled
// the view, to insert at the same place.
target.removeChildren(nextChild, recycledViewIndex - nextChild + 1);
return insertNewView(context, target, params,
() -> targetVg.removeViews(nextChild,
recycledViewIndex - nextChild + 1));
}
}
// If we cannot recycle, simply add the view at the same available slot.
return insertNewView(context, target, params, () -> {});
}
private Action insertNewView(Context context, ViewTree target,
ActionApplyParams params, Runnable finalizeAction) {
ViewGroup targetVg = (ViewGroup) target.mRoot;
int nextChild = getNextRecyclableChild(targetVg);
final AsyncApplyTask task = mNestedViews.getInternalAsyncApplyTask(context, targetVg,
null /* listener */, params, null /* size */, null /* result */);
final ViewTree tree = task.doInBackground();
if (tree == null) {
throw new ActionException(task.mError);
}
if (mStableId != NO_ID) {
setStableId(task.mResult, mStableId);
}
// Update the global view tree, so that next call to findViewTreeById
// goes through the subtree as well.
final int insertIndex = mIndex >= 0 ? mIndex : nextChild;
target.addChild(tree, insertIndex);
if (nextChild >= 0) {
setNextRecyclableChild(targetVg, nextChild + 1, target.mChildren.size());
}
return new RuntimeAction() {
@Override
public void apply(View root, ViewGroup rootParent, ActionApplyParams params) {
task.onPostExecute(tree);
finalizeAction.run();
targetVg.addView(task.mResult, insertIndex);
}
};
}
@Override
public int mergeBehavior() {
return MERGE_APPEND;
}
@Override
public boolean prefersAsyncApply() {
return mNestedViews.prefersAsyncApply();
}
@Override
public int getActionTag() {
return VIEW_GROUP_ACTION_ADD_TAG;
}
}
/**
* ViewGroup methods related to removing child views.
*/
private class ViewGroupActionRemove extends Action {
/**
* Id that indicates that all child views of the affected ViewGroup should be removed.
*
* <p>Using -2 because the default id is -1. This avoids accidentally matching that.
*/
private static final int REMOVE_ALL_VIEWS_ID = -2;
private int mViewIdToKeep;
ViewGroupActionRemove(@IdRes int viewId) {
this(viewId, REMOVE_ALL_VIEWS_ID);
}
ViewGroupActionRemove(@IdRes int viewId, @IdRes int viewIdToKeep) {
this.viewId = viewId;
mViewIdToKeep = viewIdToKeep;
}
ViewGroupActionRemove(Parcel parcel) {
viewId = parcel.readInt();
mViewIdToKeep = parcel.readInt();
}
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(viewId);
dest.writeInt(mViewIdToKeep);
}
@Override
public void apply(View root, ViewGroup rootParent, ActionApplyParams params) {
final ViewGroup target = root.findViewById(viewId);
if (target == null) {
return;
}
if (mViewIdToKeep == REMOVE_ALL_VIEWS_ID) {
// Remote any view without a stable id
for (int i = target.getChildCount() - 1; i >= 0; i--) {
if (!hasStableId(target.getChildAt(i))) {
target.removeViewAt(i);
}
}
// In the end, only children with a stable id (i.e. recyclable) are left.
setNextRecyclableChild(target, 0, target.getChildCount());
return;
}
removeAllViewsExceptIdToKeep(target);
}
@Override
public Action initActionAsync(ViewTree root, ViewGroup rootParent,
ActionApplyParams params) {
// In the async implementation, update the view tree so that subsequent calls to
// findViewById return the current view.
root.createTree();
ViewTree target = root.findViewTreeById(viewId);
if ((target == null) || !(target.mRoot instanceof ViewGroup)) {
return ACTION_NOOP;
}
final ViewGroup targetVg = (ViewGroup) target.mRoot;
if (mViewIdToKeep == REMOVE_ALL_VIEWS_ID) {
target.mChildren.removeIf(childTree -> !hasStableId(childTree.mRoot));
setNextRecyclableChild(targetVg, 0, target.mChildren.size());
} else {
// Remove just the children which don't match the excepted view
target.mChildren.removeIf(childTree -> childTree.mRoot.getId() != mViewIdToKeep);
if (target.mChildren.isEmpty()) {
target.mChildren = null;
}
}
return new RuntimeAction() {
@Override
public void apply(View root, ViewGroup rootParent, ActionApplyParams params) {
if (mViewIdToKeep == REMOVE_ALL_VIEWS_ID) {
for (int i = targetVg.getChildCount() - 1; i >= 0; i--) {
if (!hasStableId(targetVg.getChildAt(i))) {
targetVg.removeViewAt(i);
}
}
return;
}
removeAllViewsExceptIdToKeep(targetVg);
}
};
}
/**
* Iterates through the children in the given ViewGroup and removes all the views that
* do not have an id of {@link #mViewIdToKeep}.
*/
private void removeAllViewsExceptIdToKeep(ViewGroup viewGroup) {
// Otherwise, remove all the views that do not match the id to keep.
int index = viewGroup.getChildCount() - 1;
while (index >= 0) {
if (viewGroup.getChildAt(index).getId() != mViewIdToKeep) {
viewGroup.removeViewAt(index);
}
index--;
}
}
@Override
public int getActionTag() {
return VIEW_GROUP_ACTION_REMOVE_TAG;
}
@Override
public int mergeBehavior() {
return MERGE_APPEND;
}
}
/**
* Action to remove a view from its parent.
*/
private class RemoveFromParentAction extends Action {
RemoveFromParentAction(@IdRes int viewId) {
this.viewId = viewId;
}
RemoveFromParentAction(Parcel parcel) {
viewId = parcel.readInt();
}
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(viewId);
}
@Override
public void apply(View root, ViewGroup rootParent, ActionApplyParams params) {
final View target = root.findViewById(viewId);
if (target == null || target == root) {
return;
}
ViewParent parent = target.getParent();
if (parent instanceof ViewManager) {
((ViewManager) parent).removeView(target);
}
}
@Override
public Action initActionAsync(ViewTree root, ViewGroup rootParent,
ActionApplyParams params) {
// In the async implementation, update the view tree so that subsequent calls to
// findViewById return the correct view.
root.createTree();
ViewTree target = root.findViewTreeById(viewId);
if (target == null || target == root) {
return ACTION_NOOP;
}
ViewTree parent = root.findViewTreeParentOf(target);
if (parent == null || !(parent.mRoot instanceof ViewManager)) {
return ACTION_NOOP;
}
final ViewManager parentVg = (ViewManager) parent.mRoot;
parent.mChildren.remove(target);
return new RuntimeAction() {
@Override
public void apply(View root, ViewGroup rootParent, ActionApplyParams params) {
parentVg.removeView(target.mRoot);
}
};
}
@Override
public int getActionTag() {
return REMOVE_FROM_PARENT_ACTION_TAG;
}
@Override
public int mergeBehavior() {
return MERGE_APPEND;
}
}
/**
* Helper action to set compound drawables on a TextView. Supports relative
* (s/t/e/b) or cardinal (l/t/r/b) arrangement.
*/
private class TextViewDrawableAction extends Action {
public TextViewDrawableAction(@IdRes int viewId, boolean isRelative, @DrawableRes int d1,
@DrawableRes int d2, @DrawableRes int d3, @DrawableRes int d4) {
this.viewId = viewId;
this.isRelative = isRelative;
this.useIcons = false;
this.d1 = d1;
this.d2 = d2;
this.d3 = d3;
this.d4 = d4;
}
public TextViewDrawableAction(@IdRes int viewId, boolean isRelative,
Icon i1, Icon i2, Icon i3, Icon i4) {
this.viewId = viewId;
this.isRelative = isRelative;
this.useIcons = true;
this.i1 = i1;
this.i2 = i2;
this.i3 = i3;
this.i4 = i4;
}
public TextViewDrawableAction(Parcel parcel) {
viewId = parcel.readInt();
isRelative = (parcel.readInt() != 0);
useIcons = (parcel.readInt() != 0);
if (useIcons) {
i1 = parcel.readTypedObject(Icon.CREATOR);
i2 = parcel.readTypedObject(Icon.CREATOR);
i3 = parcel.readTypedObject(Icon.CREATOR);
i4 = parcel.readTypedObject(Icon.CREATOR);
} else {
d1 = parcel.readInt();
d2 = parcel.readInt();
d3 = parcel.readInt();
d4 = parcel.readInt();
}
}
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(viewId);
dest.writeInt(isRelative ? 1 : 0);
dest.writeInt(useIcons ? 1 : 0);
if (useIcons) {
dest.writeTypedObject(i1, 0);
dest.writeTypedObject(i2, 0);
dest.writeTypedObject(i3, 0);
dest.writeTypedObject(i4, 0);
} else {
dest.writeInt(d1);
dest.writeInt(d2);
dest.writeInt(d3);
dest.writeInt(d4);
}
}
@Override
public void apply(View root, ViewGroup rootParent, ActionApplyParams params) {
final TextView target = root.findViewById(viewId);
if (target == null) return;
if (drawablesLoaded) {
if (isRelative) {
target.setCompoundDrawablesRelativeWithIntrinsicBounds(id1, id2, id3, id4);
} else {
target.setCompoundDrawablesWithIntrinsicBounds(id1, id2, id3, id4);
}
} else if (useIcons) {
final Context ctx = target.getContext();
final Drawable id1 = i1 == null ? null : i1.loadDrawable(ctx);
final Drawable id2 = i2 == null ? null : i2.loadDrawable(ctx);
final Drawable id3 = i3 == null ? null : i3.loadDrawable(ctx);
final Drawable id4 = i4 == null ? null : i4.loadDrawable(ctx);
if (isRelative) {
target.setCompoundDrawablesRelativeWithIntrinsicBounds(id1, id2, id3, id4);
} else {
target.setCompoundDrawablesWithIntrinsicBounds(id1, id2, id3, id4);
}
} else {
if (isRelative) {
target.setCompoundDrawablesRelativeWithIntrinsicBounds(d1, d2, d3, d4);
} else {
target.setCompoundDrawablesWithIntrinsicBounds(d1, d2, d3, d4);
}
}
}
@Override
public Action initActionAsync(ViewTree root, ViewGroup rootParent,
ActionApplyParams params) {
final TextView target = root.findViewById(viewId);
if (target == null) return ACTION_NOOP;
TextViewDrawableAction copy = useIcons ?
new TextViewDrawableAction(viewId, isRelative, i1, i2, i3, i4) :
new TextViewDrawableAction(viewId, isRelative, d1, d2, d3, d4);
// Load the drawables on the background thread.
copy.drawablesLoaded = true;
final Context ctx = target.getContext();
if (useIcons) {
copy.id1 = i1 == null ? null : i1.loadDrawable(ctx);
copy.id2 = i2 == null ? null : i2.loadDrawable(ctx);
copy.id3 = i3 == null ? null : i3.loadDrawable(ctx);
copy.id4 = i4 == null ? null : i4.loadDrawable(ctx);
} else {
copy.id1 = d1 == 0 ? null : ctx.getDrawable(d1);
copy.id2 = d2 == 0 ? null : ctx.getDrawable(d2);
copy.id3 = d3 == 0 ? null : ctx.getDrawable(d3);
copy.id4 = d4 == 0 ? null : ctx.getDrawable(d4);
}
return copy;
}
@Override
public boolean prefersAsyncApply() {
return useIcons;
}
@Override
public int getActionTag() {
return TEXT_VIEW_DRAWABLE_ACTION_TAG;
}
@Override
public void visitUris(@NonNull Consumer<Uri> visitor) {
if (useIcons) {
visitIconUri(i1, visitor);
visitIconUri(i2, visitor);
visitIconUri(i3, visitor);
visitIconUri(i4, visitor);
}
}
boolean isRelative = false;
boolean useIcons = false;
int d1, d2, d3, d4;
Icon i1, i2, i3, i4;
boolean drawablesLoaded = false;
Drawable id1, id2, id3, id4;
}
/**
* Helper action to set text size on a TextView in any supported units.
*/
private class TextViewSizeAction extends Action {
TextViewSizeAction(@IdRes int viewId, @ComplexDimensionUnit int units, float size) {
this.viewId = viewId;
this.units = units;
this.size = size;
}
TextViewSizeAction(Parcel parcel) {
viewId = parcel.readInt();
units = parcel.readInt();
size = parcel.readFloat();
}
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(viewId);
dest.writeInt(units);
dest.writeFloat(size);
}
@Override
public void apply(View root, ViewGroup rootParent, ActionApplyParams params) {
final TextView target = root.findViewById(viewId);
if (target == null) return;
target.setTextSize(units, size);
}
@Override
public int getActionTag() {
return TEXT_VIEW_SIZE_ACTION_TAG;
}
int units;
float size;
}
/**
* Helper action to set padding on a View.
*/
private class ViewPaddingAction extends Action {
public ViewPaddingAction(@IdRes int viewId, @Px int left, @Px int top,
@Px int right, @Px int bottom) {
this.viewId = viewId;
this.left = left;
this.top = top;
this.right = right;
this.bottom = bottom;
}
public ViewPaddingAction(Parcel parcel) {
viewId = parcel.readInt();
left = parcel.readInt();
top = parcel.readInt();
right = parcel.readInt();
bottom = parcel.readInt();
}
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(viewId);
dest.writeInt(left);
dest.writeInt(top);
dest.writeInt(right);
dest.writeInt(bottom);
}
@Override
public void apply(View root, ViewGroup rootParent, ActionApplyParams params) {
final View target = root.findViewById(viewId);
if (target == null) return;
target.setPadding(left, top, right, bottom);
}
@Override
public int getActionTag() {
return VIEW_PADDING_ACTION_TAG;
}
@Px int left, top, right, bottom;
}
/**
* Helper action to set layout params on a View.
*/
private static class LayoutParamAction extends Action {
static final int LAYOUT_MARGIN_LEFT = MARGIN_LEFT;
static final int LAYOUT_MARGIN_TOP = MARGIN_TOP;
static final int LAYOUT_MARGIN_RIGHT = MARGIN_RIGHT;
static final int LAYOUT_MARGIN_BOTTOM = MARGIN_BOTTOM;
static final int LAYOUT_MARGIN_START = MARGIN_START;
static final int LAYOUT_MARGIN_END = MARGIN_END;
static final int LAYOUT_WIDTH = 8;
static final int LAYOUT_HEIGHT = 9;
final int mProperty;
final int mValueType;
final int mValue;
/**
* @param viewId ID of the view alter
* @param property which layout parameter to alter
* @param value new value of the layout parameter
* @param units the units of the given value
*/
LayoutParamAction(@IdRes int viewId, int property, float value,
@ComplexDimensionUnit int units) {
this.viewId = viewId;
this.mProperty = property;
this.mValueType = VALUE_TYPE_COMPLEX_UNIT;
this.mValue = TypedValue.createComplexDimension(value, units);
}
/**
* @param viewId ID of the view alter
* @param property which layout parameter to alter
* @param value value to set.
* @param valueType must be one of {@link #VALUE_TYPE_COMPLEX_UNIT},
* {@link #VALUE_TYPE_RESOURCE}, {@link #VALUE_TYPE_ATTRIBUTE} or
* {@link #VALUE_TYPE_RAW}.
*/
LayoutParamAction(@IdRes int viewId, int property, int value, @ValueType int valueType) {
this.viewId = viewId;
this.mProperty = property;
this.mValueType = valueType;
this.mValue = value;
}
public LayoutParamAction(Parcel parcel) {
viewId = parcel.readInt();
mProperty = parcel.readInt();
mValueType = parcel.readInt();
mValue = parcel.readInt();
}
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(viewId);
dest.writeInt(mProperty);
dest.writeInt(mValueType);
dest.writeInt(mValue);
}
@Override
public void apply(View root, ViewGroup rootParent, ActionApplyParams params) {
final View target = root.findViewById(viewId);
if (target == null) {
return;
}
ViewGroup.LayoutParams layoutParams = target.getLayoutParams();
if (layoutParams == null) {
return;
}
switch (mProperty) {
case LAYOUT_MARGIN_LEFT:
if (layoutParams instanceof MarginLayoutParams) {
((MarginLayoutParams) layoutParams).leftMargin = getPixelOffset(target);
target.setLayoutParams(layoutParams);
}
break;
case LAYOUT_MARGIN_TOP:
if (layoutParams instanceof MarginLayoutParams) {
((MarginLayoutParams) layoutParams).topMargin = getPixelOffset(target);
target.setLayoutParams(layoutParams);
}
break;
case LAYOUT_MARGIN_RIGHT:
if (layoutParams instanceof MarginLayoutParams) {
((MarginLayoutParams) layoutParams).rightMargin = getPixelOffset(target);
target.setLayoutParams(layoutParams);
}
break;
case LAYOUT_MARGIN_BOTTOM:
if (layoutParams instanceof MarginLayoutParams) {
((MarginLayoutParams) layoutParams).bottomMargin = getPixelOffset(target);
target.setLayoutParams(layoutParams);
}
break;
case LAYOUT_MARGIN_START:
if (layoutParams instanceof MarginLayoutParams) {
((MarginLayoutParams) layoutParams).setMarginStart(getPixelOffset(target));
target.setLayoutParams(layoutParams);
}
break;
case LAYOUT_MARGIN_END:
if (layoutParams instanceof MarginLayoutParams) {
((MarginLayoutParams) layoutParams).setMarginEnd(getPixelOffset(target));
target.setLayoutParams(layoutParams);
}
break;
case LAYOUT_WIDTH:
layoutParams.width = getPixelSize(target);
target.setLayoutParams(layoutParams);
break;
case LAYOUT_HEIGHT:
layoutParams.height = getPixelSize(target);
target.setLayoutParams(layoutParams);
break;
default:
throw new IllegalArgumentException("Unknown property " + mProperty);
}
}
private int getPixelOffset(View target) {
try {
switch (mValueType) {
case VALUE_TYPE_ATTRIBUTE:
TypedArray typedArray = target.getContext().obtainStyledAttributes(
new int[]{this.mValue});
try {
return typedArray.getDimensionPixelOffset(0, 0);
} finally {
typedArray.recycle();
}
case VALUE_TYPE_RESOURCE:
if (mValue == 0) {
return 0;
}
return target.getResources().getDimensionPixelOffset(mValue);
case VALUE_TYPE_COMPLEX_UNIT:
return TypedValue.complexToDimensionPixelOffset(mValue,
target.getResources().getDisplayMetrics());
default:
return mValue;
}
} catch (Throwable t) {
throw new ActionException(t);
}
}
private int getPixelSize(View target) {
try {
switch (mValueType) {
case VALUE_TYPE_ATTRIBUTE:
TypedArray typedArray = target.getContext().obtainStyledAttributes(
new int[]{this.mValue});
try {
return typedArray.getDimensionPixelSize(0, 0);
} finally {
typedArray.recycle();
}
case VALUE_TYPE_RESOURCE:
if (mValue == 0) {
return 0;
}
return target.getResources().getDimensionPixelSize(mValue);
case VALUE_TYPE_COMPLEX_UNIT:
return TypedValue.complexToDimensionPixelSize(mValue,
target.getResources().getDisplayMetrics());
default:
return mValue;
}
} catch (Throwable t) {
throw new ActionException(t);
}
}
@Override
public int getActionTag() {
return LAYOUT_PARAM_ACTION_TAG;
}
@Override
public String getUniqueKey() {
return super.getUniqueKey() + mProperty;
}
}
/**
* Helper action to add a view tag with RemoteInputs.
*/
private class SetRemoteInputsAction extends Action {
public SetRemoteInputsAction(@IdRes int viewId, RemoteInput[] remoteInputs) {
this.viewId = viewId;
this.remoteInputs = remoteInputs;
}
public SetRemoteInputsAction(Parcel parcel) {
viewId = parcel.readInt();
remoteInputs = parcel.createTypedArray(RemoteInput.CREATOR);
}
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(viewId);
dest.writeTypedArray(remoteInputs, flags);
}
@Override
public void apply(View root, ViewGroup rootParent, ActionApplyParams params) {
final View target = root.findViewById(viewId);
if (target == null) return;
target.setTagInternal(R.id.remote_input_tag, remoteInputs);
}
@Override
public int getActionTag() {
return SET_REMOTE_INPUTS_ACTION_TAG;
}
final Parcelable[] remoteInputs;
}
/**
* Helper action to override all textViewColors
*/
private class OverrideTextColorsAction extends Action {
private final int textColor;
public OverrideTextColorsAction(int textColor) {
this.textColor = textColor;
}
public OverrideTextColorsAction(Parcel parcel) {
textColor = parcel.readInt();
}
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(textColor);
}
@Override
public void apply(View root, ViewGroup rootParent, ActionApplyParams params) {
// Let's traverse the viewtree and override all textColors!
Stack<View> viewsToProcess = new Stack<>();
viewsToProcess.add(root);
while (!viewsToProcess.isEmpty()) {
View v = viewsToProcess.pop();
if (v instanceof TextView) {
TextView textView = (TextView) v;
textView.setText(ContrastColorUtil.clearColorSpans(textView.getText()));
textView.setTextColor(textColor);
}
if (v instanceof ViewGroup) {
ViewGroup viewGroup = (ViewGroup) v;
for (int i = 0; i < viewGroup.getChildCount(); i++) {
viewsToProcess.push(viewGroup.getChildAt(i));
}
}
}
}
@Override
public int getActionTag() {
return OVERRIDE_TEXT_COLORS_TAG;
}
}
private class SetIntTagAction extends Action {
@IdRes private final int mViewId;
@IdRes private final int mKey;
private final int mTag;
SetIntTagAction(@IdRes int viewId, @IdRes int key, int tag) {
mViewId = viewId;
mKey = key;
mTag = tag;
}
SetIntTagAction(Parcel parcel) {
mViewId = parcel.readInt();
mKey = parcel.readInt();
mTag = parcel.readInt();
}
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(mViewId);
dest.writeInt(mKey);
dest.writeInt(mTag);
}
@Override
public void apply(View root, ViewGroup rootParent, ActionApplyParams params) {
final View target = root.findViewById(mViewId);
if (target == null) return;
target.setTagInternal(mKey, mTag);
}
@Override
public int getActionTag() {
return SET_INT_TAG_TAG;
}
}
private static class SetCompoundButtonCheckedAction extends Action {
private final boolean mChecked;
SetCompoundButtonCheckedAction(@IdRes int viewId, boolean checked) {
this.viewId = viewId;
mChecked = checked;
}
SetCompoundButtonCheckedAction(Parcel in) {
viewId = in.readInt();
mChecked = in.readBoolean();
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(viewId);
dest.writeBoolean(mChecked);
}
@Override
public void apply(View root, ViewGroup rootParent, ActionApplyParams params)
throws ActionException {
final View target = root.findViewById(viewId);
if (target == null) return;
if (!(target instanceof CompoundButton)) {
Log.w(LOG_TAG, "Cannot set checked to view "
+ viewId + " because it is not a CompoundButton");
return;
}
CompoundButton button = (CompoundButton) target;
Object tag = button.getTag(R.id.remote_checked_change_listener_tag);
// Temporarily unset the checked change listener so calling setChecked doesn't launch
// the intent.
if (tag instanceof OnCheckedChangeListener) {
button.setOnCheckedChangeListener(null);
button.setChecked(mChecked);
button.setOnCheckedChangeListener((OnCheckedChangeListener) tag);
} else {
button.setChecked(mChecked);
}
}
@Override
public int getActionTag() {
return SET_COMPOUND_BUTTON_CHECKED_TAG;
}
}
private static class SetRadioGroupCheckedAction extends Action {
@IdRes private final int mCheckedId;
SetRadioGroupCheckedAction(@IdRes int viewId, @IdRes int checkedId) {
this.viewId = viewId;
mCheckedId = checkedId;
}
SetRadioGroupCheckedAction(Parcel in) {
viewId = in.readInt();
mCheckedId = in.readInt();
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(viewId);
dest.writeInt(mCheckedId);
}
@Override
public void apply(View root, ViewGroup rootParent, ActionApplyParams params)
throws ActionException {
final View target = root.findViewById(viewId);
if (target == null) return;
if (!(target instanceof RadioGroup)) {
Log.w(LOG_TAG, "Cannot check " + viewId + " because it's not a RadioGroup");
return;
}
RadioGroup group = (RadioGroup) target;
// Temporarily unset all the checked change listeners while we check the group.
for (int i = 0; i < group.getChildCount(); i++) {
View child = group.getChildAt(i);
if (!(child instanceof CompoundButton)) continue;
Object tag = child.getTag(R.id.remote_checked_change_listener_tag);
if (!(tag instanceof OnCheckedChangeListener)) continue;
// Clear the checked change listener, we'll restore it after the check.
((CompoundButton) child).setOnCheckedChangeListener(null);
}
group.check(mCheckedId);
// Loop through the children again and restore the checked change listeners.
for (int i = 0; i < group.getChildCount(); i++) {
View child = group.getChildAt(i);
if (!(child instanceof CompoundButton)) continue;
Object tag = child.getTag(R.id.remote_checked_change_listener_tag);
if (!(tag instanceof OnCheckedChangeListener)) continue;
((CompoundButton) child).setOnCheckedChangeListener((OnCheckedChangeListener) tag);
}
}
@Override
public int getActionTag() {
return SET_RADIO_GROUP_CHECKED;
}
}
private static class SetViewOutlinePreferredRadiusAction extends Action {
@ValueType
private final int mValueType;
private final int mValue;
SetViewOutlinePreferredRadiusAction(@IdRes int viewId, int value,
@ValueType int valueType) {
this.viewId = viewId;
this.mValueType = valueType;
this.mValue = value;
}
SetViewOutlinePreferredRadiusAction(
@IdRes int viewId, float radius, @ComplexDimensionUnit int units) {
this.viewId = viewId;
this.mValueType = VALUE_TYPE_COMPLEX_UNIT;
this.mValue = TypedValue.createComplexDimension(radius, units);
}
SetViewOutlinePreferredRadiusAction(Parcel in) {
viewId = in.readInt();
mValueType = in.readInt();
mValue = in.readInt();
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(viewId);
dest.writeInt(mValueType);
dest.writeInt(mValue);
}
@Override
public void apply(View root, ViewGroup rootParent, ActionApplyParams params)
throws ActionException {
final View target = root.findViewById(viewId);
if (target == null) return;
try {
float radius;
switch (mValueType) {
case VALUE_TYPE_ATTRIBUTE:
TypedArray typedArray = target.getContext().obtainStyledAttributes(
new int[]{mValue});
try {
radius = typedArray.getDimension(0, 0);
} finally {
typedArray.recycle();
}
break;
case VALUE_TYPE_RESOURCE:
radius = mValue == 0 ? 0 : target.getResources().getDimension(mValue);
break;
case VALUE_TYPE_COMPLEX_UNIT:
radius = TypedValue.complexToDimension(mValue,
target.getResources().getDisplayMetrics());
break;
default:
radius = mValue;
}
target.setOutlineProvider(new RemoteViewOutlineProvider(radius));
} catch (Throwable t) {
throw new ActionException(t);
}
}
@Override
public int getActionTag() {
return SET_VIEW_OUTLINE_RADIUS_TAG;
}
}
/**
* OutlineProvider for a view with a radius set by
* {@link #setViewOutlinePreferredRadius(int, float, int)}.
*/
public static final class RemoteViewOutlineProvider extends ViewOutlineProvider {
private final float mRadius;
public RemoteViewOutlineProvider(float radius) {
mRadius = radius;
}
/** Returns the corner radius used when providing the view outline. */
public float getRadius() {
return mRadius;
}
@Override
public void getOutline(@NonNull View view, @NonNull Outline outline) {
outline.setRoundRect(
0 /*left*/,
0 /* top */,
view.getWidth() /* right */,
view.getHeight() /* bottom */,
mRadius);
}
}
/**
* Create a new RemoteViews object that will display the views contained
* in the specified layout file.
*
* @param packageName Name of the package that contains the layout resource
* @param layoutId The id of the layout resource
*/
public RemoteViews(String packageName, int layoutId) {
this(getApplicationInfo(packageName, UserHandle.myUserId()), layoutId);
}
/**
* Create a new RemoteViews object that will display the views contained
* in the specified layout file and change the id of the root view to the specified one.
*
* @param packageName Name of the package that contains the layout resource
* @param layoutId The id of the layout resource
*/
public RemoteViews(@NonNull String packageName, @LayoutRes int layoutId, @IdRes int viewId) {
this(packageName, layoutId);
this.mViewId = viewId;
}
/**
* Create a new RemoteViews object that will display the views contained
* in the specified layout file.
*
* @param application The application whose content is shown by the views.
* @param layoutId The id of the layout resource.
*
* @hide
*/
protected RemoteViews(ApplicationInfo application, @LayoutRes int layoutId) {
mApplication = application;
mLayoutId = layoutId;
mApplicationInfoCache.put(application);
}
private boolean hasMultipleLayouts() {
return hasLandscapeAndPortraitLayouts() || hasSizedRemoteViews();
}
private boolean hasLandscapeAndPortraitLayouts() {
return (mLandscape != null) && (mPortrait != null);
}
private boolean hasSizedRemoteViews() {
return mSizedRemoteViews != null;
}
private @Nullable SizeF getIdealSize() {
return mIdealSize;
}
private void setIdealSize(@Nullable SizeF size) {
mIdealSize = size;
}
/**
* Finds the smallest view in {@code mSizedRemoteViews}.
* This method must not be called if {@code mSizedRemoteViews} is null.
*/
private RemoteViews findSmallestRemoteView() {
return mSizedRemoteViews.get(mSizedRemoteViews.size() - 1);
}
/**
* Create a new RemoteViews object that will inflate as the specified
* landspace or portrait RemoteViews, depending on the current configuration.
*
* @param landscape The RemoteViews to inflate in landscape configuration
* @param portrait The RemoteViews to inflate in portrait configuration
* @throws IllegalArgumentException if either landscape or portrait are null or if they are
* not from the same application
*/
public RemoteViews(RemoteViews landscape, RemoteViews portrait) {
if (landscape == null || portrait == null) {
throw new IllegalArgumentException("Both RemoteViews must be non-null");
}
if (!landscape.hasSameAppInfo(portrait.mApplication)) {
throw new IllegalArgumentException(
"Both RemoteViews must share the same package and user");
}
mApplication = portrait.mApplication;
mLayoutId = portrait.mLayoutId;
mViewId = portrait.mViewId;
mLightBackgroundLayoutId = portrait.mLightBackgroundLayoutId;
mLandscape = landscape;
mPortrait = portrait;
mClassCookies = (portrait.mClassCookies != null)
? portrait.mClassCookies : landscape.mClassCookies;
configureDescendantsAsChildren();
}
/**
* Create a new RemoteViews object that will inflate the layout with the closest size
* specification.
*
* The default remote views in that case is always the one with the smallest area.
*
* If the {@link RemoteViews} host provides the size of the view, the layout with the largest
* area that fits entirely in the provided size will be used (i.e. the width and height of
* the layout must be less than the size of the view, with a 1dp margin to account for
* rounding). If no layout fits in the view, the layout with the smallest area will be used.
*
* @param remoteViews Mapping of size to layout.
* @throws IllegalArgumentException if the map is empty, there are more than
* MAX_INIT_VIEW_COUNT layouts or the remote views are not all from the same application.
*/
public RemoteViews(@NonNull Map<SizeF, RemoteViews> remoteViews) {
if (remoteViews.isEmpty()) {
throw new IllegalArgumentException("The set of RemoteViews cannot be empty");
}
if (remoteViews.size() > MAX_INIT_VIEW_COUNT) {
throw new IllegalArgumentException("Too many RemoteViews in constructor");
}
if (remoteViews.size() == 1) {
// If the map only contains a single mapping, treat this as if that RemoteViews was
// passed as the top-level RemoteViews.
RemoteViews single = remoteViews.values().iterator().next();
initializeFrom(single, /* hierarchyRoot= */ single);
return;
}
mClassCookies = initializeSizedRemoteViews(
remoteViews.entrySet().stream().map(
entry -> {
entry.getValue().setIdealSize(entry.getKey());
return entry.getValue();
}
).iterator()
);
RemoteViews smallestView = findSmallestRemoteView();
mApplication = smallestView.mApplication;
mLayoutId = smallestView.mLayoutId;
mViewId = smallestView.mViewId;
mLightBackgroundLayoutId = smallestView.mLightBackgroundLayoutId;
configureDescendantsAsChildren();
}
// Initialize mSizedRemoteViews and return the class cookies.
private Map<Class, Object> initializeSizedRemoteViews(Iterator<RemoteViews> remoteViews) {
List<RemoteViews> sizedRemoteViews = new ArrayList<>();
Map<Class, Object> classCookies = null;
float viewArea = Float.MAX_VALUE;
RemoteViews smallestView = null;
while (remoteViews.hasNext()) {
RemoteViews view = remoteViews.next();
SizeF size = view.getIdealSize();
if (size == null) {
throw new IllegalStateException("Expected RemoteViews to have ideal size");
}
float newViewArea = size.getWidth() * size.getHeight();
if (smallestView != null && !view.hasSameAppInfo(smallestView.mApplication)) {
throw new IllegalArgumentException(
"All RemoteViews must share the same package and user");
}
if (smallestView == null || newViewArea < viewArea) {
if (smallestView != null) {
sizedRemoteViews.add(smallestView);
}
viewArea = newViewArea;
smallestView = view;
} else {
sizedRemoteViews.add(view);
}
view.setIdealSize(size);
if (classCookies == null) {
classCookies = view.mClassCookies;
}
}
sizedRemoteViews.add(smallestView);
mSizedRemoteViews = sizedRemoteViews;
return classCookies;
}
/**
* Creates a copy of another RemoteViews.
*/
public RemoteViews(RemoteViews src) {
initializeFrom(src, /* hierarchyRoot= */ null);
}
/**
* No-arg constructor for use with {@link #initializeFrom(RemoteViews, RemoteViews)}. A
* constructor taking two RemoteViews parameters would clash with the landscape/portrait
* constructor.
*/
private RemoteViews() {}
private static RemoteViews createInitializedFrom(@NonNull RemoteViews src,
@Nullable RemoteViews hierarchyRoot) {
RemoteViews child = new RemoteViews();
child.initializeFrom(src, hierarchyRoot);
return child;
}
private void initializeFrom(@NonNull RemoteViews src, @Nullable RemoteViews hierarchyRoot) {
if (hierarchyRoot == null) {
mBitmapCache = src.mBitmapCache;
mApplicationInfoCache = src.mApplicationInfoCache;
} else {
mBitmapCache = hierarchyRoot.mBitmapCache;
mApplicationInfoCache = hierarchyRoot.mApplicationInfoCache;
}
if (hierarchyRoot == null || src.mIsRoot) {
// If there's no provided root, or if src was itself a root, then this RemoteViews is
// the root of the new hierarchy.
mIsRoot = true;
hierarchyRoot = this;
} else {
// Otherwise, we're a descendant in the hierarchy.
mIsRoot = false;
}
mApplication = src.mApplication;
mLayoutId = src.mLayoutId;
mLightBackgroundLayoutId = src.mLightBackgroundLayoutId;
mApplyFlags = src.mApplyFlags;
mClassCookies = src.mClassCookies;
mIdealSize = src.mIdealSize;
mProviderInstanceId = src.mProviderInstanceId;
if (src.hasLandscapeAndPortraitLayouts()) {
mLandscape = createInitializedFrom(src.mLandscape, hierarchyRoot);
mPortrait = createInitializedFrom(src.mPortrait, hierarchyRoot);
}
if (src.hasSizedRemoteViews()) {
mSizedRemoteViews = new ArrayList<>(src.mSizedRemoteViews.size());
for (RemoteViews srcView : src.mSizedRemoteViews) {
mSizedRemoteViews.add(createInitializedFrom(srcView, hierarchyRoot));
}
}
if (src.mActions != null) {
Parcel p = Parcel.obtain();
p.putClassCookies(mClassCookies);
src.writeActionsToParcel(p, /* flags= */ 0);
p.setDataPosition(0);
// Since src is already in memory, we do not care about stack overflow as it has
// already been read once.
readActionsFromParcel(p, 0);
p.recycle();
}
// Now that everything is initialized and duplicated, create new caches for this
// RemoteViews and recursively set up all descendants.
if (mIsRoot) {
reconstructCaches();
}
}
/**
* Reads a RemoteViews object from a parcel.
*
* @param parcel
*/
public RemoteViews(Parcel parcel) {
this(parcel, /* rootData= */ null, /* info= */ null, /* depth= */ 0);
}
private RemoteViews(@NonNull Parcel parcel, @Nullable HierarchyRootData rootData,
@Nullable ApplicationInfo info, int depth) {
if (depth > MAX_NESTED_VIEWS
&& (UserHandle.getAppId(Binder.getCallingUid()) != Process.SYSTEM_UID)) {
throw new IllegalArgumentException("Too many nested views.");
}
depth++;
int mode = parcel.readInt();
if (rootData == null) {
// We only store a bitmap cache in the root of the RemoteViews.
mBitmapCache = new BitmapCache(parcel);
// Store the class cookies such that they are available when we clone this RemoteView.
mClassCookies = parcel.copyClassCookies();
} else {
configureAsChild(rootData);
}
if (mode == MODE_NORMAL) {
mApplication = ApplicationInfo.CREATOR.createFromParcel(parcel);
mIdealSize = parcel.readInt() == 0 ? null : SizeF.CREATOR.createFromParcel(parcel);
mLayoutId = parcel.readInt();
mViewId = parcel.readInt();
mLightBackgroundLayoutId = parcel.readInt();
readActionsFromParcel(parcel, depth);
} else if (mode == MODE_HAS_SIZED_REMOTEVIEWS) {
int numViews = parcel.readInt();
if (numViews > MAX_INIT_VIEW_COUNT) {
throw new IllegalArgumentException(
"Too many views in mapping from size to RemoteViews.");
}
List<RemoteViews> remoteViews = new ArrayList<>(numViews);
for (int i = 0; i < numViews; i++) {
RemoteViews view = new RemoteViews(parcel, getHierarchyRootData(), info, depth);
info = view.mApplication;
remoteViews.add(view);
}
initializeSizedRemoteViews(remoteViews.iterator());
RemoteViews smallestView = findSmallestRemoteView();
mApplication = smallestView.mApplication;
mLayoutId = smallestView.mLayoutId;
mViewId = smallestView.mViewId;
mLightBackgroundLayoutId = smallestView.mLightBackgroundLayoutId;
} else {
// MODE_HAS_LANDSCAPE_AND_PORTRAIT
mLandscape = new RemoteViews(parcel, getHierarchyRootData(), info, depth);
mPortrait =
new RemoteViews(parcel, getHierarchyRootData(), mLandscape.mApplication, depth);
mApplication = mPortrait.mApplication;
mLayoutId = mPortrait.mLayoutId;
mViewId = mPortrait.mViewId;
mLightBackgroundLayoutId = mPortrait.mLightBackgroundLayoutId;
}
mApplyFlags = parcel.readInt();
mProviderInstanceId = parcel.readLong();
// Ensure that all descendants have their caches set up recursively.
if (mIsRoot) {
configureDescendantsAsChildren();
}
}
private void readActionsFromParcel(Parcel parcel, int depth) {
int count = parcel.readInt();
if (count > 0) {
mActions = new ArrayList<>(count);
for (int i = 0; i < count; i++) {
mActions.add(getActionFromParcel(parcel, depth));
}
}
}
private Action getActionFromParcel(Parcel parcel, int depth) {
int tag = parcel.readInt();
switch (tag) {
case SET_ON_CLICK_RESPONSE_TAG:
return new SetOnClickResponse(parcel);
case SET_DRAWABLE_TINT_TAG:
return new SetDrawableTint(parcel);
case REFLECTION_ACTION_TAG:
return new ReflectionAction(parcel);
case VIEW_GROUP_ACTION_ADD_TAG:
return new ViewGroupActionAdd(parcel, mApplication, depth);
case VIEW_GROUP_ACTION_REMOVE_TAG:
return new ViewGroupActionRemove(parcel);
case VIEW_CONTENT_NAVIGATION_TAG:
return new ViewContentNavigation(parcel);
case SET_EMPTY_VIEW_ACTION_TAG:
return new SetEmptyView(parcel);
case SET_PENDING_INTENT_TEMPLATE_TAG:
return new SetPendingIntentTemplate(parcel);
case SET_REMOTE_VIEW_ADAPTER_INTENT_TAG:
return new SetRemoteViewsAdapterIntent(parcel);
case TEXT_VIEW_DRAWABLE_ACTION_TAG:
return new TextViewDrawableAction(parcel);
case TEXT_VIEW_SIZE_ACTION_TAG:
return new TextViewSizeAction(parcel);
case VIEW_PADDING_ACTION_TAG:
return new ViewPaddingAction(parcel);
case BITMAP_REFLECTION_ACTION_TAG:
return new BitmapReflectionAction(parcel);
case SET_REMOTE_VIEW_ADAPTER_LIST_TAG:
return new SetRemoteViewsAdapterList(parcel);
case SET_REMOTE_INPUTS_ACTION_TAG:
return new SetRemoteInputsAction(parcel);
case LAYOUT_PARAM_ACTION_TAG:
return new LayoutParamAction(parcel);
case OVERRIDE_TEXT_COLORS_TAG:
return new OverrideTextColorsAction(parcel);
case SET_RIPPLE_DRAWABLE_COLOR_TAG:
return new SetRippleDrawableColor(parcel);
case SET_INT_TAG_TAG:
return new SetIntTagAction(parcel);
case REMOVE_FROM_PARENT_ACTION_TAG:
return new RemoveFromParentAction(parcel);
case RESOURCE_REFLECTION_ACTION_TAG:
return new ResourceReflectionAction(parcel);
case COMPLEX_UNIT_DIMENSION_REFLECTION_ACTION_TAG:
return new ComplexUnitDimensionReflectionAction(parcel);
case SET_COMPOUND_BUTTON_CHECKED_TAG:
return new SetCompoundButtonCheckedAction(parcel);
case SET_RADIO_GROUP_CHECKED:
return new SetRadioGroupCheckedAction(parcel);
case SET_VIEW_OUTLINE_RADIUS_TAG:
return new SetViewOutlinePreferredRadiusAction(parcel);
case SET_ON_CHECKED_CHANGE_RESPONSE_TAG:
return new SetOnCheckedChangeResponse(parcel);
case NIGHT_MODE_REFLECTION_ACTION_TAG:
return new NightModeReflectionAction(parcel);
case SET_REMOTE_COLLECTION_ITEMS_ADAPTER_TAG:
return new SetRemoteCollectionItemListAdapterAction(parcel);
case ATTRIBUTE_REFLECTION_ACTION_TAG:
return new AttributeReflectionAction(parcel);
default:
throw new ActionException("Tag " + tag + " not found");
}
};
/**
* Returns a deep copy of the RemoteViews object. The RemoteView may not be
* attached to another RemoteView -- it must be the root of a hierarchy.
*
* @deprecated use {@link #RemoteViews(RemoteViews)} instead.
* @throws IllegalStateException if this is not the root of a RemoteView
* hierarchy
*/
@Override
@Deprecated
public RemoteViews clone() {
Preconditions.checkState(mIsRoot, "RemoteView has been attached to another RemoteView. "
+ "May only clone the root of a RemoteView hierarchy.");
return new RemoteViews(this);
}
public String getPackage() {
return (mApplication != null) ? mApplication.packageName : null;
}
/**
* Returns the layout id of the root layout associated with this RemoteViews. In the case
* that the RemoteViews has both a landscape and portrait root, this will return the layout
* id associated with the portrait layout.
*
* @return the layout id.
*/
public int getLayoutId() {
return hasFlags(FLAG_USE_LIGHT_BACKGROUND_LAYOUT) && (mLightBackgroundLayoutId != 0)
? mLightBackgroundLayoutId : mLayoutId;
}
/**
* Sets the root of the hierarchy and then recursively traverses the tree to update the root
* and populate caches for all descendants.
*/
private void configureAsChild(@NonNull HierarchyRootData rootData) {
mIsRoot = false;
mBitmapCache = rootData.mBitmapCache;
mApplicationInfoCache = rootData.mApplicationInfoCache;
mClassCookies = rootData.mClassCookies;
configureDescendantsAsChildren();
}
/**
* Recursively traverses the tree to update the root and populate caches for all descendants.
*/
private void configureDescendantsAsChildren() {
// Before propagating down the tree, replace our application from the root application info
// cache, to ensure the same instance is present throughout the hierarchy to allow for
// squashing.
mApplication = mApplicationInfoCache.getOrPut(mApplication);
HierarchyRootData rootData = getHierarchyRootData();
if (hasSizedRemoteViews()) {
for (RemoteViews remoteView : mSizedRemoteViews) {
remoteView.configureAsChild(rootData);
}
} else if (hasLandscapeAndPortraitLayouts()) {
mLandscape.configureAsChild(rootData);
mPortrait.configureAsChild(rootData);
} else {
if (mActions != null) {
for (Action action : mActions) {
action.setHierarchyRootData(rootData);
}
}
}
}
/**
* Recreates caches at the root level of the hierarchy, then recursively populates the caches
* down the hierarchy.
*/
private void reconstructCaches() {
if (!mIsRoot) return;
mBitmapCache = new BitmapCache();
mApplicationInfoCache = new ApplicationInfoCache();
mApplication = mApplicationInfoCache.getOrPut(mApplication);
configureDescendantsAsChildren();
}
/**
* Returns an estimate of the bitmap heap memory usage for this RemoteViews.
*/
/** @hide */
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
public int estimateMemoryUsage() {
return mBitmapCache.getBitmapMemory();
}
/**
* Add an action to be executed on the remote side when apply is called.
*
* @param a The action to add
*/
private void addAction(Action a) {
if (hasMultipleLayouts()) {
throw new RuntimeException("RemoteViews specifying separate layouts for orientation"
+ " or size cannot be modified. Instead, fully configure each layouts"
+ " individually before constructing the combined layout.");
}
if (mActions == null) {
mActions = new ArrayList<>();
}
mActions.add(a);
}
/**
* Equivalent to calling {@link ViewGroup#addView(View)} after inflating the
* given {@link RemoteViews}. This allows users to build "nested"
* {@link RemoteViews}. In cases where consumers of {@link RemoteViews} may
* recycle layouts, use {@link #removeAllViews(int)} to clear any existing
* children.
*
* @param viewId The id of the parent {@link ViewGroup} to add child into.
* @param nestedView {@link RemoteViews} that describes the child.
*/
public void addView(@IdRes int viewId, RemoteViews nestedView) {
// Clear all children when nested views omitted
addAction(nestedView == null
? new ViewGroupActionRemove(viewId)
: new ViewGroupActionAdd(viewId, nestedView));
}
/**
* Equivalent to calling {@link ViewGroup#addView(View)} after inflating the given
* {@link RemoteViews}. If the {@link RemoteViews} may be re-inflated or updated,
* {@link #removeAllViews(int)} must be called on the same {@code viewId
* } before the first call to this method for the behavior of this method to be predictable.
*
* The {@code stableId} will be used to identify a potential view to recycled when the remote
* view is inflated. Views can be re-used if inserted in the same order, potentially with
* some views appearing / disappearing. To be recycled the view must not change the layout
* used to inflate it or its view id (see {@link RemoteViews#RemoteViews(String, int, int)}).
*
* Note: if a view is re-used, all the actions will be re-applied on it. However, its properties
* are not reset, so what was applied in previous round will have an effect. As a view may be
* re-created at any time by the host, the RemoteViews should not rely on keeping information
* from previous applications and always re-set all the properties they need.
*
* @param viewId The id of the parent {@link ViewGroup} to add child into.
* @param nestedView {@link RemoteViews} that describes the child.
* @param stableId An id that is stable across different versions of RemoteViews.
*/
public void addStableView(@IdRes int viewId, @NonNull RemoteViews nestedView, int stableId) {
addAction(new ViewGroupActionAdd(viewId, nestedView, -1 /* index */, stableId));
}
/**
* Equivalent to calling {@link ViewGroup#addView(View, int)} after inflating the
* given {@link RemoteViews}.
*
* @param viewId The id of the parent {@link ViewGroup} to add the child into.
* @param nestedView {@link RemoteViews} of the child to add.
* @param index The position at which to add the child.
*
* @hide
*/
@UnsupportedAppUsage
public void addView(@IdRes int viewId, RemoteViews nestedView, int index) {
addAction(new ViewGroupActionAdd(viewId, nestedView, index));
}
/**
* Equivalent to calling {@link ViewGroup#removeAllViews()}.
*
* @param viewId The id of the parent {@link ViewGroup} to remove all
* children from.
*/
public void removeAllViews(@IdRes int viewId) {
addAction(new ViewGroupActionRemove(viewId));
}
/**
* Removes all views in the {@link ViewGroup} specified by the {@code viewId} except for any
* child that has the {@code viewIdToKeep} as its id.
*
* @param viewId The id of the parent {@link ViewGroup} to remove children from.
* @param viewIdToKeep The id of a child that should not be removed.
*
* @hide
*/
public void removeAllViewsExceptId(@IdRes int viewId, @IdRes int viewIdToKeep) {
addAction(new ViewGroupActionRemove(viewId, viewIdToKeep));
}
/**
* Removes the {@link View} specified by the {@code viewId} from its parent {@link ViewManager}.
* This will do nothing if the viewId specifies the root view of this RemoteViews.
*
* @param viewId The id of the {@link View} to remove from its parent.
*
* @hide
*/
public void removeFromParent(@IdRes int viewId) {
addAction(new RemoveFromParentAction(viewId));
}
/**
* Equivalent to calling {@link AdapterViewAnimator#showNext()}
*
* @param viewId The id of the view on which to call {@link AdapterViewAnimator#showNext()}
* @deprecated As RemoteViews may be reapplied frequently, it is preferable to call
* {@link #setDisplayedChild(int, int)} to ensure that the adapter index does not change
* unexpectedly.
*/
@Deprecated
public void showNext(@IdRes int viewId) {
addAction(new ViewContentNavigation(viewId, true /* next */));
}
/**
* Equivalent to calling {@link AdapterViewAnimator#showPrevious()}
*
* @param viewId The id of the view on which to call {@link AdapterViewAnimator#showPrevious()}
* @deprecated As RemoteViews may be reapplied frequently, it is preferable to call
* {@link #setDisplayedChild(int, int)} to ensure that the adapter index does not change
* unexpectedly.
*/
@Deprecated
public void showPrevious(@IdRes int viewId) {
addAction(new ViewContentNavigation(viewId, false /* next */));
}
/**
* Equivalent to calling {@link AdapterViewAnimator#setDisplayedChild(int)}
*
* @param viewId The id of the view on which to call
* {@link AdapterViewAnimator#setDisplayedChild(int)}
*/
public void setDisplayedChild(@IdRes int viewId, int childIndex) {
setInt(viewId, "setDisplayedChild", childIndex);
}
/**
* Equivalent to calling {@link View#setVisibility(int)}
*
* @param viewId The id of the view whose visibility should change
* @param visibility The new visibility for the view
*/
public void setViewVisibility(@IdRes int viewId, @View.Visibility int visibility) {
setInt(viewId, "setVisibility", visibility);
}
/**
* Equivalent to calling {@link TextView#setText(CharSequence)}
*
* @param viewId The id of the view whose text should change
* @param text The new text for the view
*/
public void setTextViewText(@IdRes int viewId, CharSequence text) {
setCharSequence(viewId, "setText", text);
}
/**
* Equivalent to calling {@link TextView#setTextSize(int, float)}
*
* @param viewId The id of the view whose text size should change
* @param units The units of size (e.g. COMPLEX_UNIT_SP)
* @param size The size of the text
*/
public void setTextViewTextSize(@IdRes int viewId, int units, float size) {
addAction(new TextViewSizeAction(viewId, units, size));
}
/**
* Equivalent to calling
* {@link TextView#setCompoundDrawablesWithIntrinsicBounds(int, int, int, int)}.
*
* @param viewId The id of the view whose text should change
* @param left The id of a drawable to place to the left of the text, or 0
* @param top The id of a drawable to place above the text, or 0
* @param right The id of a drawable to place to the right of the text, or 0
* @param bottom The id of a drawable to place below the text, or 0
*/
public void setTextViewCompoundDrawables(@IdRes int viewId, @DrawableRes int left,
@DrawableRes int top, @DrawableRes int right, @DrawableRes int bottom) {
addAction(new TextViewDrawableAction(viewId, false, left, top, right, bottom));
}
/**
* Equivalent to calling {@link
* TextView#setCompoundDrawablesRelativeWithIntrinsicBounds(int, int, int, int)}.
*
* @param viewId The id of the view whose text should change
* @param start The id of a drawable to place before the text (relative to the
* layout direction), or 0
* @param top The id of a drawable to place above the text, or 0
* @param end The id of a drawable to place after the text, or 0
* @param bottom The id of a drawable to place below the text, or 0
*/
public void setTextViewCompoundDrawablesRelative(@IdRes int viewId, @DrawableRes int start,
@DrawableRes int top, @DrawableRes int end, @DrawableRes int bottom) {
addAction(new TextViewDrawableAction(viewId, true, start, top, end, bottom));
}
/**
* Equivalent to calling {@link
* TextView#setCompoundDrawablesWithIntrinsicBounds(Drawable, Drawable, Drawable, Drawable)}
* using the drawables yielded by {@link Icon#loadDrawable(Context)}.
*
* @param viewId The id of the view whose text should change
* @param left an Icon to place to the left of the text, or 0
* @param top an Icon to place above the text, or 0
* @param right an Icon to place to the right of the text, or 0
* @param bottom an Icon to place below the text, or 0
*
* @hide
*/
public void setTextViewCompoundDrawables(@IdRes int viewId,
Icon left, Icon top, Icon right, Icon bottom) {
addAction(new TextViewDrawableAction(viewId, false, left, top, right, bottom));
}
/**
* Equivalent to calling {@link
* TextView#setCompoundDrawablesRelativeWithIntrinsicBounds(Drawable, Drawable, Drawable, Drawable)}
* using the drawables yielded by {@link Icon#loadDrawable(Context)}.
*
* @param viewId The id of the view whose text should change
* @param start an Icon to place before the text (relative to the
* layout direction), or 0
* @param top an Icon to place above the text, or 0
* @param end an Icon to place after the text, or 0
* @param bottom an Icon to place below the text, or 0
*
* @hide
*/
public void setTextViewCompoundDrawablesRelative(@IdRes int viewId,
Icon start, Icon top, Icon end, Icon bottom) {
addAction(new TextViewDrawableAction(viewId, true, start, top, end, bottom));
}
/**
* Equivalent to calling {@link ImageView#setImageResource(int)}
*
* @param viewId The id of the view whose drawable should change
* @param srcId The new resource id for the drawable
*/
public void setImageViewResource(@IdRes int viewId, @DrawableRes int srcId) {
setInt(viewId, "setImageResource", srcId);
}
/**
* Equivalent to calling {@link ImageView#setImageURI(Uri)}
*
* @param viewId The id of the view whose drawable should change
* @param uri The Uri for the image
*/
public void setImageViewUri(@IdRes int viewId, Uri uri) {
setUri(viewId, "setImageURI", uri);
}
/**
* Equivalent to calling {@link ImageView#setImageBitmap(Bitmap)}
*
* @param viewId The id of the view whose bitmap should change
* @param bitmap The new Bitmap for the drawable
*/
public void setImageViewBitmap(@IdRes int viewId, Bitmap bitmap) {
setBitmap(viewId, "setImageBitmap", bitmap);
}
/**
* Equivalent to calling {@link ImageView#setImageIcon(Icon)}
*
* @param viewId The id of the view whose bitmap should change
* @param icon The new Icon for the ImageView
*/
public void setImageViewIcon(@IdRes int viewId, Icon icon) {
setIcon(viewId, "setImageIcon", icon);
}
/**
* Equivalent to calling {@link AdapterView#setEmptyView(View)}
*
* @param viewId The id of the view on which to set the empty view
* @param emptyViewId The view id of the empty view
*/
public void setEmptyView(@IdRes int viewId, @IdRes int emptyViewId) {
addAction(new SetEmptyView(viewId, emptyViewId));
}
/**
* Equivalent to calling {@link Chronometer#setBase Chronometer.setBase},
* {@link Chronometer#setFormat Chronometer.setFormat},
* and {@link Chronometer#start Chronometer.start()} or
* {@link Chronometer#stop Chronometer.stop()}.
*
* @param viewId The id of the {@link Chronometer} to change
* @param base The time at which the timer would have read 0:00. This
* time should be based off of
* {@link android.os.SystemClock#elapsedRealtime SystemClock.elapsedRealtime()}.
* @param format The Chronometer format string, or null to
* simply display the timer value.
* @param started True if you want the clock to be started, false if not.
*
* @see #setChronometerCountDown(int, boolean)
*/
public void setChronometer(@IdRes int viewId, long base, String format, boolean started) {
setLong(viewId, "setBase", base);
setString(viewId, "setFormat", format);
setBoolean(viewId, "setStarted", started);
}
/**
* Equivalent to calling {@link Chronometer#setCountDown(boolean) Chronometer.setCountDown} on
* the chronometer with the given viewId.
*
* @param viewId The id of the {@link Chronometer} to change
* @param isCountDown True if you want the chronometer to count down to base instead of
* counting up.
*/
public void setChronometerCountDown(@IdRes int viewId, boolean isCountDown) {
setBoolean(viewId, "setCountDown", isCountDown);
}
/**
* Equivalent to calling {@link ProgressBar#setMax ProgressBar.setMax},
* {@link ProgressBar#setProgress ProgressBar.setProgress}, and
* {@link ProgressBar#setIndeterminate ProgressBar.setIndeterminate}
*
* If indeterminate is true, then the values for max and progress are ignored.
*
* @param viewId The id of the {@link ProgressBar} to change
* @param max The 100% value for the progress bar
* @param progress The current value of the progress bar.
* @param indeterminate True if the progress bar is indeterminate,
* false if not.
*/
public void setProgressBar(@IdRes int viewId, int max, int progress,
boolean indeterminate) {
setBoolean(viewId, "setIndeterminate", indeterminate);
if (!indeterminate) {
setInt(viewId, "setMax", max);
setInt(viewId, "setProgress", progress);
}
}
/**
* Equivalent to calling
* {@link android.view.View#setOnClickListener(android.view.View.OnClickListener)}
* to launch the provided {@link PendingIntent}. The source bounds
* ({@link Intent#getSourceBounds()}) of the intent will be set to the bounds of the clicked
* view in screen space.
* Note that any activity options associated with the mPendingIntent may get overridden
* before starting the intent.
*
* When setting the on-click action of items within collections (eg. {@link ListView},
* {@link StackView} etc.), this method will not work. Instead, use {@link
* RemoteViews#setPendingIntentTemplate(int, PendingIntent)} in conjunction with
* {@link RemoteViews#setOnClickFillInIntent(int, Intent)}.
*
* @param viewId The id of the view that will trigger the {@link PendingIntent} when clicked
* @param pendingIntent The {@link PendingIntent} to send when user clicks
*/
public void setOnClickPendingIntent(@IdRes int viewId, PendingIntent pendingIntent) {
setOnClickResponse(viewId, RemoteResponse.fromPendingIntent(pendingIntent));
}
/**
* Equivalent of calling
* {@link android.view.View#setOnClickListener(android.view.View.OnClickListener)}
* to launch the provided {@link RemoteResponse}.
*
* @param viewId The id of the view that will trigger the {@link RemoteResponse} when clicked
* @param response The {@link RemoteResponse} to send when user clicks
*/
public void setOnClickResponse(@IdRes int viewId, @NonNull RemoteResponse response) {
addAction(new SetOnClickResponse(viewId, response));
}
/**
* When using collections (eg. {@link ListView}, {@link StackView} etc.) in widgets, it is very
* costly to set PendingIntents on the individual items, and is hence not recommended. Instead
* this method should be used to set a single PendingIntent template on the collection, and
* individual items can differentiate their on-click behavior using
* {@link RemoteViews#setOnClickFillInIntent(int, Intent)}.
*
* @param viewId The id of the collection who's children will use this PendingIntent template
* when clicked
* @param pendingIntentTemplate The {@link PendingIntent} to be combined with extras specified
* by a child of viewId and executed when that child is clicked
*/
public void setPendingIntentTemplate(@IdRes int viewId, PendingIntent pendingIntentTemplate) {
addAction(new SetPendingIntentTemplate(viewId, pendingIntentTemplate));
}
/**
* When using collections (eg. {@link ListView}, {@link StackView} etc.) in widgets, it is very
* costly to set PendingIntents on the individual items, and is hence not recommended. Instead
* a single PendingIntent template can be set on the collection, see {@link
* RemoteViews#setPendingIntentTemplate(int, PendingIntent)}, and the individual on-click
* action of a given item can be distinguished by setting a fillInIntent on that item. The
* fillInIntent is then combined with the PendingIntent template in order to determine the final
* intent which will be executed when the item is clicked. This works as follows: any fields
* which are left blank in the PendingIntent template, but are provided by the fillInIntent
* will be overwritten, and the resulting PendingIntent will be used. The rest
* of the PendingIntent template will then be filled in with the associated fields that are
* set in fillInIntent. See {@link Intent#fillIn(Intent, int)} for more details.
*
* @param viewId The id of the view on which to set the fillInIntent
* @param fillInIntent The intent which will be combined with the parent's PendingIntent
* in order to determine the on-click behavior of the view specified by viewId
*/
public void setOnClickFillInIntent(@IdRes int viewId, Intent fillInIntent) {
setOnClickResponse(viewId, RemoteResponse.fromFillInIntent(fillInIntent));
}
/**
* Equivalent to calling
* {@link android.widget.CompoundButton#setOnCheckedChangeListener(
* android.widget.CompoundButton.OnCheckedChangeListener)}
* to launch the provided {@link RemoteResponse}.
*
* The intent will be filled with the current checked state of the view at the key
* {@link #EXTRA_CHECKED}.
*
* The {@link RemoteResponse} will not be launched in response to check changes arising from
* {@link #setCompoundButtonChecked(int, boolean)} or {@link #setRadioGroupChecked(int, int)}
* usages.
*
* The {@link RemoteResponse} must be created using
* {@link RemoteResponse#fromFillInIntent(Intent)} in conjunction with
* {@link RemoteViews#setPendingIntentTemplate(int, PendingIntent)} for items inside
* collections (eg. {@link ListView}, {@link StackView} etc.).
*
* Otherwise, create the {@link RemoteResponse} using
* {@link RemoteResponse#fromPendingIntent(PendingIntent)}.
*
* @param viewId The id of the view that will trigger the {@link PendingIntent} when checked
* state changes.
* @param response The {@link RemoteResponse} to send when the checked state changes.
*/
public void setOnCheckedChangeResponse(
@IdRes int viewId,
@NonNull RemoteResponse response) {
addAction(
new SetOnCheckedChangeResponse(
viewId,
response.setInteractionType(
RemoteResponse.INTERACTION_TYPE_CHECKED_CHANGE)));
}
/**
* @hide
* Equivalent to calling
* {@link Drawable#setColorFilter(int, android.graphics.PorterDuff.Mode)},
* on the {@link Drawable} of a given view.
* <p>
*
* @param viewId The id of the view that contains the target
* {@link Drawable}
* @param targetBackground If true, apply these parameters to the
* {@link Drawable} returned by
* {@link android.view.View#getBackground()}. Otherwise, assume
* the target view is an {@link ImageView} and apply them to
* {@link ImageView#getDrawable()}.
* @param colorFilter Specify a color for a
* {@link android.graphics.ColorFilter} for this drawable. This will be ignored if
* {@code mode} is {@code null}.
* @param mode Specify a PorterDuff mode for this drawable, or null to leave
* unchanged.
*/
public void setDrawableTint(@IdRes int viewId, boolean targetBackground,
@ColorInt int colorFilter, @NonNull PorterDuff.Mode mode) {
addAction(new SetDrawableTint(viewId, targetBackground, colorFilter, mode));
}
/**
* @hide
* Equivalent to calling
* {@link RippleDrawable#setColor(ColorStateList)} on the {@link Drawable} of a given view,
* assuming it's a {@link RippleDrawable}.
* <p>
*
* @param viewId The id of the view that contains the target
* {@link RippleDrawable}
* @param colorStateList Specify a color for a
* {@link ColorStateList} for this drawable.
*/
public void setRippleDrawableColor(@IdRes int viewId, ColorStateList colorStateList) {
addAction(new SetRippleDrawableColor(viewId, colorStateList));
}
/**
* @hide
* Equivalent to calling {@link android.widget.ProgressBar#setProgressTintList}.
*
* @param viewId The id of the view whose tint should change
* @param tint the tint to apply, may be {@code null} to clear tint
*/
public void setProgressTintList(@IdRes int viewId, ColorStateList tint) {
addAction(new ReflectionAction(viewId, "setProgressTintList",
BaseReflectionAction.COLOR_STATE_LIST, tint));
}
/**
* @hide
* Equivalent to calling {@link android.widget.ProgressBar#setProgressBackgroundTintList}.
*
* @param viewId The id of the view whose tint should change
* @param tint the tint to apply, may be {@code null} to clear tint
*/
public void setProgressBackgroundTintList(@IdRes int viewId, ColorStateList tint) {
addAction(new ReflectionAction(viewId, "setProgressBackgroundTintList",
BaseReflectionAction.COLOR_STATE_LIST, tint));
}
/**
* @hide
* Equivalent to calling {@link android.widget.ProgressBar#setIndeterminateTintList}.
*
* @param viewId The id of the view whose tint should change
* @param tint the tint to apply, may be {@code null} to clear tint
*/
public void setProgressIndeterminateTintList(@IdRes int viewId, ColorStateList tint) {
addAction(new ReflectionAction(viewId, "setIndeterminateTintList",
BaseReflectionAction.COLOR_STATE_LIST, tint));
}
/**
* Equivalent to calling {@link android.widget.TextView#setTextColor(int)}.
*
* @param viewId The id of the view whose text color should change
* @param color Sets the text color for all the states (normal, selected,
* focused) to be this color.
*/
public void setTextColor(@IdRes int viewId, @ColorInt int color) {
setInt(viewId, "setTextColor", color);
}
/**
* @hide
* Equivalent to calling {@link android.widget.TextView#setTextColor(ColorStateList)}.
*
* @param viewId The id of the view whose text color should change
* @param colors the text colors to set
*/
public void setTextColor(@IdRes int viewId, ColorStateList colors) {
addAction(new ReflectionAction(viewId, "setTextColor",
BaseReflectionAction.COLOR_STATE_LIST, colors));
}
/**
* Equivalent to calling {@link android.widget.AbsListView#setRemoteViewsAdapter(Intent)}.
*
* @param appWidgetId The id of the app widget which contains the specified view. (This
* parameter is ignored in this deprecated method)
* @param viewId The id of the {@link AdapterView}
* @param intent The intent of the service which will be
* providing data to the RemoteViewsAdapter
* @deprecated This method has been deprecated. See
* {@link android.widget.RemoteViews#setRemoteAdapter(int, Intent)}
*/
@Deprecated
public void setRemoteAdapter(int appWidgetId, @IdRes int viewId, Intent intent) {
setRemoteAdapter(viewId, intent);
}
/**
* Equivalent to calling {@link android.widget.AbsListView#setRemoteViewsAdapter(Intent)}.
* Can only be used for App Widgets.
*
* @param viewId The id of the {@link AdapterView}
* @param intent The intent of the service which will be
* providing data to the RemoteViewsAdapter
*/
public void setRemoteAdapter(@IdRes int viewId, Intent intent) {
addAction(new SetRemoteViewsAdapterIntent(viewId, intent));
}
/**
* Creates a simple Adapter for the viewId specified. The viewId must point to an AdapterView,
* ie. {@link ListView}, {@link GridView}, {@link StackView} or {@link AdapterViewAnimator}.
* This is a simpler but less flexible approach to populating collection widgets. Its use is
* encouraged for most scenarios, as long as the total memory within the list of RemoteViews
* is relatively small (ie. doesn't contain large or numerous Bitmaps, see {@link
* RemoteViews#setImageViewBitmap}). In the case of numerous images, the use of API is still
* possible by setting image URIs instead of Bitmaps, see {@link RemoteViews#setImageViewUri}.
*
* This API is supported in the compatibility library for previous API levels, see
* RemoteViewsCompat.
*
* @param viewId The id of the {@link AdapterView}
* @param list The list of RemoteViews which will populate the view specified by viewId.
* @param viewTypeCount The maximum number of unique layout id's used to construct the list of
* RemoteViews. This count cannot change during the life-cycle of a given widget, so this
* parameter should account for the maximum possible number of types that may appear in the
* See {@link Adapter#getViewTypeCount()}.
*
* @hide
* @deprecated this appears to have no users outside of UnsupportedAppUsage?
*/
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
@Deprecated
public void setRemoteAdapter(@IdRes int viewId, ArrayList<RemoteViews> list,
int viewTypeCount) {
addAction(new SetRemoteViewsAdapterList(viewId, list, viewTypeCount));
}
/**
* Creates a simple Adapter for the viewId specified. The viewId must point to an AdapterView,
* ie. {@link ListView}, {@link GridView}, {@link StackView} or {@link AdapterViewAnimator}.
* This is a simpler but less flexible approach to populating collection widgets. Its use is
* encouraged for most scenarios, as long as the total memory within the list of RemoteViews
* is relatively small (ie. doesn't contain large or numerous Bitmaps, see {@link
* RemoteViews#setImageViewBitmap}). In the case of numerous images, the use of API is still
* possible by setting image URIs instead of Bitmaps, see {@link RemoteViews#setImageViewUri}.
*
* This API is supported in the compatibility library for previous API levels, see
* RemoteViewsCompat.
*
* @param viewId The id of the {@link AdapterView}.
* @param items The items to display in the {@link AdapterView}.
*/
public void setRemoteAdapter(@IdRes int viewId, @NonNull RemoteCollectionItems items) {
addAction(new SetRemoteCollectionItemListAdapterAction(viewId, items));
}
/**
* Equivalent to calling {@link ListView#smoothScrollToPosition(int)}.
*
* @param viewId The id of the view to change
* @param position Scroll to this adapter position
*/
public void setScrollPosition(@IdRes int viewId, int position) {
setInt(viewId, "smoothScrollToPosition", position);
}
/**
* Equivalent to calling {@link ListView#smoothScrollByOffset(int)}.
*
* @param viewId The id of the view to change
* @param offset Scroll by this adapter position offset
*/
public void setRelativeScrollPosition(@IdRes int viewId, int offset) {
setInt(viewId, "smoothScrollByOffset", offset);
}
/**
* Equivalent to calling {@link android.view.View#setPadding(int, int, int, int)}.
*
* @param viewId The id of the view to change
* @param left the left padding in pixels
* @param top the top padding in pixels
* @param right the right padding in pixels
* @param bottom the bottom padding in pixels
*/
public void setViewPadding(@IdRes int viewId,
@Px int left, @Px int top, @Px int right, @Px int bottom) {
addAction(new ViewPaddingAction(viewId, left, top, right, bottom));
}
/**
* Equivalent to calling {@link MarginLayoutParams#setMarginEnd}.
* Only works if the {@link View#getLayoutParams()} supports margins.
*
* @param viewId The id of the view to change
* @param type The margin being set e.g. {@link #MARGIN_END}
* @param dimen a dimension resource to apply to the margin, or 0 to clear the margin.
*/
public void setViewLayoutMarginDimen(@IdRes int viewId, @MarginType int type,
@DimenRes int dimen) {
addAction(new LayoutParamAction(viewId, type, dimen, VALUE_TYPE_RESOURCE));
}
/**
* Equivalent to calling {@link MarginLayoutParams#setMarginEnd}.
* Only works if the {@link View#getLayoutParams()} supports margins.
*
* @param viewId The id of the view to change
* @param type The margin being set e.g. {@link #MARGIN_END}
* @param attr a dimension attribute to apply to the margin, or 0 to clear the margin.
*/
public void setViewLayoutMarginAttr(@IdRes int viewId, @MarginType int type,
@AttrRes int attr) {
addAction(new LayoutParamAction(viewId, type, attr, VALUE_TYPE_ATTRIBUTE));
}
/**
* Equivalent to calling {@link MarginLayoutParams#setMarginEnd}.
* Only works if the {@link View#getLayoutParams()} supports margins.
*
* <p>NOTE: It is recommended to use {@link TypedValue#COMPLEX_UNIT_PX} only for 0.
* Setting margins in pixels will behave poorly when the RemoteViews object is used on a
* display with a different density.
*
* @param viewId The id of the view to change
* @param type The margin being set e.g. {@link #MARGIN_END}
* @param value a value for the margin the given units.
* @param units The unit type of the value e.g. {@link TypedValue#COMPLEX_UNIT_DIP}
*/
public void setViewLayoutMargin(@IdRes int viewId, @MarginType int type, float value,
@ComplexDimensionUnit int units) {
addAction(new LayoutParamAction(viewId, type, value, units));
}
/**
* Equivalent to setting {@link android.view.ViewGroup.LayoutParams#width} except that you may
* provide the value in any dimension units.
*
* <p>NOTE: It is recommended to use {@link TypedValue#COMPLEX_UNIT_PX} only for 0,
* {@link ViewGroup.LayoutParams#WRAP_CONTENT}, or {@link ViewGroup.LayoutParams#MATCH_PARENT}.
* Setting actual sizes in pixels will behave poorly when the RemoteViews object is used on a
* display with a different density.
*
* @param width Width of the view in the given units
* @param units The unit type of the value e.g. {@link TypedValue#COMPLEX_UNIT_DIP}
*/
public void setViewLayoutWidth(@IdRes int viewId, float width,
@ComplexDimensionUnit int units) {
addAction(new LayoutParamAction(viewId, LayoutParamAction.LAYOUT_WIDTH, width, units));
}
/**
* Equivalent to setting {@link android.view.ViewGroup.LayoutParams#width} with
* the result of {@link Resources#getDimensionPixelSize(int)}.
*
* @param widthDimen the dimension resource for the view's width
*/
public void setViewLayoutWidthDimen(@IdRes int viewId, @DimenRes int widthDimen) {
addAction(new LayoutParamAction(viewId, LayoutParamAction.LAYOUT_WIDTH, widthDimen,
VALUE_TYPE_RESOURCE));
}
/**
* Equivalent to setting {@link android.view.ViewGroup.LayoutParams#width} with
* the value of the given attribute in the current theme.
*
* @param widthAttr the dimension attribute for the view's width
*/
public void setViewLayoutWidthAttr(@IdRes int viewId, @AttrRes int widthAttr) {
addAction(new LayoutParamAction(viewId, LayoutParamAction.LAYOUT_WIDTH, widthAttr,
VALUE_TYPE_ATTRIBUTE));
}
/**
* Equivalent to setting {@link android.view.ViewGroup.LayoutParams#height} except that you may
* provide the value in any dimension units.
*
* <p>NOTE: It is recommended to use {@link TypedValue#COMPLEX_UNIT_PX} only for 0,
* {@link ViewGroup.LayoutParams#WRAP_CONTENT}, or {@link ViewGroup.LayoutParams#MATCH_PARENT}.
* Setting actual sizes in pixels will behave poorly when the RemoteViews object is used on a
* display with a different density.
*
* @param height height of the view in the given units
* @param units The unit type of the value e.g. {@link TypedValue#COMPLEX_UNIT_DIP}
*/
public void setViewLayoutHeight(@IdRes int viewId, float height,
@ComplexDimensionUnit int units) {
addAction(new LayoutParamAction(viewId, LayoutParamAction.LAYOUT_HEIGHT, height, units));
}
/**
* Equivalent to setting {@link android.view.ViewGroup.LayoutParams#height} with
* the result of {@link Resources#getDimensionPixelSize(int)}.
*
* @param heightDimen a dimen resource to read the height from.
*/
public void setViewLayoutHeightDimen(@IdRes int viewId, @DimenRes int heightDimen) {
addAction(new LayoutParamAction(viewId, LayoutParamAction.LAYOUT_HEIGHT, heightDimen,
VALUE_TYPE_RESOURCE));
}
/**
* Equivalent to setting {@link android.view.ViewGroup.LayoutParams#height} with
* the value of the given attribute in the current theme.
*
* @param heightAttr a dimen attribute to read the height from.
*/
public void setViewLayoutHeightAttr(@IdRes int viewId, @AttrRes int heightAttr) {
addAction(new LayoutParamAction(viewId, LayoutParamAction.LAYOUT_HEIGHT, heightAttr,
VALUE_TYPE_ATTRIBUTE));
}
/**
* Sets an OutlineProvider on the view whose corner radius is a dimension calculated using
* {@link TypedValue#applyDimension(int, float, DisplayMetrics)}.
*
* <p>NOTE: It is recommended to use {@link TypedValue#COMPLEX_UNIT_PX} only for 0.
* Setting margins in pixels will behave poorly when the RemoteViews object is used on a
* display with a different density.
*/
public void setViewOutlinePreferredRadius(
@IdRes int viewId, float radius, @ComplexDimensionUnit int units) {
addAction(new SetViewOutlinePreferredRadiusAction(viewId, radius, units));
}
/**
* Sets an OutlineProvider on the view whose corner radius is a dimension resource with
* {@code resId}.
*/
public void setViewOutlinePreferredRadiusDimen(@IdRes int viewId, @DimenRes int resId) {
addAction(new SetViewOutlinePreferredRadiusAction(viewId, resId, VALUE_TYPE_RESOURCE));
}
/**
* Sets an OutlineProvider on the view whose corner radius is a dimension attribute with
* {@code attrId}.
*/
public void setViewOutlinePreferredRadiusAttr(@IdRes int viewId, @AttrRes int attrId) {
addAction(new SetViewOutlinePreferredRadiusAction(viewId, attrId, VALUE_TYPE_ATTRIBUTE));
}
/**
* Call a method taking one boolean on a view in the layout for this RemoteViews.
*
* @param viewId The id of the view on which to call the method.
* @param methodName The name of the method to call.
* @param value The value to pass to the method.
*/
public void setBoolean(@IdRes int viewId, String methodName, boolean value) {
addAction(new ReflectionAction(viewId, methodName, BaseReflectionAction.BOOLEAN, value));
}
/**
* Call a method taking one byte on a view in the layout for this RemoteViews.
*
* @param viewId The id of the view on which to call the method.
* @param methodName The name of the method to call.
* @param value The value to pass to the method.
*/
public void setByte(@IdRes int viewId, String methodName, byte value) {
addAction(new ReflectionAction(viewId, methodName, BaseReflectionAction.BYTE, value));
}
/**
* Call a method taking one short on a view in the layout for this RemoteViews.
*
* @param viewId The id of the view on which to call the method.
* @param methodName The name of the method to call.
* @param value The value to pass to the method.
*/
public void setShort(@IdRes int viewId, String methodName, short value) {
addAction(new ReflectionAction(viewId, methodName, BaseReflectionAction.SHORT, value));
}
/**
* Call a method taking one int on a view in the layout for this RemoteViews.
*
* @param viewId The id of the view on which to call the method.
* @param methodName The name of the method to call.
* @param value The value to pass to the method.
*/
public void setInt(@IdRes int viewId, String methodName, int value) {
addAction(new ReflectionAction(viewId, methodName, BaseReflectionAction.INT, value));
}
/**
* Call a method taking one int, a size in pixels, on a view in the layout for this
* RemoteViews.
*
* The dimension will be resolved from the resources at the time the {@link RemoteViews} is
* (re-)applied.
*
* Undefined resources will result in an exception, except 0 which will resolve to 0.
*
* @param viewId The id of the view on which to call the method.
* @param methodName The name of the method to call.
* @param dimenResource The resource to resolve and pass as argument to the method.
*/
public void setIntDimen(@IdRes int viewId, @NonNull String methodName,
@DimenRes int dimenResource) {
addAction(new ResourceReflectionAction(viewId, methodName, BaseReflectionAction.INT,
ResourceReflectionAction.DIMEN_RESOURCE, dimenResource));
}
/**
* Call a method taking one int, a size in pixels, on a view in the layout for this
* RemoteViews.
*
* The dimension will be resolved from the specified dimension at the time of inflation.
*
* @param viewId The id of the view on which to call the method.
* @param methodName The name of the method to call.
* @param value The value of the dimension.
* @param unit The unit in which the value is specified.
*/
public void setIntDimen(@IdRes int viewId, @NonNull String methodName,
float value, @ComplexDimensionUnit int unit) {
addAction(new ComplexUnitDimensionReflectionAction(viewId, methodName, ReflectionAction.INT,
value, unit));
}
/**
* Call a method taking one int, a size in pixels, on a view in the layout for this
* RemoteViews.
*
* The dimension will be resolved from the theme attribute at the time the
* {@link RemoteViews} is (re-)applied.
*
* Unresolvable attributes will result in an exception, except 0 which will resolve to 0.
*
* @param viewId The id of the view on which to call the method.
* @param methodName The name of the method to call.
* @param dimenAttr The attribute to resolve and pass as argument to the method.
*/
public void setIntDimenAttr(@IdRes int viewId, @NonNull String methodName,
@AttrRes int dimenAttr) {
addAction(new AttributeReflectionAction(viewId, methodName, BaseReflectionAction.INT,
ResourceReflectionAction.DIMEN_RESOURCE, dimenAttr));
}
/**
* Call a method taking one int, a color, on a view in the layout for this RemoteViews.
*
* The Color will be resolved from the resources at the time the {@link RemoteViews} is (re-)
* applied.
*
* Undefined resources will result in an exception, except 0 which will resolve to 0.
*
* @param viewId The id of the view on which to call the method.
* @param methodName The name of the method to call.
* @param colorResource The resource to resolve and pass as argument to the method.
*/
public void setColor(@IdRes int viewId, @NonNull String methodName,
@ColorRes int colorResource) {
addAction(new ResourceReflectionAction(viewId, methodName, BaseReflectionAction.INT,
ResourceReflectionAction.COLOR_RESOURCE, colorResource));
}
/**
* Call a method taking one int, a color, on a view in the layout for this RemoteViews.
*
* The Color will be resolved from the theme attribute at the time the {@link RemoteViews} is
* (re-)applied.
*
* Unresolvable attributes will result in an exception, except 0 which will resolve to 0.
*
* @param viewId The id of the view on which to call the method.
* @param methodName The name of the method to call.
* @param colorAttribute The theme attribute to resolve and pass as argument to the method.
*/
public void setColorAttr(@IdRes int viewId, @NonNull String methodName,
@AttrRes int colorAttribute) {
addAction(new AttributeReflectionAction(viewId, methodName, BaseReflectionAction.INT,
AttributeReflectionAction.COLOR_RESOURCE, colorAttribute));
}
/**
* Call a method taking one int, a color, on a view in the layout for this RemoteViews.
*
* @param viewId The id of the view on which to call the method.
* @param methodName The name of the method to call.
* @param notNight The value to pass to the method when the view's configuration is set to
* {@link Configuration#UI_MODE_NIGHT_NO}
* @param night The value to pass to the method when the view's configuration is set to
* {@link Configuration#UI_MODE_NIGHT_YES}
*/
public void setColorInt(
@IdRes int viewId,
@NonNull String methodName,
@ColorInt int notNight,
@ColorInt int night) {
addAction(
new NightModeReflectionAction(
viewId,
methodName,
BaseReflectionAction.INT,
notNight,
night));
}
/**
* Call a method taking one ColorStateList on a view in the layout for this RemoteViews.
*
* @param viewId The id of the view on which to call the method.
* @param methodName The name of the method to call.
* @param value The value to pass to the method.
*/
public void setColorStateList(@IdRes int viewId, @NonNull String methodName,
@Nullable ColorStateList value) {
addAction(new ReflectionAction(viewId, methodName, BaseReflectionAction.COLOR_STATE_LIST,
value));
}
/**
* Call a method taking one ColorStateList on a view in the layout for this RemoteViews.
*
* @param viewId The id of the view on which to call the method.
* @param methodName The name of the method to call.
* @param notNight The value to pass to the method when the view's configuration is set to
* {@link Configuration#UI_MODE_NIGHT_NO}
* @param night The value to pass to the method when the view's configuration is set to
* {@link Configuration#UI_MODE_NIGHT_YES}
*/
public void setColorStateList(
@IdRes int viewId,
@NonNull String methodName,
@Nullable ColorStateList notNight,
@Nullable ColorStateList night) {
addAction(
new NightModeReflectionAction(
viewId,
methodName,
BaseReflectionAction.COLOR_STATE_LIST,
notNight,
night));
}
/**
* Call a method taking one ColorStateList on a view in the layout for this RemoteViews.
*
* The ColorStateList will be resolved from the resources at the time the {@link RemoteViews} is
* (re-)applied.
*
* Undefined resources will result in an exception, except 0 which will resolve to null.
*
* @param viewId The id of the view on which to call the method.
* @param methodName The name of the method to call.
* @param colorResource The resource to resolve and pass as argument to the method.
*/
public void setColorStateList(@IdRes int viewId, @NonNull String methodName,
@ColorRes int colorResource) {
addAction(new ResourceReflectionAction(viewId, methodName,
BaseReflectionAction.COLOR_STATE_LIST, ResourceReflectionAction.COLOR_RESOURCE,
colorResource));
}
/**
* Call a method taking one ColorStateList on a view in the layout for this RemoteViews.
*
* The ColorStateList will be resolved from the theme attribute at the time the
* {@link RemoteViews} is (re-)applied.
*
* Unresolvable attributes will result in an exception, except 0 which will resolve to null.
*
* @param viewId The id of the view on which to call the method.
* @param methodName The name of the method to call.
* @param colorAttr The theme attribute to resolve and pass as argument to the method.
*/
public void setColorStateListAttr(@IdRes int viewId, @NonNull String methodName,
@AttrRes int colorAttr) {
addAction(new AttributeReflectionAction(viewId, methodName,
BaseReflectionAction.COLOR_STATE_LIST, ResourceReflectionAction.COLOR_RESOURCE,
colorAttr));
}
/**
* Call a method taking one long on a view in the layout for this RemoteViews.
*
* @param viewId The id of the view on which to call the method.
* @param methodName The name of the method to call.
* @param value The value to pass to the method.
*/
public void setLong(@IdRes int viewId, String methodName, long value) {
addAction(new ReflectionAction(viewId, methodName, BaseReflectionAction.LONG, value));
}
/**
* Call a method taking one float on a view in the layout for this RemoteViews.
*
* @param viewId The id of the view on which to call the method.
* @param methodName The name of the method to call.
* @param value The value to pass to the method.
*/
public void setFloat(@IdRes int viewId, String methodName, float value) {
addAction(new ReflectionAction(viewId, methodName, BaseReflectionAction.FLOAT, value));
}
/**
* Call a method taking one float, a size in pixels, on a view in the layout for this
* RemoteViews.
*
* The dimension will be resolved from the resources at the time the {@link RemoteViews} is
* (re-)applied.
*
* Undefined resources will result in an exception, except 0 which will resolve to 0f.
*
* @param viewId The id of the view on which to call the method.
* @param methodName The name of the method to call.
* @param dimenResource The resource to resolve and pass as argument to the method.
*/
public void setFloatDimen(@IdRes int viewId, @NonNull String methodName,
@DimenRes int dimenResource) {
addAction(new ResourceReflectionAction(viewId, methodName, BaseReflectionAction.FLOAT,
ResourceReflectionAction.DIMEN_RESOURCE, dimenResource));
}
/**
* Call a method taking one float, a size in pixels, on a view in the layout for this
* RemoteViews.
*
* The dimension will be resolved from the resources at the time the {@link RemoteViews} is
* (re-)applied.
*
* @param viewId The id of the view on which to call the method.
* @param methodName The name of the method to call.
* @param value The value of the dimension.
* @param unit The unit in which the value is specified.
*/
public void setFloatDimen(@IdRes int viewId, @NonNull String methodName,
float value, @ComplexDimensionUnit int unit) {
addAction(
new ComplexUnitDimensionReflectionAction(viewId, methodName, ReflectionAction.FLOAT,
value, unit));
}
/**
* Call a method taking one float, a size in pixels, on a view in the layout for this
* RemoteViews.
*
* The dimension will be resolved from the theme attribute at the time the {@link RemoteViews}
* is (re-)applied.
*
* Unresolvable attributes will result in an exception, except 0 which will resolve to 0f.
*
* @param viewId The id of the view on which to call the method.
* @param methodName The name of the method to call.
* @param dimenAttr The attribute to resolve and pass as argument to the method.
*/
public void setFloatDimenAttr(@IdRes int viewId, @NonNull String methodName,
@AttrRes int dimenAttr) {
addAction(new AttributeReflectionAction(viewId, methodName, BaseReflectionAction.FLOAT,
ResourceReflectionAction.DIMEN_RESOURCE, dimenAttr));
}
/**
* Call a method taking one double on a view in the layout for this RemoteViews.
*
* @param viewId The id of the view on which to call the method.
* @param methodName The name of the method to call.
* @param value The value to pass to the method.
*/
public void setDouble(@IdRes int viewId, String methodName, double value) {
addAction(new ReflectionAction(viewId, methodName, BaseReflectionAction.DOUBLE, value));
}
/**
* Call a method taking one char on a view in the layout for this RemoteViews.
*
* @param viewId The id of the view on which to call the method.
* @param methodName The name of the method to call.
* @param value The value to pass to the method.
*/
public void setChar(@IdRes int viewId, String methodName, char value) {
addAction(new ReflectionAction(viewId, methodName, BaseReflectionAction.CHAR, value));
}
/**
* Call a method taking one String on a view in the layout for this RemoteViews.
*
* @param viewId The id of the view on which to call the method.
* @param methodName The name of the method to call.
* @param value The value to pass to the method.
*/
public void setString(@IdRes int viewId, String methodName, String value) {
addAction(new ReflectionAction(viewId, methodName, BaseReflectionAction.STRING, value));
}
/**
* Call a method taking one CharSequence on a view in the layout for this RemoteViews.
*
* @param viewId The id of the view on which to call the method.
* @param methodName The name of the method to call.
* @param value The value to pass to the method.
*/
public void setCharSequence(@IdRes int viewId, String methodName, CharSequence value) {
addAction(new ReflectionAction(viewId, methodName, BaseReflectionAction.CHAR_SEQUENCE,
value));
}
/**
* Call a method taking one CharSequence on a view in the layout for this RemoteViews.
*
* The CharSequence will be resolved from the resources at the time the {@link RemoteViews} is
* (re-)applied.
*
* Undefined resources will result in an exception, except 0 which will resolve to null.
*
* @param viewId The id of the view on which to call the method.
* @param methodName The name of the method to call.
* @param stringResource The resource to resolve and pass as argument to the method.
*/
public void setCharSequence(@IdRes int viewId, @NonNull String methodName,
@StringRes int stringResource) {
addAction(
new ResourceReflectionAction(viewId, methodName, BaseReflectionAction.CHAR_SEQUENCE,
ResourceReflectionAction.STRING_RESOURCE, stringResource));
}
/**
* Call a method taking one CharSequence on a view in the layout for this RemoteViews.
*
* The CharSequence will be resolved from the theme attribute at the time the
* {@link RemoteViews} is (re-)applied.
*
* Unresolvable attributes will result in an exception, except 0 which will resolve to null.
*
* @param viewId The id of the view on which to call the method.
* @param methodName The name of the method to call.
* @param stringAttribute The attribute to resolve and pass as argument to the method.
*/
public void setCharSequenceAttr(@IdRes int viewId, @NonNull String methodName,
@AttrRes int stringAttribute) {
addAction(
new AttributeReflectionAction(viewId, methodName,
BaseReflectionAction.CHAR_SEQUENCE,
AttributeReflectionAction.STRING_RESOURCE, stringAttribute));
}
/**
* Call a method taking one Uri on a view in the layout for this RemoteViews.
*
* @param viewId The id of the view on which to call the method.
* @param methodName The name of the method to call.
* @param value The value to pass to the method.
*/
public void setUri(@IdRes int viewId, String methodName, Uri value) {
if (value != null) {
// Resolve any filesystem path before sending remotely
value = value.getCanonicalUri();
if (StrictMode.vmFileUriExposureEnabled()) {
value.checkFileUriExposed("RemoteViews.setUri()");
}
}
addAction(new ReflectionAction(viewId, methodName, BaseReflectionAction.URI, value));
}
/**
* Call a method taking one Bitmap on a view in the layout for this RemoteViews.
* @more
* <p class="note">The bitmap will be flattened into the parcel if this object is
* sent across processes, so it may end up using a lot of memory, and may be fairly slow.</p>
*
* @param viewId The id of the view on which to call the method.
* @param methodName The name of the method to call.
* @param value The value to pass to the method.
*/
public void setBitmap(@IdRes int viewId, String methodName, Bitmap value) {
addAction(new BitmapReflectionAction(viewId, methodName, value));
}
/**
* Call a method taking one BlendMode on a view in the layout for this RemoteViews.
*
* @param viewId The id of the view on which to call the method.
* @param methodName The name of the method to call.
* @param value The value to pass to the method.
*/
public void setBlendMode(@IdRes int viewId, @NonNull String methodName,
@Nullable BlendMode value) {
addAction(new ReflectionAction(viewId, methodName, BaseReflectionAction.BLEND_MODE, value));
}
/**
* Call a method taking one Bundle on a view in the layout for this RemoteViews.
*
* @param viewId The id of the view on which to call the method.
* @param methodName The name of the method to call.
* @param value The value to pass to the method.
*/
public void setBundle(@IdRes int viewId, String methodName, Bundle value) {
addAction(new ReflectionAction(viewId, methodName, BaseReflectionAction.BUNDLE, value));
}
/**
* Call a method taking one Intent on a view in the layout for this RemoteViews.
*
* @param viewId The id of the view on which to call the method.
* @param methodName The name of the method to call.
* @param value The {@link android.content.Intent} to pass the method.
*/
public void setIntent(@IdRes int viewId, String methodName, Intent value) {
addAction(new ReflectionAction(viewId, methodName, BaseReflectionAction.INTENT, value));
}
/**
* Call a method taking one Icon on a view in the layout for this RemoteViews.
*
* @param viewId The id of the view on which to call the method.
* @param methodName The name of the method to call.
* @param value The {@link android.graphics.drawable.Icon} to pass the method.
*/
public void setIcon(@IdRes int viewId, String methodName, Icon value) {
addAction(new ReflectionAction(viewId, methodName, BaseReflectionAction.ICON, value));
}
/**
* Call a method taking one Icon on a view in the layout for this RemoteViews.
*
* @param viewId The id of the view on which to call the method.
* @param methodName The name of the method to call.
* @param notNight The value to pass to the method when the view's configuration is set to
* {@link Configuration#UI_MODE_NIGHT_NO}
* @param night The value to pass to the method when the view's configuration is set to
* {@link Configuration#UI_MODE_NIGHT_YES}
*/
public void setIcon(
@IdRes int viewId,
@NonNull String methodName,
@Nullable Icon notNight,
@Nullable Icon night) {
addAction(
new NightModeReflectionAction(
viewId,
methodName,
BaseReflectionAction.ICON,
notNight,
night));
}
/**
* Equivalent to calling View.setContentDescription(CharSequence).
*
* @param viewId The id of the view whose content description should change.
* @param contentDescription The new content description for the view.
*/
public void setContentDescription(@IdRes int viewId, CharSequence contentDescription) {
setCharSequence(viewId, "setContentDescription", contentDescription);
}
/**
* Equivalent to calling {@link android.view.View#setAccessibilityTraversalBefore(int)}.
*
* @param viewId The id of the view whose before view in accessibility traversal to set.
* @param nextId The id of the next in the accessibility traversal.
**/
public void setAccessibilityTraversalBefore(@IdRes int viewId, @IdRes int nextId) {
setInt(viewId, "setAccessibilityTraversalBefore", nextId);
}
/**
* Equivalent to calling {@link android.view.View#setAccessibilityTraversalAfter(int)}.
*
* @param viewId The id of the view whose after view in accessibility traversal to set.
* @param nextId The id of the next in the accessibility traversal.
**/
public void setAccessibilityTraversalAfter(@IdRes int viewId, @IdRes int nextId) {
setInt(viewId, "setAccessibilityTraversalAfter", nextId);
}
/**
* Equivalent to calling {@link View#setLabelFor(int)}.
*
* @param viewId The id of the view whose property to set.
* @param labeledId The id of a view for which this view serves as a label.
*/
public void setLabelFor(@IdRes int viewId, @IdRes int labeledId) {
setInt(viewId, "setLabelFor", labeledId);
}
/**
* Equivalent to calling {@link android.widget.CompoundButton#setChecked(boolean)}.
*
* @param viewId The id of the view whose property to set.
* @param checked true to check the button, false to uncheck it.
*/
public void setCompoundButtonChecked(@IdRes int viewId, boolean checked) {
addAction(new SetCompoundButtonCheckedAction(viewId, checked));
}
/**
* Equivalent to calling {@link android.widget.RadioGroup#check(int)}.
*
* @param viewId The id of the view whose property to set.
* @param checkedId The unique id of the radio button to select in the group.
*/
public void setRadioGroupChecked(@IdRes int viewId, @IdRes int checkedId) {
addAction(new SetRadioGroupCheckedAction(viewId, checkedId));
}
/**
* Provides an alternate layout ID, which can be used to inflate this view. This layout will be
* used by the host when the widgets displayed on a light-background where foreground elements
* and text can safely draw using a dark color without any additional background protection.
*/
public void setLightBackgroundLayoutId(@LayoutRes int layoutId) {
mLightBackgroundLayoutId = layoutId;
}
/**
* If this view supports dark text versions, creates a copy representing that version,
* otherwise returns itself.
* @hide
*/
public RemoteViews getDarkTextViews() {
if (hasFlags(FLAG_USE_LIGHT_BACKGROUND_LAYOUT)) {
return this;
}
try {
addFlags(FLAG_USE_LIGHT_BACKGROUND_LAYOUT);
return new RemoteViews(this);
} finally {
mApplyFlags &= ~FLAG_USE_LIGHT_BACKGROUND_LAYOUT;
}
}
private RemoteViews getRemoteViewsToApply(Context context) {
if (hasLandscapeAndPortraitLayouts()) {
int orientation = context.getResources().getConfiguration().orientation;
if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
return mLandscape;
}
return mPortrait;
}
if (hasSizedRemoteViews()) {
return findSmallestRemoteView();
}
return this;
}
/**
* Returns the square distance between two points.
*
* This is particularly useful when we only care about the ordering of the distances.
*/
private static float squareDistance(SizeF p1, SizeF p2) {
float dx = p1.getWidth() - p2.getWidth();
float dy = p1.getHeight() - p2.getHeight();
return dx * dx + dy * dy;
}
/**
* Returns whether the layout fits in the space available to the widget.
*
* A layout fits on a widget if the widget size is known (i.e. not null) and both dimensions
* are smaller than the ones of the widget, adding some padding to account for rounding errors.
*/
private static boolean fitsIn(SizeF sizeLayout, @Nullable SizeF sizeWidget) {
return sizeWidget != null && (Math.ceil(sizeWidget.getWidth()) + 1 > sizeLayout.getWidth())
&& (Math.ceil(sizeWidget.getHeight()) + 1 > sizeLayout.getHeight());
}
private RemoteViews findBestFitLayout(@NonNull SizeF widgetSize) {
// Find the better remote view
RemoteViews bestFit = null;
float bestSqDist = Float.MAX_VALUE;
for (RemoteViews layout : mSizedRemoteViews) {
SizeF layoutSize = layout.getIdealSize();
if (layoutSize == null) {
throw new IllegalStateException("Expected RemoteViews to have ideal size");
}
if (fitsIn(layoutSize, widgetSize)) {
if (bestFit == null) {
bestFit = layout;
bestSqDist = squareDistance(layoutSize, widgetSize);
} else {
float newSqDist = squareDistance(layoutSize, widgetSize);
if (newSqDist < bestSqDist) {
bestFit = layout;
bestSqDist = newSqDist;
}
}
}
}
if (bestFit == null) {
Log.w(LOG_TAG, "Could not find a RemoteViews fitting the current size: " + widgetSize);
return findSmallestRemoteView();
}
return bestFit;
}
/**
* Returns the most appropriate {@link RemoteViews} given the context and, if not null, the
* size of the widget.
*
* If {@link RemoteViews#hasSizedRemoteViews()} returns true, the most appropriate view is
* the one that fits in the widget (according to {@link RemoteViews#fitsIn}) and has the
* diagonal the most similar to the widget. If no layout fits or the size of the widget is
* not specified, the one with the smallest area will be chosen.
*
* @hide
*/
public RemoteViews getRemoteViewsToApply(@NonNull Context context,
@Nullable SizeF widgetSize) {
if (!hasSizedRemoteViews() || widgetSize == null) {
// If there isn't multiple remote views, fall back on the previous methods.
return getRemoteViewsToApply(context);
}
return findBestFitLayout(widgetSize);
}
/**
* Checks whether the change of size will lead to using a different {@link RemoteViews}.
*
* @hide
*/
@Nullable
public RemoteViews getRemoteViewsToApplyIfDifferent(@Nullable SizeF oldSize,
@NonNull SizeF newSize) {
if (!hasSizedRemoteViews()) {
return null;
}
RemoteViews oldBestFit = oldSize == null ? findSmallestRemoteView() : findBestFitLayout(
oldSize);
RemoteViews newBestFit = findBestFitLayout(newSize);
if (oldBestFit != newBestFit) {
return newBestFit;
}
return null;
}
/**
* Inflates the view hierarchy represented by this object and applies
* all of the actions.
*
* <p><strong>Caller beware: this may throw</strong>
*
* @param context Default context to use
* @param parent Parent that the resulting view hierarchy will be attached to. This method
* does <strong>not</strong> attach the hierarchy. The caller should do so when appropriate.
* @return The inflated view hierarchy
*/
public View apply(Context context, ViewGroup parent) {
return apply(context, parent, null);
}
/** @hide */
public View apply(Context context, ViewGroup parent, InteractionHandler handler) {
return apply(context, parent, handler, null);
}
/** @hide */
public View apply(@NonNull Context context, @NonNull ViewGroup parent,
@Nullable InteractionHandler handler, @Nullable SizeF size) {
return apply(context, parent, size, new ActionApplyParams()
.withInteractionHandler(handler));
}
/** @hide */
public View applyWithTheme(@NonNull Context context, @NonNull ViewGroup parent,
@Nullable InteractionHandler handler, @StyleRes int applyThemeResId) {
return apply(context, parent, null, new ActionApplyParams()
.withInteractionHandler(handler)
.withThemeResId(applyThemeResId));
}
/** @hide */
public View apply(Context context, ViewGroup parent, InteractionHandler handler,
@Nullable SizeF size, @Nullable ColorResources colorResources) {
return apply(context, parent, size, new ActionApplyParams()
.withInteractionHandler(handler)
.withColorResources(colorResources));
}
/** @hide **/
public View apply(Context context, ViewGroup parent, @Nullable SizeF size,
ActionApplyParams params) {
return apply(context, parent, parent, size, params);
}
private View apply(Context context, ViewGroup directParent, ViewGroup rootParent,
@Nullable SizeF size, ActionApplyParams params) {
RemoteViews rvToApply = getRemoteViewsToApply(context, size);
View result = inflateView(context, rvToApply, directParent,
params.applyThemeResId, params.colorResources);
rvToApply.performApply(result, rootParent, params);
return result;
}
private View inflateView(Context context, RemoteViews rv, @Nullable ViewGroup parent,
@StyleRes int applyThemeResId, @Nullable ColorResources colorResources) {
// RemoteViews may be built by an application installed in another
// user. So build a context that loads resources from that user but
// still returns the current users userId so settings like data / time formats
// are loaded without requiring cross user persmissions.
final Context contextForResources =
getContextForResourcesEnsuringCorrectCachedApkPaths(context);
if (colorResources != null) {
colorResources.apply(contextForResources);
}
Context inflationContext = new RemoteViewsContextWrapper(context, contextForResources);
// If mApplyThemeResId is not given, Theme.DeviceDefault will be used.
if (applyThemeResId != 0) {
inflationContext = new ContextThemeWrapper(inflationContext, applyThemeResId);
}
LayoutInflater inflater = LayoutInflater.from(context);
// Clone inflater so we load resources from correct context and
// we don't add a filter to the static version returned by getSystemService.
inflater = inflater.cloneInContext(inflationContext);
inflater.setFilter(shouldUseStaticFilter() ? INFLATER_FILTER : this);
View v = inflater.inflate(rv.getLayoutId(), parent, false);
if (mViewId != View.NO_ID) {
v.setId(mViewId);
v.setTagInternal(R.id.remote_views_override_id, mViewId);
}
v.setTagInternal(R.id.widget_frame, rv.getLayoutId());
return v;
}
/**
* A static filter is much lighter than RemoteViews itself. It's optimized here only for
* RemoteVies class. Subclasses should always override this and return true if not overriding
* {@link this#onLoadClass(Class)}.
*
* @hide
*/
protected boolean shouldUseStaticFilter() {
return this.getClass().equals(RemoteViews.class);
}
/**
* Implement this interface to receive a callback when
* {@link #applyAsync} or {@link #reapplyAsync} is finished.
* @hide
*/
public interface OnViewAppliedListener {
/**
* Callback when the RemoteView has finished inflating,
* but no actions have been applied yet.
*/
default void onViewInflated(View v) {};
void onViewApplied(View v);
void onError(Exception e);
}
/**
* Applies the views asynchronously, moving as much of the task on the background
* thread as possible.
*
* @see #apply(Context, ViewGroup)
* @param context Default context to use
* @param parent Parent that the resulting view hierarchy will be attached to. This method
* does <strong>not</strong> attach the hierarchy. The caller should do so when appropriate.
* @param listener the callback to run when all actions have been applied. May be null.
* @param executor The executor to use. If null {@link AsyncTask#THREAD_POOL_EXECUTOR} is used.
* @return CancellationSignal
* @hide
*/
public CancellationSignal applyAsync(
Context context, ViewGroup parent, Executor executor, OnViewAppliedListener listener) {
return applyAsync(context, parent, executor, listener, null /* handler */);
}
/** @hide */
public CancellationSignal applyAsync(Context context, ViewGroup parent,
Executor executor, OnViewAppliedListener listener, InteractionHandler handler) {
return applyAsync(context, parent, executor, listener, handler, null /* size */);
}
/** @hide */
public CancellationSignal applyAsync(Context context, ViewGroup parent,
Executor executor, OnViewAppliedListener listener, InteractionHandler handler,
SizeF size) {
return applyAsync(context, parent, executor, listener, handler, size,
null /* themeColors */);
}
/** @hide */
public CancellationSignal applyAsync(Context context, ViewGroup parent, Executor executor,
OnViewAppliedListener listener, InteractionHandler handler, SizeF size,
ColorResources colorResources) {
ActionApplyParams params = new ActionApplyParams()
.withInteractionHandler(handler)
.withColorResources(colorResources)
.withExecutor(executor);
return new AsyncApplyTask(getRemoteViewsToApply(context, size), parent, context, listener,
params, null /* result */, true /* topLevel */).startTaskOnExecutor(executor);
}
private AsyncApplyTask getInternalAsyncApplyTask(Context context, ViewGroup parent,
OnViewAppliedListener listener, ActionApplyParams params, SizeF size, View result) {
return new AsyncApplyTask(getRemoteViewsToApply(context, size), parent, context, listener,
params, result, false /* topLevel */);
}
private class AsyncApplyTask extends AsyncTask<Void, Void, ViewTree>
implements CancellationSignal.OnCancelListener {
final CancellationSignal mCancelSignal = new CancellationSignal();
final RemoteViews mRV;
final ViewGroup mParent;
final Context mContext;
final OnViewAppliedListener mListener;
final ActionApplyParams mApplyParams;
/**
* Whether the remote view is the top-level one (i.e. not within an action).
*
* This is only used if the result is specified (i.e. the view is being recycled).
*/
final boolean mTopLevel;
private View mResult;
private ViewTree mTree;
private Action[] mActions;
private Exception mError;
private AsyncApplyTask(
RemoteViews rv, ViewGroup parent, Context context, OnViewAppliedListener listener,
ActionApplyParams applyParams, View result, boolean topLevel) {
mRV = rv;
mParent = parent;
mContext = context;
mListener = listener;
mTopLevel = topLevel;
mApplyParams = applyParams;
mResult = result;
}
@Nullable
@Override
protected ViewTree doInBackground(Void... params) {
try {
if (mResult == null) {
mResult = inflateView(mContext, mRV, mParent, 0, mApplyParams.colorResources);
}
mTree = new ViewTree(mResult);
if (mRV.mActions != null) {
int count = mRV.mActions.size();
mActions = new Action[count];
for (int i = 0; i < count && !isCancelled(); i++) {
// TODO: check if isCancelled in nested views.
mActions[i] = mRV.mActions.get(i)
.initActionAsync(mTree, mParent, mApplyParams);
}
} else {
mActions = null;
}
return mTree;
} catch (Exception e) {
mError = e;
return null;
}
}
@Override
protected void onPostExecute(ViewTree viewTree) {
mCancelSignal.setOnCancelListener(null);
if (mError == null) {
if (mListener != null) {
mListener.onViewInflated(viewTree.mRoot);
}
try {
if (mActions != null) {
ActionApplyParams applyParams = mApplyParams.clone();
if (applyParams.handler == null) {
applyParams.handler = DEFAULT_INTERACTION_HANDLER;
}
for (Action a : mActions) {
a.apply(viewTree.mRoot, mParent, applyParams);
}
}
// If the parent of the view is has is a root, resolve the recycling.
if (mTopLevel && mResult instanceof ViewGroup) {
finalizeViewRecycling((ViewGroup) mResult);
}
} catch (Exception e) {
mError = e;
}
}
if (mListener != null) {
if (mError != null) {
mListener.onError(mError);
} else {
mListener.onViewApplied(viewTree.mRoot);
}
} else if (mError != null) {
if (mError instanceof ActionException) {
throw (ActionException) mError;
} else {
throw new ActionException(mError);
}
}
}
@Override
public void onCancel() {
cancel(true);
}
private CancellationSignal startTaskOnExecutor(Executor executor) {
mCancelSignal.setOnCancelListener(this);
executeOnExecutor(executor == null ? AsyncTask.THREAD_POOL_EXECUTOR : executor);
return mCancelSignal;
}
}
/**
* Applies all of the actions to the provided view.
*
* <p><strong>Caller beware: this may throw</strong>
*
* @param v The view to apply the actions to. This should be the result of
* the {@link #apply(Context,ViewGroup)} call.
*/
public void reapply(Context context, View v) {
reapply(context, v, null /* size */, new ActionApplyParams());
}
/** @hide */
public void reapply(Context context, View v, InteractionHandler handler) {
reapply(context, v, null /* size */,
new ActionApplyParams().withInteractionHandler(handler));
}
/** @hide */
public void reapply(Context context, View v, InteractionHandler handler, SizeF size,
ColorResources colorResources) {
reapply(context, v, size, new ActionApplyParams()
.withInteractionHandler(handler).withColorResources(colorResources));
}
/** @hide */
public void reapply(Context context, View v, @Nullable SizeF size, ActionApplyParams params) {
reapply(context, v, (ViewGroup) v.getParent(), size, params, true);
}
private void reapplyNestedViews(Context context, View v, ViewGroup rootParent,
ActionApplyParams params) {
reapply(context, v, rootParent, null, params, false);
}
// Note: topLevel should be true only for calls on the topLevel RemoteViews, internal calls
// should set it to false.
private void reapply(Context context, View v, ViewGroup rootParent,
@Nullable SizeF size, ActionApplyParams params, boolean topLevel) {
RemoteViews rvToApply = getRemoteViewsToReapply(context, v, size);
rvToApply.performApply(v, rootParent, params);
// If the parent of the view is has is a root, resolve the recycling.
if (topLevel && v instanceof ViewGroup) {
finalizeViewRecycling((ViewGroup) v);
}
}
/** @hide */
public boolean canRecycleView(@Nullable View v) {
if (v == null) {
return false;
}
Integer previousLayoutId = (Integer) v.getTag(R.id.widget_frame);
if (previousLayoutId == null) {
return false;
}
Integer overrideIdTag = (Integer) v.getTag(R.id.remote_views_override_id);
int overrideId = overrideIdTag == null ? View.NO_ID : overrideIdTag;
// If mViewId is View.NO_ID, we only recycle if overrideId is also View.NO_ID.
// Otherwise, it might be that, on a previous iteration, the view's ID was set to
// something else, and it should now be reset to the ID defined in the XML layout file,
// whatever it is.
return previousLayoutId == getLayoutId() && mViewId == overrideId;
}
/**
* Returns the RemoteViews that should be used in the reapply operation.
*
* If the current RemoteViews has multiple layout, this will select the correct one.
*
* @throws RuntimeException If the current RemoteViews should not be reapplied onto the provided
* View.
*/
private RemoteViews getRemoteViewsToReapply(Context context, View v, @Nullable SizeF size) {
RemoteViews rvToApply = getRemoteViewsToApply(context, size);
// In the case that a view has this RemoteViews applied in one orientation or size, is
// persisted across change, and has the RemoteViews re-applied in a different situation
// (orientation or size), we throw an exception, since the layouts may be completely
// unrelated.
// If the ViewID has been changed on the view, or is changed by the RemoteViews, we also
// may throw an exception, as the RemoteViews will probably not apply properly.
// However, we need to let potentially unrelated RemoteViews apply, as this lack of testing
// is already used in production code in some apps.
if (hasMultipleLayouts()
|| rvToApply.mViewId != View.NO_ID
|| v.getTag(R.id.remote_views_override_id) != null) {
if (!rvToApply.canRecycleView(v)) {
throw new RuntimeException("Attempting to re-apply RemoteViews to a view that" +
" that does not share the same root layout id.");
}
}
return rvToApply;
}
/**
* Applies all the actions to the provided view, moving as much of the task on the background
* thread as possible.
*
* @see #reapply(Context, View)
* @param context Default context to use
* @param v The view to apply the actions to. This should be the result of
* the {@link #apply(Context,ViewGroup)} call.
* @param listener the callback to run when all actions have been applied. May be null.
* @param executor The executor to use. If null {@link AsyncTask#THREAD_POOL_EXECUTOR} is used
* @return CancellationSignal
* @hide
*/
public CancellationSignal reapplyAsync(Context context, View v, Executor executor,
OnViewAppliedListener listener) {
return reapplyAsync(context, v, executor, listener, null);
}
/** @hide */
public CancellationSignal reapplyAsync(Context context, View v, Executor executor,
OnViewAppliedListener listener, InteractionHandler handler) {
return reapplyAsync(context, v, executor, listener, handler, null, null);
}
/** @hide */
public CancellationSignal reapplyAsync(Context context, View v, Executor executor,
OnViewAppliedListener listener, InteractionHandler handler, SizeF size,
ColorResources colorResources) {
RemoteViews rvToApply = getRemoteViewsToReapply(context, v, size);
ActionApplyParams params = new ActionApplyParams()
.withColorResources(colorResources)
.withInteractionHandler(handler)
.withExecutor(executor);
return new AsyncApplyTask(rvToApply, (ViewGroup) v.getParent(),
context, listener, params, v, true /* topLevel */)
.startTaskOnExecutor(executor);
}
private void performApply(View v, ViewGroup parent, ActionApplyParams params) {
params = params.clone();
if (params.handler == null) {
params.handler = DEFAULT_INTERACTION_HANDLER;
}
if (mActions != null) {
final int count = mActions.size();
for (int i = 0; i < count; i++) {
mActions.get(i).apply(v, parent, params);
}
}
}
/**
* Returns true if the RemoteViews contains potentially costly operations and should be
* applied asynchronously.
*
* @hide
*/
public boolean prefersAsyncApply() {
if (mActions != null) {
final int count = mActions.size();
for (int i = 0; i < count; i++) {
if (mActions.get(i).prefersAsyncApply()) {
return true;
}
}
}
return false;
}
/** @hide */
public void updateAppInfo(@NonNull ApplicationInfo info) {
ApplicationInfo existing = mApplicationInfoCache.get(info);
if (existing != null && !existing.sourceDir.equals(info.sourceDir)) {
// Overlay paths are generated against a particular version of an application.
// The overlays paths of a newly upgraded application are incompatible with the
// old version of the application.
return;
}
// If we can update to the new AppInfo, put it in the cache and propagate the change
// throughout the hierarchy.
mApplicationInfoCache.put(info);
configureDescendantsAsChildren();
}
private Context getContextForResourcesEnsuringCorrectCachedApkPaths(Context context) {
if (mApplication != null) {
if (context.getUserId() == UserHandle.getUserId(mApplication.uid)
&& context.getPackageName().equals(mApplication.packageName)) {
return context;
}
try {
LoadedApk.checkAndUpdateApkPaths(mApplication);
return context.createApplicationContext(mApplication,
Context.CONTEXT_RESTRICTED);
} catch (NameNotFoundException e) {
Log.e(LOG_TAG, "Package name " + mApplication.packageName + " not found");
}
}
return context;
}
/**
* Utility class to hold all the options when applying the remote views
* @hide
*/
public class ActionApplyParams {
public InteractionHandler handler;
public ColorResources colorResources;
public Executor executor;
@StyleRes public int applyThemeResId;
@Override
public ActionApplyParams clone() {
return new ActionApplyParams()
.withInteractionHandler(handler)
.withColorResources(colorResources)
.withExecutor(executor)
.withThemeResId(applyThemeResId);
}
public ActionApplyParams withInteractionHandler(InteractionHandler handler) {
this.handler = handler;
return this;
}
public ActionApplyParams withColorResources(ColorResources colorResources) {
this.colorResources = colorResources;
return this;
}
public ActionApplyParams withThemeResId(@StyleRes int themeResId) {
this.applyThemeResId = themeResId;
return this;
}
public ActionApplyParams withExecutor(Executor executor) {
this.executor = executor;
return this;
}
}
/**
* Object allowing the modification of a context to overload the system's dynamic colors.
*
* Only colors from {@link android.R.color#system_accent1_0} to
* {@link android.R.color#system_neutral2_1000} can be overloaded.
* @hide
*/
public static final class ColorResources {
// Set of valid colors resources.
private static final int FIRST_RESOURCE_COLOR_ID = android.R.color.system_neutral1_0;
private static final int LAST_RESOURCE_COLOR_ID = android.R.color.system_accent3_1000;
// Size, in bytes, of an entry in the array of colors in an ARSC file.
private static final int ARSC_ENTRY_SIZE = 16;
private final ResourcesLoader mLoader;
private final SparseIntArray mColorMapping;
private ColorResources(ResourcesLoader loader, SparseIntArray colorMapping) {
mLoader = loader;
mColorMapping = colorMapping;
}
/**
* Apply the color resources to the given context.
*
* No resource resolution must have be done on the context given to that method.
*/
public void apply(Context context) {
context.getResources().addLoaders(mLoader);
}
public SparseIntArray getColorMapping() {
return mColorMapping;
}
private static ByteArrayOutputStream readFileContent(InputStream input) throws IOException {
ByteArrayOutputStream content = new ByteArrayOutputStream(2048);
byte[] buffer = new byte[4096];
while (input.available() > 0) {
int read = input.read(buffer);
content.write(buffer, 0, read);
}
return content;
}
/**
* Creates the compiled resources content from the asset stored in the APK.
*
* The asset is a compiled resource with the correct resources name and correct ids, only
* the values are incorrect. The last value is at the very end of the file. The resources
* are in an array, the array's entries are 16 bytes each. We use this to work out the
* location of all the positions of the various resources.
*/
@Nullable
private static byte[] createCompiledResourcesContent(Context context,
SparseIntArray colorResources) throws IOException {
byte[] content;
try (InputStream input = context.getResources().openRawResource(
com.android.internal.R.raw.remote_views_color_resources)) {
ByteArrayOutputStream rawContent = readFileContent(input);
content = rawContent.toByteArray();
}
int valuesOffset =
content.length - (LAST_RESOURCE_COLOR_ID & 0xffff) * ARSC_ENTRY_SIZE - 4;
if (valuesOffset < 0) {
Log.e(LOG_TAG, "ARSC file for theme colors is invalid.");
return null;
}
for (int colorRes = FIRST_RESOURCE_COLOR_ID; colorRes <= LAST_RESOURCE_COLOR_ID;
colorRes++) {
// The last 2 bytes are the index in the color array.
int index = colorRes & 0xffff;
int offset = valuesOffset + index * ARSC_ENTRY_SIZE;
int value = colorResources.get(colorRes, context.getColor(colorRes));
// Write the 32 bit integer in little endian
for (int b = 0; b < 4; b++) {
content[offset + b] = (byte) (value & 0xff);
value >>= 8;
}
}
return content;
}
/**
* Adds a resource loader for theme colors to the given context.
*
* @param context Context of the view hosting the widget.
* @param colorMapping Mapping of resources to color values.
*
* @hide
*/
@Nullable
public static ColorResources create(Context context, SparseIntArray colorMapping) {
try {
byte[] contentBytes = createCompiledResourcesContent(context, colorMapping);
if (contentBytes == null) {
return null;
}
FileDescriptor arscFile = null;
try {
arscFile = Os.memfd_create("remote_views_theme_colors.arsc", 0 /* flags */);
// Note: This must not be closed through the OutputStream.
try (OutputStream pipeWriter = new FileOutputStream(arscFile)) {
pipeWriter.write(contentBytes);
try (ParcelFileDescriptor pfd = ParcelFileDescriptor.dup(arscFile)) {
ResourcesLoader colorsLoader = new ResourcesLoader();
colorsLoader.addProvider(ResourcesProvider
.loadFromTable(pfd, null /* assetsProvider */));
return new ColorResources(colorsLoader, colorMapping.clone());
}
}
} finally {
if (arscFile != null) {
Os.close(arscFile);
}
}
} catch (Exception ex) {
Log.e(LOG_TAG, "Failed to setup the context for theme colors", ex);
}
return null;
}
}
/**
* Returns the number of actions in this RemoteViews. Can be used as a sequence number.
*
* @hide
*/
public int getSequenceNumber() {
return (mActions == null) ? 0 : mActions.size();
}
/**
* Used to restrict the views which can be inflated
*
* @see android.view.LayoutInflater.Filter#onLoadClass(java.lang.Class)
* @deprecated Used by system to enforce safe inflation of {@link RemoteViews}. Apps should not
* override this method. Changing of this method will NOT affect the process where RemoteViews
* is rendered.
*/
@Deprecated
public boolean onLoadClass(Class clazz) {
return clazz.isAnnotationPresent(RemoteView.class);
}
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel dest, int flags) {
boolean prevSquashingAllowed = dest.allowSquashing();
if (!hasMultipleLayouts()) {
dest.writeInt(MODE_NORMAL);
// We only write the bitmap cache if we are the root RemoteViews, as this cache
// is shared by all children.
if (mIsRoot) {
mBitmapCache.writeBitmapsToParcel(dest, flags);
}
mApplication.writeToParcel(dest, flags);
if (mIsRoot || mIdealSize == null) {
dest.writeInt(0);
} else {
dest.writeInt(1);
mIdealSize.writeToParcel(dest, flags);
}
dest.writeInt(mLayoutId);
dest.writeInt(mViewId);
dest.writeInt(mLightBackgroundLayoutId);
writeActionsToParcel(dest, flags);
} else if (hasSizedRemoteViews()) {
dest.writeInt(MODE_HAS_SIZED_REMOTEVIEWS);
if (mIsRoot) {
mBitmapCache.writeBitmapsToParcel(dest, flags);
}
dest.writeInt(mSizedRemoteViews.size());
for (RemoteViews view : mSizedRemoteViews) {
view.writeToParcel(dest, flags);
}
} else {
dest.writeInt(MODE_HAS_LANDSCAPE_AND_PORTRAIT);
// We only write the bitmap cache if we are the root RemoteViews, as this cache
// is shared by all children.
if (mIsRoot) {
mBitmapCache.writeBitmapsToParcel(dest, flags);
}
mLandscape.writeToParcel(dest, flags);
// Both RemoteViews already share the same package and user
mPortrait.writeToParcel(dest, flags);
}
dest.writeInt(mApplyFlags);
dest.writeLong(mProviderInstanceId);
dest.restoreAllowSquashing(prevSquashingAllowed);
}
private void writeActionsToParcel(Parcel parcel, int flags) {
int count;
if (mActions != null) {
count = mActions.size();
} else {
count = 0;
}
parcel.writeInt(count);
for (int i = 0; i < count; i++) {
Action a = mActions.get(i);
parcel.writeInt(a.getActionTag());
a.writeToParcel(parcel, flags);
}
}
@Nullable
private static ApplicationInfo getApplicationInfo(@Nullable String packageName, int userId) {
if (packageName == null) {
return null;
}
// Get the application for the passed in package and user.
Application application = ActivityThread.currentApplication();
if (application == null) {
throw new IllegalStateException("Cannot create remote views out of an aplication.");
}
ApplicationInfo applicationInfo = application.getApplicationInfo();
if (UserHandle.getUserId(applicationInfo.uid) != userId
|| !applicationInfo.packageName.equals(packageName)) {
try {
Context context = application.getBaseContext().createPackageContextAsUser(
packageName, 0, new UserHandle(userId));
applicationInfo = context.getApplicationInfo();
} catch (NameNotFoundException nnfe) {
throw new IllegalArgumentException("No such package " + packageName);
}
}
return applicationInfo;
}
/**
* Returns true if the {@link #mApplication} is same as the provided info.
*
* @hide
*/
public boolean hasSameAppInfo(ApplicationInfo info) {
return mApplication.packageName.equals(info.packageName) && mApplication.uid == info.uid;
}
/**
* Parcelable.Creator that instantiates RemoteViews objects
*/
public static final @android.annotation.NonNull Parcelable.Creator<RemoteViews> CREATOR = new Parcelable.Creator<RemoteViews>() {
public RemoteViews createFromParcel(Parcel parcel) {
return new RemoteViews(parcel);
}
public RemoteViews[] newArray(int size) {
return new RemoteViews[size];
}
};
/**
* A representation of the view hierarchy. Only views which have a valid ID are added
* and can be searched.
*/
private static class ViewTree {
private static final int INSERT_AT_END_INDEX = -1;
private View mRoot;
private ArrayList<ViewTree> mChildren;
private ViewTree(View root) {
mRoot = root;
}
public void createTree() {
if (mChildren != null) {
return;
}
mChildren = new ArrayList<>();
if (mRoot instanceof ViewGroup) {
ViewGroup vg = (ViewGroup) mRoot;
int count = vg.getChildCount();
for (int i = 0; i < count; i++) {
addViewChild(vg.getChildAt(i));
}
}
}
@Nullable
public ViewTree findViewTreeById(@IdRes int id) {
if (mRoot.getId() == id) {
return this;
}
if (mChildren == null) {
return null;
}
for (ViewTree tree : mChildren) {
ViewTree result = tree.findViewTreeById(id);
if (result != null) {
return result;
}
}
return null;
}
@Nullable
public ViewTree findViewTreeParentOf(ViewTree child) {
if (mChildren == null) {
return null;
}
for (ViewTree tree : mChildren) {
if (tree == child) {
return this;
}
ViewTree result = tree.findViewTreeParentOf(child);
if (result != null) {
return result;
}
}
return null;
}
public void replaceView(View v) {
mRoot = v;
mChildren = null;
createTree();
}
@Nullable
public <T extends View> T findViewById(@IdRes int id) {
if (mChildren == null) {
return mRoot.findViewById(id);
}
ViewTree tree = findViewTreeById(id);
return tree == null ? null : (T) tree.mRoot;
}
public void addChild(ViewTree child) {
addChild(child, INSERT_AT_END_INDEX);
}
/**
* Adds the given {@link ViewTree} as a child at the given index.
*
* @param index The position at which to add the child or -1 to add last.
*/
public void addChild(ViewTree child, int index) {
if (mChildren == null) {
mChildren = new ArrayList<>();
}
child.createTree();
if (index == INSERT_AT_END_INDEX) {
mChildren.add(child);
return;
}
mChildren.add(index, child);
}
public void removeChildren(int start, int count) {
if (mChildren != null) {
for (int i = 0; i < count; i++) {
mChildren.remove(start);
}
}
}
private void addViewChild(View v) {
// ViewTree only contains Views which can be found using findViewById.
// If isRootNamespace is true, this view is skipped.
// @see ViewGroup#findViewTraversal(int)
if (v.isRootNamespace()) {
return;
}
final ViewTree target;
// If the view has a valid id, i.e., if can be found using findViewById, add it to the
// tree, otherwise skip this view and add its children instead.
if (v.getId() != 0) {
ViewTree tree = new ViewTree(v);
mChildren.add(tree);
target = tree;
} else {
target = this;
}
if (v instanceof ViewGroup) {
if (target.mChildren == null) {
target.mChildren = new ArrayList<>();
ViewGroup vg = (ViewGroup) v;
int count = vg.getChildCount();
for (int i = 0; i < count; i++) {
target.addViewChild(vg.getChildAt(i));
}
}
}
}
/** Find the first child for which the condition is true and return its index. */
public int findChildIndex(Predicate<View> condition) {
return findChildIndex(0, condition);
}
/**
* Find the first child, starting at {@code startIndex}, for which the condition is true and
* return its index.
*/
public int findChildIndex(int startIndex, Predicate<View> condition) {
if (mChildren == null) {
return -1;
}
for (int i = startIndex; i < mChildren.size(); i++) {
if (condition.test(mChildren.get(i).mRoot)) {
return i;
}
}
return -1;
}
}
/**
* Class representing a response to an action performed on any element of a RemoteViews.
*/
public static class RemoteResponse {
/** @hide **/
@IntDef(prefix = "INTERACTION_TYPE_", value = {
INTERACTION_TYPE_CLICK,
INTERACTION_TYPE_CHECKED_CHANGE,
})
@Retention(RetentionPolicy.SOURCE)
@interface InteractionType {}
/** @hide */
public static final int INTERACTION_TYPE_CLICK = 0;
/** @hide */
public static final int INTERACTION_TYPE_CHECKED_CHANGE = 1;
private PendingIntent mPendingIntent;
private Intent mFillIntent;
private int mInteractionType = INTERACTION_TYPE_CLICK;
private IntArray mViewIds;
private ArrayList<String> mElementNames;
/**
* Creates a response which sends a pending intent as part of the response. The source
* bounds ({@link Intent#getSourceBounds()}) of the intent will be set to the bounds of the
* target view in screen space.
* Note that any activity options associated with the mPendingIntent may get overridden
* before starting the intent.
*
* @param pendingIntent The {@link PendingIntent} to send as part of the response
*/
@NonNull
public static RemoteResponse fromPendingIntent(@NonNull PendingIntent pendingIntent) {
RemoteResponse response = new RemoteResponse();
response.mPendingIntent = pendingIntent;
return response;
}
/**
* When using collections (eg. {@link ListView}, {@link StackView} etc.) in widgets, it is
* very costly to set PendingIntents on the individual items, and is hence not recommended.
* Instead a single PendingIntent template can be set on the collection, see {@link
* RemoteViews#setPendingIntentTemplate(int, PendingIntent)}, and the individual on-click
* action of a given item can be distinguished by setting a fillInIntent on that item. The
* fillInIntent is then combined with the PendingIntent template in order to determine the
* final intent which will be executed when the item is clicked. This works as follows: any
* fields which are left blank in the PendingIntent template, but are provided by the
* fillInIntent will be overwritten, and the resulting PendingIntent will be used. The rest
* of the PendingIntent template will then be filled in with the associated fields that are
* set in fillInIntent. See {@link Intent#fillIn(Intent, int)} for more details.
* Creates a response which sends a pending intent as part of the response. The source
* bounds ({@link Intent#getSourceBounds()}) of the intent will be set to the bounds of the
* target view in screen space.
* Note that any activity options associated with the mPendingIntent may get overridden
* before starting the intent.
*
* @param fillIntent The intent which will be combined with the parent's PendingIntent in
* order to determine the behavior of the response
* @see RemoteViews#setPendingIntentTemplate(int, PendingIntent)
* @see RemoteViews#setOnClickFillInIntent(int, Intent)
*/
@NonNull
public static RemoteResponse fromFillInIntent(@NonNull Intent fillIntent) {
RemoteResponse response = new RemoteResponse();
response.mFillIntent = fillIntent;
return response;
}
/**
* Adds a shared element to be transferred as part of the transition between Activities
* using cross-Activity scene animations. The position of the first element will be used as
* the epicenter for the exit Transition. The position of the associated shared element in
* the launched Activity will be the epicenter of its entering Transition.
*
* @param viewId The id of the view to be shared as part of the transition
* @param sharedElementName The shared element name for this view
* @see ActivityOptions#makeSceneTransitionAnimation(Activity, Pair[])
*/
@NonNull
public RemoteResponse addSharedElement(@IdRes int viewId,
@NonNull String sharedElementName) {
if (mViewIds == null) {
mViewIds = new IntArray();
mElementNames = new ArrayList<>();
}
mViewIds.add(viewId);
mElementNames.add(sharedElementName);
return this;
}
/**
* Sets the interaction type for which this RemoteResponse responds.
*
* @param type the type of interaction for which this is a response, such as clicking or
* checked state changing
*
* @hide
*/
@NonNull
public RemoteResponse setInteractionType(@InteractionType int type) {
mInteractionType = type;
return this;
}
private void writeToParcel(Parcel dest, int flags) {
PendingIntent.writePendingIntentOrNullToParcel(mPendingIntent, dest);
if (mPendingIntent == null) {
// Only write the intent if pending intent is null
dest.writeTypedObject(mFillIntent, flags);
}
dest.writeInt(mInteractionType);
dest.writeIntArray(mViewIds == null ? null : mViewIds.toArray());
dest.writeStringList(mElementNames);
}
private void readFromParcel(Parcel parcel) {
mPendingIntent = PendingIntent.readPendingIntentOrNullFromParcel(parcel);
if (mPendingIntent == null) {
mFillIntent = parcel.readTypedObject(Intent.CREATOR);
}
mInteractionType = parcel.readInt();
int[] viewIds = parcel.createIntArray();
mViewIds = viewIds == null ? null : IntArray.wrap(viewIds);
mElementNames = parcel.createStringArrayList();
}
private void handleViewInteraction(
View v,
InteractionHandler handler) {
final PendingIntent pi;
if (mPendingIntent != null) {
pi = mPendingIntent;
} else if (mFillIntent != null) {
AdapterView<?> ancestor = getAdapterViewAncestor(v);
if (ancestor == null) {
Log.e(LOG_TAG, "Collection item doesn't have AdapterView parent");
return;
}
// Ensure that a template pending intent has been set on the ancestor
if (!(ancestor.getTag() instanceof PendingIntent)) {
Log.e(LOG_TAG, "Attempting setOnClickFillInIntent or "
+ "setOnCheckedChangeFillInIntent without calling "
+ "setPendingIntentTemplate on parent.");
return;
}
pi = (PendingIntent) ancestor.getTag();
} else {
Log.e(LOG_TAG, "Response has neither pendingIntent nor fillInIntent");
return;
}
handler.onInteraction(v, pi, this);
}
/**
* Returns the closest ancestor of the view that is an AdapterView or null if none could be
* found.
*/
@Nullable
private static AdapterView<?> getAdapterViewAncestor(@Nullable View view) {
if (view == null) return null;
View parent = (View) view.getParent();
// Break the for loop on the first encounter of:
// 1) an AdapterView,
// 2) an AppWidgetHostView that is not a RemoteViewsFrameLayout, or
// 3) a null parent.
// 2) and 3) are unexpected and catch the case where a child is not
// correctly parented in an AdapterView.
while (parent != null && !(parent instanceof AdapterView<?>)
&& !((parent instanceof AppWidgetHostView)
&& !(parent instanceof RemoteViewsAdapter.RemoteViewsFrameLayout))) {
parent = (View) parent.getParent();
}
return parent instanceof AdapterView<?> ? (AdapterView<?>) parent : null;
}
/** @hide */
public Pair<Intent, ActivityOptions> getLaunchOptions(View view) {
Intent intent = mPendingIntent != null ? new Intent() : new Intent(mFillIntent);
intent.setSourceBounds(getSourceBounds(view));
if (view instanceof CompoundButton
&& mInteractionType == INTERACTION_TYPE_CHECKED_CHANGE) {
intent.putExtra(EXTRA_CHECKED, ((CompoundButton) view).isChecked());
}
ActivityOptions opts = null;
Context context = view.getContext();
if (context.getResources().getBoolean(
com.android.internal.R.bool.config_overrideRemoteViewsActivityTransition)) {
TypedArray windowStyle = context.getTheme().obtainStyledAttributes(
com.android.internal.R.styleable.Window);
int windowAnimations = windowStyle.getResourceId(
com.android.internal.R.styleable.Window_windowAnimationStyle, 0);
TypedArray windowAnimationStyle = context.obtainStyledAttributes(
windowAnimations, com.android.internal.R.styleable.WindowAnimation);
int enterAnimationId = windowAnimationStyle.getResourceId(com.android.internal.R
.styleable.WindowAnimation_activityOpenRemoteViewsEnterAnimation, 0);
windowStyle.recycle();
windowAnimationStyle.recycle();
if (enterAnimationId != 0) {
opts = ActivityOptions.makeCustomAnimation(context,
enterAnimationId, 0);
opts.setPendingIntentLaunchFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
}
if (opts == null && mViewIds != null && mElementNames != null) {
View parent = (View) view.getParent();
while (parent != null && !(parent instanceof AppWidgetHostView)) {
parent = (View) parent.getParent();
}
if (parent instanceof AppWidgetHostView) {
opts = ((AppWidgetHostView) parent).createSharedElementActivityOptions(
mViewIds.toArray(),
mElementNames.toArray(new String[mElementNames.size()]), intent);
}
}
if (opts == null) {
opts = ActivityOptions.makeBasic();
opts.setPendingIntentLaunchFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
if (view.getDisplay() != null) {
opts.setLaunchDisplayId(view.getDisplay().getDisplayId());
} else {
// TODO(b/218409359): Remove once bug is fixed.
Log.w(LOG_TAG, "getLaunchOptions: view.getDisplay() is null!",
new Exception());
}
return Pair.create(intent, opts);
}
}
/** @hide */
public static boolean startPendingIntent(View view, PendingIntent pendingIntent,
Pair<Intent, ActivityOptions> options) {
try {
// TODO: Unregister this handler if PendingIntent.FLAG_ONE_SHOT?
Context context = view.getContext();
// The NEW_TASK flags are applied through the activity options and not as a part of
// the call to startIntentSender() to ensure that they are consistently applied to
// both mutable and immutable PendingIntents.
context.startIntentSender(
pendingIntent.getIntentSender(), options.first,
0, 0, 0, options.second.toBundle());
} catch (IntentSender.SendIntentException e) {
Log.e(LOG_TAG, "Cannot send pending intent: ", e);
return false;
} catch (Exception e) {
Log.e(LOG_TAG, "Cannot send pending intent due to unknown exception: ", e);
return false;
}
return true;
}
/** Representation of a fixed list of items to be displayed in a RemoteViews collection. */
public static final class RemoteCollectionItems implements Parcelable {
private final long[] mIds;
private final RemoteViews[] mViews;
private final boolean mHasStableIds;
private final int mViewTypeCount;
private HierarchyRootData mHierarchyRootData;
RemoteCollectionItems(
long[] ids, RemoteViews[] views, boolean hasStableIds, int viewTypeCount) {
mIds = ids;
mViews = views;
mHasStableIds = hasStableIds;
mViewTypeCount = viewTypeCount;
if (ids.length != views.length) {
throw new IllegalArgumentException(
"RemoteCollectionItems has different number of ids and views");
}
if (viewTypeCount < 1) {
throw new IllegalArgumentException("View type count must be >= 1");
}
int layoutIdCount = (int) Arrays.stream(views)
.mapToInt(RemoteViews::getLayoutId)
.distinct()
.count();
if (layoutIdCount > viewTypeCount) {
throw new IllegalArgumentException(
"View type count is set to " + viewTypeCount + ", but the collection "
+ "contains " + layoutIdCount + " different layout ids");
}
// Until the collection items are attached to a parent, we configure the first item
// to be the root of the others to share caches and save space during serialization.
if (views.length > 0) {
setHierarchyRootData(views[0].getHierarchyRootData());
views[0].mIsRoot = true;
}
}
RemoteCollectionItems(@NonNull Parcel in, @Nullable HierarchyRootData hierarchyRootData) {
mHasStableIds = in.readBoolean();
mViewTypeCount = in.readInt();
int length = in.readInt();
mIds = new long[length];
in.readLongArray(mIds);
boolean attached = in.readBoolean();
mViews = new RemoteViews[length];
int firstChildIndex;
if (attached) {
if (hierarchyRootData == null) {
throw new IllegalStateException("Cannot unparcel a RemoteCollectionItems that "
+ "was parceled as attached without providing data for a root "
+ "RemoteViews");
}
mHierarchyRootData = hierarchyRootData;
firstChildIndex = 0;
} else {
mViews[0] = new RemoteViews(in);
mHierarchyRootData = mViews[0].getHierarchyRootData();
firstChildIndex = 1;
}
for (int i = firstChildIndex; i < length; i++) {
mViews[i] = new RemoteViews(
in,
mHierarchyRootData,
/* info= */ null,
/* depth= */ 0);
}
}
void setHierarchyRootData(@NonNull HierarchyRootData rootData) {
mHierarchyRootData = rootData;
for (RemoteViews view : mViews) {
view.configureAsChild(rootData);
}
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(@NonNull Parcel dest, int flags) {
writeToParcel(dest, flags, /* attached= */ false);
}
private void writeToParcel(@NonNull Parcel dest, int flags, boolean attached) {
boolean prevAllowSquashing = dest.allowSquashing();
dest.writeBoolean(mHasStableIds);
dest.writeInt(mViewTypeCount);
dest.writeInt(mIds.length);
dest.writeLongArray(mIds);
if (attached && mHierarchyRootData == null) {
throw new IllegalStateException("Cannot call writeToParcelAttached for a "
+ "RemoteCollectionItems without first calling setHierarchyRootData()");
}
// Write whether we parceled as attached or not. This allows cleaner validation and
// proper error messaging when unparceling later.
dest.writeBoolean(attached);
boolean restoreRoot = false;
if (!attached && mViews.length > 0 && !mViews[0].mIsRoot) {
// If we're writing unattached, temporarily set the first item as the root so that
// the bitmap cache is written to the parcel.
restoreRoot = true;
mViews[0].mIsRoot = true;
}
for (RemoteViews view : mViews) {
view.writeToParcel(dest, flags);
}
if (restoreRoot) mViews[0].mIsRoot = false;
dest.restoreAllowSquashing(prevAllowSquashing);
}
/**
* Returns the id for {@code position}. See {@link #hasStableIds()} for whether this id
* should be considered meaningful across collection updates.
*
* @return Id for the position.
*/
public long getItemId(int position) {
return mIds[position];
}
/**
* Returns the {@link RemoteViews} to display at {@code position}.
*
* @return RemoteViews for the position.
*/
@NonNull
public RemoteViews getItemView(int position) {
return mViews[position];
}
/**
* Returns the number of elements in the collection.
*
* @return Count of items.
*/
public int getItemCount() {
return mIds.length;
}
/**
* Returns the view type count for the collection when used in an adapter
*
* @return Count of view types for the collection when used in an adapter.
* @see android.widget.Adapter#getViewTypeCount()
*/
public int getViewTypeCount() {
return mViewTypeCount;
}
/**
* Indicates whether the item ids are stable across changes to the underlying data.
*
* @return True if the same id always refers to the same object.
* @see android.widget.Adapter#hasStableIds()
*/
public boolean hasStableIds() {
return mHasStableIds;
}
@NonNull
public static final Creator<RemoteCollectionItems> CREATOR =
new Creator<RemoteCollectionItems>() {
@NonNull
@Override
public RemoteCollectionItems createFromParcel(@NonNull Parcel source) {
return new RemoteCollectionItems(source, /* hierarchyRoot= */ null);
}
@NonNull
@Override
public RemoteCollectionItems[] newArray(int size) {
return new RemoteCollectionItems[size];
}
};
/** Builder class for {@link RemoteCollectionItems} objects.*/
public static final class Builder {
private final LongArray mIds = new LongArray();
private final List<RemoteViews> mViews = new ArrayList<>();
private boolean mHasStableIds;
private int mViewTypeCount;
/**
* Adds a {@link RemoteViews} to the collection.
*
* @param id Id to associate with the row. Use {@link #setHasStableIds(boolean)} to
* indicate that ids are stable across changes to the collection.
* @param view RemoteViews to display for the row.
*/
@NonNull
// Covered by getItemId, getItemView, getItemCount.
@SuppressLint("MissingGetterMatchingBuilder")
public Builder addItem(long id, @NonNull RemoteViews view) {
if (view == null) throw new NullPointerException();
if (view.hasMultipleLayouts()) {
throw new IllegalArgumentException(
"RemoteViews used in a RemoteCollectionItems cannot specify separate "
+ "layouts for orientations or sizes.");
}
mIds.add(id);
mViews.add(view);
return this;
}
/**
* Sets whether the item ids are stable across changes to the underlying data.
*
* @see android.widget.Adapter#hasStableIds()
*/
@NonNull
public Builder setHasStableIds(boolean hasStableIds) {
mHasStableIds = hasStableIds;
return this;
}
/**
* Sets the view type count for the collection when used in an adapter. This can be set
* to the maximum number of different layout ids that will be used by RemoteViews in
* this collection.
*
* If this value is not set, then a value will be inferred from the provided items. As
* a result, the adapter may need to be recreated when the list is updated with
* previously unseen RemoteViews layouts for new items.
*
* @see android.widget.Adapter#getViewTypeCount()
*/
@NonNull
public Builder setViewTypeCount(int viewTypeCount) {
mViewTypeCount = viewTypeCount;
return this;
}
/** Creates the {@link RemoteCollectionItems} defined by this builder. */
@NonNull
public RemoteCollectionItems build() {
if (mViewTypeCount < 1) {
// If a view type count wasn't specified, set it to be the number of distinct
// layout ids used in the items.
mViewTypeCount = (int) mViews.stream()
.mapToInt(RemoteViews::getLayoutId)
.distinct()
.count();
}
return new RemoteCollectionItems(
mIds.toArray(),
mViews.toArray(new RemoteViews[0]),
mHasStableIds,
Math.max(mViewTypeCount, 1));
}
}
}
/**
* Get the ID of the top-level view of the XML layout, if set using
* {@link RemoteViews#RemoteViews(String, int, int)}.
*/
public @IdRes int getViewId() {
return mViewId;
}
/**
* Set the provider instance ID.
*
* This should only be used by {@link com.android.server.appwidget.AppWidgetService}.
* @hide
*/
public void setProviderInstanceId(long id) {
mProviderInstanceId = id;
}
/**
* Get the provider instance id.
*
* This should uniquely identifies {@link RemoteViews} coming from a given App Widget
* Provider. This changes each time the App Widget provider update the {@link RemoteViews} of
* its widget. Returns -1 if the {@link RemoteViews} doesn't come from an App Widget provider.
* @hide
*/
public long getProviderInstanceId() {
return mProviderInstanceId;
}
/**
* Identify the child of this {@link RemoteViews}, or 0 if this is not a child.
*
* The returned value is always a small integer, currently between 0 and 17.
*/
private int getChildId(@NonNull RemoteViews child) {
if (child == this) {
return 0;
}
if (hasSizedRemoteViews()) {
for (int i = 0; i < mSizedRemoteViews.size(); i++) {
if (mSizedRemoteViews.get(i) == child) {
return i + 1;
}
}
}
if (hasLandscapeAndPortraitLayouts()) {
if (mLandscape == child) {
return 1;
} else if (mPortrait == child) {
return 2;
}
}
// This is not a child of this RemoteViews.
return 0;
}
/**
* Identify uniquely this RemoteViews, or returns -1 if not possible.
*
* @param parent If the {@link RemoteViews} is not a root {@link RemoteViews}, this should be
* the parent that contains it.
*
* @hide
*/
public long computeUniqueId(@Nullable RemoteViews parent) {
if (mIsRoot) {
long viewId = getProviderInstanceId();
if (viewId != -1) {
viewId <<= 8;
}
return viewId;
}
if (parent == null) {
return -1;
}
long viewId = parent.getProviderInstanceId();
if (viewId == -1) {
return -1;
}
int childId = parent.getChildId(this);
if (childId == -1) {
return -1;
}
viewId <<= 8;
viewId |= childId;
return viewId;
}
@Nullable
private static Pair<String, Integer> getPackageUserKey(@Nullable ApplicationInfo info) {
if (info == null || info.packageName == null) return null;
return Pair.create(info.packageName, info.uid);
}
private HierarchyRootData getHierarchyRootData() {
return new HierarchyRootData(mBitmapCache, mApplicationInfoCache, mClassCookies);
}
private static final class HierarchyRootData {
final BitmapCache mBitmapCache;
final ApplicationInfoCache mApplicationInfoCache;
final Map<Class, Object> mClassCookies;
HierarchyRootData(
BitmapCache bitmapCache,
ApplicationInfoCache applicationInfoCache,
Map<Class, Object> classCookies) {
mBitmapCache = bitmapCache;
mApplicationInfoCache = applicationInfoCache;
mClassCookies = classCookies;
}
}
}
|