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
|
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/ash/holding_space/holding_space_keyed_service.h"
#include <map>
#include <string>
#include <vector>
#include "ash/constants/ash_features.h"
#include "ash/constants/ash_switches.h"
#include "ash/public/cpp/holding_space/holding_space_client.h"
#include "ash/public/cpp/holding_space/holding_space_constants.h"
#include "ash/public/cpp/holding_space/holding_space_controller.h"
#include "ash/public/cpp/holding_space/holding_space_controller_observer.h"
#include "ash/public/cpp/holding_space/holding_space_file.h"
#include "ash/public/cpp/holding_space/holding_space_image.h"
#include "ash/public/cpp/holding_space/holding_space_item.h"
#include "ash/public/cpp/holding_space/holding_space_model.h"
#include "ash/public/cpp/holding_space/holding_space_progress.h"
#include "ash/public/cpp/holding_space/holding_space_util.h"
#include "ash/public/cpp/image_util.h"
#include "ash/session/session_controller_impl.h"
#include "ash/shell.h"
#include "base/containers/fixed_flat_set.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/memory/raw_ptr.h"
#include "base/scoped_observation.h"
#include "base/test/bind.h"
#include "base/test/gmock_callback_support.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/scoped_feature_list.h"
#include "base/test/test_future.h"
#include "base/time/time.h"
#include "base/time/time_override.h"
#include "chrome/browser/ash/arc/fileapi/arc_file_system_bridge.h"
#include "chrome/browser/ash/file_manager/fileapi_util.h"
#include "chrome/browser/ash/file_manager/path_util.h"
#include "chrome/browser/ash/file_manager/trash_common_util.h"
#include "chrome/browser/ash/file_manager/trash_io_task.h"
#include "chrome/browser/ash/file_manager/volume_manager.h"
#include "chrome/browser/ash/file_manager/volume_manager_factory.h"
#include "chrome/browser/ash/file_suggest/file_suggest_keyed_service_factory.h"
#include "chrome/browser/ash/file_suggest/file_suggest_test_util.h"
#include "chrome/browser/ash/file_suggest/file_suggest_util.h"
#include "chrome/browser/ash/file_suggest/mock_file_suggest_keyed_service.h"
#include "chrome/browser/ash/profiles/profile_helper.h"
#include "chrome/browser/file_system_access/chrome_file_system_access_permission_context.h"
#include "chrome/browser/file_system_access/file_system_access_permission_context_factory.h"
#include "chrome/browser/nearby_sharing/common/nearby_share_features.h"
#include "chrome/browser/prefs/browser_prefs.h"
#include "chrome/browser/ui/ash/holding_space/holding_space_keyed_service_factory.h"
#include "chrome/browser/ui/ash/holding_space/holding_space_persistence_delegate.h"
#include "chrome/browser/ui/ash/holding_space/holding_space_test_util.h"
#include "chrome/browser/ui/ash/holding_space/holding_space_util.h"
#include "chrome/browser/ui/ash/holding_space/scoped_test_mount_point.h"
#include "chrome/browser/ui/webui/print_preview/pdf_printer_handler.h"
#include "chrome/test/base/browser_with_test_window_test.h"
#include "chrome/test/base/testing_profile_manager.h"
#include "chromeos/ash/components/disks/disk_mount_manager.h"
#include "chromeos/ash/components/disks/fake_disk_mount_manager.h"
#include "chromeos/ash/experiences/arc/session/arc_service_manager.h"
#include "chromeos/ui/base/file_icon_util.h"
#include "components/account_id/account_id.h"
#include "components/pref_registry/pref_registry_syncable.h"
#include "components/sync_preferences/pref_service_mock_factory.h"
#include "components/sync_preferences/pref_service_syncable.h"
#include "components/user_manager/test_helper.h"
#include "components/user_manager/user_names.h"
#include "components/vector_icons/vector_icons.h"
#include "content/public/test/fake_download_item.h"
#include "content/public/test/mock_download_manager.h"
#include "google_apis/gaia/gaia_id.h"
#include "storage/browser/file_system/file_system_context.h"
#include "storage/browser/file_system/file_system_url.h"
#include "storage/browser/test/async_file_test_helper.h"
#include "storage/browser/test/test_file_system_context.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "ui/chromeos/styles/cros_styles.h"
#include "ui/gfx/image/image_skia.h"
#include "ui/gfx/image/image_skia_operations.h"
#include "ui/gfx/image/image_unittest_util.h"
#include "ui/gfx/paint_vector_icon.h"
#include "ui/gfx/skia_util.h"
namespace ash {
namespace {
// Aliases ---------------------------------------------------------------------
using ::ash::holding_space::ScopedTestMountPoint;
using ::ash::holding_space_metrics::FilePickerBindingContext;
using ::base::Bucket;
using ::base::BucketsAre;
using ::base::BucketsAreArray;
using ::testing::AllOf;
using ::testing::Conditional;
using ::testing::ElementsAre;
using ::testing::Eq;
using ::testing::Field;
using ::testing::IsEmpty;
using ::testing::IsFalse;
using ::testing::IsTrue;
using ::testing::Pointee;
using ::testing::Property;
using ::testing::ResultOf;
using ::testing::Value;
// Constants -------------------------------------------------------------------
constexpr char kTotalCountV2HistogramPrefix[] =
"HoldingSpace.Item.TotalCountV2";
// Helpers ---------------------------------------------------------------------
// Returns whether the bitmaps backing the specified `gfx::ImageSkia` are equal.
bool BitmapsAreEqual(const gfx::ImageSkia& a, const gfx::ImageSkia& b) {
return gfx::BitmapsAreEqual(*a.bitmap(), *b.bitmap());
}
// Creates an empty holding space image.
std::unique_ptr<HoldingSpaceImage> CreateTestHoldingSpaceImage(
HoldingSpaceItem::Type type,
const base::FilePath& file_path) {
return std::make_unique<HoldingSpaceImage>(
holding_space_util::GetMaxImageSizeForType(type), file_path,
/*async_bitmap_resolver=*/base::DoNothing());
}
std::unique_ptr<KeyedService> BuildArcFileSystemBridge(
content::BrowserContext* context) {
EXPECT_TRUE(arc::ArcServiceManager::Get());
EXPECT_TRUE(arc::ArcServiceManager::Get()->arc_bridge_service());
return std::make_unique<arc::ArcFileSystemBridge>(
context, arc::ArcServiceManager::Get()->arc_bridge_service());
}
std::unique_ptr<KeyedService> BuildVolumeManager(
content::BrowserContext* context) {
return std::make_unique<file_manager::VolumeManager>(
Profile::FromBrowserContext(context),
nullptr /* drive_integration_service */,
nullptr /* power_manager_client */,
disks::DiskMountManager::GetInstance(),
nullptr /* file_system_provider_service */,
file_manager::VolumeManager::GetMtpStorageInfoCallback());
}
HoldingSpaceItem* AddUninitializedItem(HoldingSpaceModel* model,
HoldingSpaceItem::Type type,
const base::FilePath& path) {
// Create a holding space item and use it to create a serialized item
// dictionary.
auto item = HoldingSpaceItem::CreateFileBackedItem(
type,
HoldingSpaceFile(path, HoldingSpaceFile::FileSystemType::kTest,
GURL("filesystem:ignored")),
base::BindOnce(&CreateTestHoldingSpaceImage));
const auto serialized_holding_space_item = item->Serialize();
auto deserialized_item = HoldingSpaceItem::Deserialize(
serialized_holding_space_item,
/*image_resolver=*/base::BindOnce(&CreateTestHoldingSpaceImage));
auto* deserialized_item_ptr = deserialized_item.get();
model->AddItem(std::move(deserialized_item));
return deserialized_item_ptr;
}
// Returns the expected TotalCountV2 histogram samples for the specified
// `model`. The names of histograms returned are:
// * "HoldingSpace.Item.TotalCountV2.All"
// * "HoldingSpace.Item.TotalCountV2.All.FileSystemType.{fs_type}"
// * "HoldingSpace.Item.TotalCountV2.{type}"
// * "HoldingSpace.Item.TotalCountV2.{type}.FileSystemType.{fs_type}"
std::map<std::string, std::vector<Bucket>>
GetExpectedTotalCountV2HistogramSamples(const HoldingSpaceModel* model) {
// Aliases.
using FileSystemType = HoldingSpaceFile::FileSystemType;
using Type = HoldingSpaceItem::Type;
std::map<std::string, std::vector<Bucket>> result;
// Fill "HoldingSpace.Item.TotalCountV2.All".
result.emplace(base::StrCat({kTotalCountV2HistogramPrefix, ".All"}),
std::vector<Bucket>(
{Bucket(/*sample=*/model->items().size(), /*count=*/1u)}));
// File system types are allowlisted based on need to limit the number of
// recorded histograms arising from combinations with holding space item type.
constexpr auto kAllowlistedFsTypes = base::MakeFixedFlatSet<FileSystemType>(
{FileSystemType::kDriveFs, FileSystemType::kLocal});
// Fill "HoldingSpace.Item.TotalCountV2.All.FileSystemType.{fs_type}".
for (const FileSystemType fs_type : kAllowlistedFsTypes) {
result.emplace(
base::StrCat({kTotalCountV2HistogramPrefix, ".All.FileSystemType.",
holding_space_util::ToString(fs_type)}),
std::vector<Bucket>({Bucket(/*sample=*/std::ranges::count(
model->items(), fs_type,
[&](const auto& item) {
return item->file().file_system_type;
}),
/*count=*/1u)}));
}
// Fill "HoldingSpace.Item.TotalCountV2.{type}".
for (const Type type : holding_space_util::GetAllItemTypes()) {
result.emplace(base::StrCat({kTotalCountV2HistogramPrefix, ".",
holding_space_util::ToString(type)}),
std::vector<Bucket>({Bucket(
/*sample=*/std::ranges::count(model->items(), type,
&HoldingSpaceItem::type),
/*count=*/1u)}));
// Fill "HoldingSpace.Item.TotalCountV2.{type}.FileSystemType.{fs_type}".
for (const FileSystemType fs_type : kAllowlistedFsTypes) {
result.emplace(
base::StrCat({kTotalCountV2HistogramPrefix, ".",
holding_space_util::ToString(type), ".FileSystemType.",
holding_space_util::ToString(fs_type)}),
std::vector<Bucket>({Bucket(
/*sample=*/std::ranges::count_if(
model->items(),
[&](const auto& item) {
return item->type() == type &&
item->file().file_system_type == fs_type;
}),
/*count=*/1u)}));
}
}
return result;
}
// Returns a new map of histogram samples having merged `a` and `b`.
std::map<std::string, std::vector<Bucket>> MergeHistogramSamples(
const std::map<std::string, std::vector<Bucket>>& a,
const std::map<std::string, std::vector<Bucket>>& b) {
std::map<std::string, std::vector<Bucket>> result = a;
for (const auto& [name, buckets] : b) {
auto name_it = result.find(name);
// Case: Name did *not* exist in other map. Add all buckets.
if (name_it == result.end()) {
result.emplace(name, buckets);
continue;
}
std::vector<Bucket>& result_buckets = name_it->second;
// Case: Name *did* exist in other map.
for (const auto& bucket : buckets) {
auto bucket_it =
std::ranges::find(result_buckets, bucket.min, &Bucket::min);
// Case: Bucket did *not* exist in other map. Add bucket.
if (bucket_it == result_buckets.end()) {
result_buckets.emplace_back(bucket);
continue;
}
// Case: Bucket *did* exist in other map. Update bucket.
bucket_it->count += bucket.count;
}
}
return result;
}
bool ShouldRestoreFromPersistence(HoldingSpaceItem::Type type) {
if (HoldingSpaceItem::IsSuggestionType(type) &&
!features::IsHoldingSpaceSuggestionsEnabled()) {
return false;
}
return true;
}
// Waiters ---------------------------------------------------------------------
// Utility class which can wait until a `HoldingSpaceModel` for a given profile
// is attached to the `HoldingSpaceController`.
class HoldingSpaceModelAttachedWaiter : public HoldingSpaceControllerObserver {
public:
explicit HoldingSpaceModelAttachedWaiter(Profile* profile)
: profile_(profile) {
holding_space_controller_observation_.Observe(
HoldingSpaceController::Get());
}
void Wait() {
if (IsModelAttached()) {
return;
}
wait_loop_ = std::make_unique<base::RunLoop>();
wait_loop_->Run();
wait_loop_.reset();
}
private:
// HoldingSpaceControllerObserver:
void OnHoldingSpaceModelAttached(HoldingSpaceModel* model) override {
if (wait_loop_ && IsModelAttached()) {
wait_loop_->Quit();
}
}
bool IsModelAttached() const {
HoldingSpaceKeyedService* const holding_space_service =
HoldingSpaceKeyedServiceFactory::GetInstance()->GetService(profile_);
return HoldingSpaceController::Get()->model() ==
holding_space_service->model_for_testing();
}
const raw_ptr<Profile> profile_;
base::ScopedObservation<HoldingSpaceController,
HoldingSpaceControllerObserver>
holding_space_controller_observation_{this};
std::unique_ptr<base::RunLoop> wait_loop_;
};
class ItemUpdatedWaiter : public HoldingSpaceModelObserver {
public:
ItemUpdatedWaiter(HoldingSpaceModel* model, const HoldingSpaceItem* item)
: wait_item_(item) {
model_observer_.Observe(model);
}
ItemUpdatedWaiter(const ItemUpdatedWaiter&) = delete;
ItemUpdatedWaiter& operator=(const ItemUpdatedWaiter&) = delete;
~ItemUpdatedWaiter() override = default;
void Wait() {
ASSERT_TRUE(wait_item_);
ASSERT_FALSE(wait_loop_);
if (wait_item_updated_) {
// The item has already been updated, no waiting necessary.
wait_item_updated_ = false;
return;
}
wait_loop_ = std::make_unique<base::RunLoop>();
wait_loop_->Run();
wait_loop_.reset();
}
private:
// HoldingSpaceModelObserver:
void OnHoldingSpaceItemUpdated(
const HoldingSpaceItem* item,
const HoldingSpaceItemUpdatedFields& updated_fields) override {
if (!wait_loop_) {
// `wait_loop_` is nullptr, if wait has not yet been called.
if (item == wait_item_) {
wait_item_updated_ = true;
}
return;
}
if (item == wait_item_) {
wait_loop_->Quit();
}
}
raw_ptr<const HoldingSpaceItem> wait_item_ = nullptr;
std::unique_ptr<base::RunLoop> wait_loop_;
bool wait_item_updated_ = false;
base::ScopedObservation<HoldingSpaceModel, HoldingSpaceModelObserver>
model_observer_{this};
};
class ItemRemovedWaiter : public HoldingSpaceModelObserver {
public:
ItemRemovedWaiter(HoldingSpaceModel* model, const HoldingSpaceItem* item)
: wait_item_(item) {
model_observer_.Observe(model);
}
ItemRemovedWaiter(const ItemRemovedWaiter&) = delete;
ItemRemovedWaiter& operator=(const ItemRemovedWaiter&) = delete;
~ItemRemovedWaiter() override = default;
void Wait() {
ASSERT_TRUE(wait_item_);
ASSERT_FALSE(wait_loop_);
if (wait_item_removed_) {
// The item has already been removed, no waiting necessary.
wait_item_removed_ = false;
return;
}
wait_loop_ = std::make_unique<base::RunLoop>();
wait_loop_->Run();
wait_loop_.reset();
}
private:
// HoldingSpaceModelObserver:
void OnHoldingSpaceItemsRemoved(
const std::vector<const HoldingSpaceItem*>& items) override {
if (items.size() != 1 || items[0] != wait_item_) {
return;
}
if (wait_loop_) {
wait_loop_->Quit();
} else {
wait_item_removed_ = true;
}
}
raw_ptr<const HoldingSpaceItem, DanglingUntriaged> wait_item_ = nullptr;
std::unique_ptr<base::RunLoop> wait_loop_;
bool wait_item_removed_ = false;
base::ScopedObservation<HoldingSpaceModel, HoldingSpaceModelObserver>
model_observer_{this};
};
class ItemsInitializedWaiter : public HoldingSpaceModelObserver {
public:
// Predicate that determines whether the waiter should wait for an item to be
// initialized.
using ItemFilter =
base::RepeatingCallback<bool(const HoldingSpaceItem* item)>;
explicit ItemsInitializedWaiter(HoldingSpaceModel* model) : model_(model) {}
ItemsInitializedWaiter(const ItemsInitializedWaiter&) = delete;
ItemsInitializedWaiter& operator=(const ItemsInitializedWaiter&) = delete;
~ItemsInitializedWaiter() override = default;
// NOTE: The filter defaults to all items.
void Wait(const ItemFilter& filter = ItemFilter()) {
ASSERT_FALSE(wait_loop_);
filter_ = filter;
if (FilteredItemsInitialized()) {
return;
}
base::ScopedObservation<HoldingSpaceModel, HoldingSpaceModelObserver>
model_observer{this};
model_observer.Observe(model_.get());
wait_loop_ = std::make_unique<base::RunLoop>();
wait_loop_->Run();
wait_loop_.reset();
filter_ = ItemFilter();
}
void OnHoldingSpaceItemsRemoved(
const std::vector<const HoldingSpaceItem*>& items) override {
if (FilteredItemsInitialized()) {
wait_loop_->Quit();
}
}
void OnHoldingSpaceItemInitialized(const HoldingSpaceItem* item) override {
if (FilteredItemsInitialized()) {
wait_loop_->Quit();
}
}
private:
bool FilteredItemsInitialized() const {
for (auto& item : model_->items()) {
if (filter_ && !filter_.Run(item.get())) {
continue;
}
if (!item->IsInitialized()) {
return false;
}
}
return true;
}
const raw_ptr<HoldingSpaceModel> model_;
ItemFilter filter_;
std::unique_ptr<base::RunLoop> wait_loop_;
};
class ItemImageUpdateWaiter {
public:
explicit ItemImageUpdateWaiter(const HoldingSpaceItem* item) {
image_subscription_ =
item->image().AddImageSkiaChangedCallback(base::BindRepeating(
&ItemImageUpdateWaiter::OnHoldingSpaceItemImageChanged,
base::Unretained(this)));
}
ItemImageUpdateWaiter(const ItemImageUpdateWaiter&) = delete;
ItemImageUpdateWaiter& operator=(const ItemImageUpdateWaiter&) = delete;
~ItemImageUpdateWaiter() = default;
void Wait() { run_loop_.Run(); }
private:
void OnHoldingSpaceItemImageChanged() { run_loop_.Quit(); }
base::RunLoop run_loop_;
base::CallbackListSubscription image_subscription_;
};
// Mocks -----------------------------------------------------------------------
// A mock `content::DownloadManager` which can notify observers of events.
class MockDownloadManager : public content::MockDownloadManager {
public:
// content::MockDownloadManager:
void AddObserver(Observer* observer) override {
observers_.AddObserver(observer);
}
void RemoveObserver(Observer* observer) override {
observers_.RemoveObserver(observer);
}
void Shutdown() override {
for (auto& observer : observers_) {
observer.ManagerGoingDown(this);
}
}
void NotifyDownloadCreated(download::DownloadItem* item) {
for (auto& observer : observers_) {
observer.OnDownloadCreated(this, item);
}
}
private:
base::ObserverList<content::DownloadManager::Observer>::Unchecked observers_;
};
} // namespace
// HoldingSpaceKeyedServiceTest ------------------------------------------------
class HoldingSpaceKeyedServiceTest : public BrowserWithTestWindowTest {
public:
HoldingSpaceKeyedServiceTest()
: BrowserWithTestWindowTest(
base::test::TaskEnvironment::TimeSource::MOCK_TIME) {
HoldingSpaceImage::SetUseZeroInvalidationDelayForTesting(true);
}
HoldingSpaceKeyedServiceTest(const HoldingSpaceKeyedServiceTest& other) =
delete;
HoldingSpaceKeyedServiceTest& operator=(
const HoldingSpaceKeyedServiceTest& other) = delete;
~HoldingSpaceKeyedServiceTest() override {
HoldingSpaceImage::SetUseZeroInvalidationDelayForTesting(false);
}
// BrowserWithTestWindowTest:
void SetUp() override {
ash::ProfileHelper::SetProfileToUserForTestingEnabled(true);
// The test's task environment starts with a mock time close to the Unix
// epoch, but the files that back holding space items are created with
// accurate timestamps. Advance the clock so that the test's mock time and
// the time used for file operations are in sync for file age calculations.
task_environment()->AdvanceClock(base::subtle::TimeNowIgnoringOverride() -
base::Time::Now());
// Needed by `file_manager::VolumeManager`.
disks::DiskMountManager::InitializeForTesting(
new disks::FakeDiskMountManager);
// Needed for `app_list::MockFileSuggestKeyedService`.
ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
BrowserWithTestWindowTest::SetUp();
WaitUntilFileSuggestServiceReady(
FileSuggestKeyedServiceFactory::GetInstance()->GetService(
GetProfile()));
}
void TearDown() override {
BrowserWithTestWindowTest::TearDown();
disks::DiskMountManager::Shutdown();
ash::ProfileHelper::SetProfileToUserForTestingEnabled(false);
}
TestingProfile::TestingFactories GetTestingFactories() override {
return {
TestingProfile::TestingFactory{
arc::ArcFileSystemBridge::GetFactory(),
base::BindRepeating(&BuildArcFileSystemBridge)},
TestingProfile::TestingFactory{
file_manager::VolumeManagerFactory::GetInstance(),
base::BindRepeating(&BuildVolumeManager)},
TestingProfile::TestingFactory{
FileSuggestKeyedServiceFactory::GetInstance(),
base::BindRepeating(
&MockFileSuggestKeyedService::BuildMockFileSuggestKeyedService,
temp_dir_.GetPath())}};
}
TestingProfile* CreateProfile(const std::string& profile_name) override {
auto* profile = BrowserWithTestWindowTest::CreateProfile(profile_name);
SetUpDownloadManager(profile);
return profile;
}
TestingProfile* CreateSecondaryProfile(
std::unique_ptr<sync_preferences::PrefServiceSyncable> prefs = nullptr) {
constexpr char kSecondaryProfileName[] = "secondary_profile";
const GaiaId kFakeGaia2("fakegaia2");
LogIn(kSecondaryProfileName, kFakeGaia2);
return profile_manager()->CreateTestingProfile(
kSecondaryProfileName, std::move(prefs), /*user_name=*/std::u16string(),
/*avatar_id=*/0, GetTestingFactories());
}
using PopulatePrefStoreCallback = base::OnceCallback<void(TestingPrefStore*)>;
TestingProfile* CreateSecondaryProfile(PopulatePrefStoreCallback callback) {
// Create and initialize pref registry.
auto registry = base::MakeRefCounted<user_prefs::PrefRegistrySyncable>();
RegisterUserProfilePrefs(registry.get());
// Create and initialize pref store.
auto pref_store = base::MakeRefCounted<TestingPrefStore>();
std::move(callback).Run(pref_store.get());
// Create and initialize pref factory.
sync_preferences::PrefServiceMockFactory prefs_factory;
prefs_factory.set_user_prefs(pref_store);
// Create and return profile.
return CreateSecondaryProfile(prefs_factory.CreateSyncable(registry));
}
void ActivateSecondaryProfile() {
const std::string kSecondaryProfileName = "secondary_profile";
const AccountId account_id(AccountId::FromUserEmail(kSecondaryProfileName));
ash::Shell::Get()->session_controller()->SwitchActiveUser(account_id);
}
// Resolves an absolute file path in the file manager's file system context,
// and returns the file's file system URL.
GURL GetFileSystemUrl(Profile* profile,
const base::FilePath& absolute_file_path) {
GURL file_system_url;
EXPECT_TRUE(file_manager::util::ConvertAbsoluteFilePathToFileSystemUrl(
profile, absolute_file_path, file_manager::util::GetFileManagerURL(),
&file_system_url));
return file_system_url;
}
// Resolves a file system URL in the file manager's file system context, and
// returns the file's virtual path relative to the mount point root.
// Returns an empty file if the URL cannot be resolved to a file. For example,
// if it's not well formed, or the file manager app cannot access it.
base::FilePath GetVirtualPathFromUrl(
const GURL& url,
const std::string& expected_mount_point) {
storage::FileSystemContext* fs_context =
file_manager::util::GetFileManagerFileSystemContext(GetProfile());
storage::FileSystemURL fs_url =
fs_context->CrackURLInFirstPartyContext(url);
base::RunLoop run_loop;
base::FilePath result;
base::FilePath* result_ptr = &result;
fs_context->ResolveURL(
fs_url,
base::BindLambdaForTesting(
[&run_loop, &expected_mount_point, &result_ptr](
base::File::Error result, const storage::FileSystemInfo& info,
const base::FilePath& file_path,
storage::FileSystemContext::ResolvedEntryType type) {
EXPECT_EQ(base::File::Error::FILE_OK, result);
EXPECT_EQ(storage::FileSystemContext::RESOLVED_ENTRY_FILE, type);
if (expected_mount_point == info.name) {
*result_ptr = file_path;
} else {
ADD_FAILURE() << "Mount point name '" << info.name
<< "' does not match expected '"
<< expected_mount_point << "'";
}
run_loop.Quit();
}));
run_loop.Run();
return result;
}
// Creates and returns a fake download item for `profile` with the specified
// `state`, `file_path`, `target_file_path`, `received_bytes`, and
// `total_bytes`.
std::unique_ptr<content::FakeDownloadItem> CreateFakeDownloadItem(
Profile* profile,
download::DownloadItem::DownloadState state,
const base::FilePath& file_path,
const base::FilePath& target_file_path,
int64_t received_bytes,
int64_t total_bytes) {
auto fake_download_item = std::make_unique<content::FakeDownloadItem>();
fake_download_item->SetDummyFilePath(file_path);
fake_download_item->SetReceivedBytes(received_bytes);
fake_download_item->SetState(state);
fake_download_item->SetTargetFilePath(target_file_path);
fake_download_item->SetTotalBytes(total_bytes);
// Notify observers of the created download.
download_managers_[profile]->NotifyDownloadCreated(
fake_download_item.get());
return fake_download_item;
}
protected:
// Creates a `MockDownloadManager` for `profile` to use.
void SetUpDownloadManager(Profile* profile) {
auto manager = std::make_unique<testing::NiceMock<MockDownloadManager>>();
ON_CALL(*manager, IsManagerInitialized)
.WillByDefault(testing::Return(true));
download_managers_[profile] = manager.get();
profile->SetDownloadManagerForTesting(std::move(manager));
}
private:
std::map<Profile*,
raw_ptr<testing::NiceMock<MockDownloadManager>, CtnExperimental>>
download_managers_;
arc::ArcServiceManager arc_service_manager_;
base::ScopedTempDir temp_dir_;
};
class HoldingSpaceKeyedServiceWithExperimentalFeatureTest
: public HoldingSpaceKeyedServiceTest,
public testing::WithParamInterface<
/*enable_suggestions=*/bool> {
public:
HoldingSpaceKeyedServiceWithExperimentalFeatureTest() {
std::vector<base::test::FeatureRef> enabled_features;
std::vector<base::test::FeatureRef> disabled_features;
(GetParam() ? enabled_features : disabled_features)
.push_back(features::kHoldingSpaceSuggestions);
scoped_feature_list_.InitWithFeatures(enabled_features, disabled_features);
}
private:
base::test::ScopedFeatureList scoped_feature_list_;
};
INSTANTIATE_TEST_SUITE_P(All,
HoldingSpaceKeyedServiceWithExperimentalFeatureTest,
/*enabled_suggestions=*/testing::Bool());
class HoldingSpaceKeyedServiceWithExperimentalFeatureForGuestTest
: public HoldingSpaceKeyedServiceWithExperimentalFeatureTest {
public:
HoldingSpaceKeyedServiceWithExperimentalFeatureForGuestTest() {
// To let ProfileHelper::GetUserByProfile() directly return
// the created guest user, without faking directory paths.
base::CommandLine::ForCurrentProcess()->AppendSwitch(
ash::switches::kIgnoreUserProfileMappingForTests);
}
void TearDown() override {
// Drop user pref service reference before `profile_` is released. This is
// needed because `profile_` is owned by the test not `TestProfileManager`.
ash_test_helper()->prefs_provider()->ClearUnownedUserPrefs(
AccountId::FromUserEmail(profile_->GetProfileUserName()));
profile_ = nullptr;
HoldingSpaceKeyedServiceWithExperimentalFeatureTest::TearDown();
}
std::optional<std::string> GetDefaultProfileName() override {
return user_manager::kGuestUserName;
}
void LogIn(std::string_view email, const GaiaId& gaia_id) override {
CHECK_EQ(email, user_manager::kGuestUserName);
auto* user = user_manager()->AddGuestUser();
user_manager()->UserLoggedIn(
user->GetAccountId(),
user_manager::TestHelper::GetFakeUsernameHash(user->GetAccountId()));
}
TestingProfile* CreateProfile(const std::string& profile_name) override {
CHECK_EQ(profile_name, user_manager::kGuestUserName);
CHECK(!profile_);
// Construct a guest session profile.
// Profile is created outside of TestingProfileManager management
// to inject more factories.
TestingProfile::Builder guest_profile_builder;
guest_profile_builder.AddTestingFactories(
{TestingProfile::TestingFactory{
arc::ArcFileSystemBridge::GetFactory(),
base::BindRepeating(&BuildArcFileSystemBridge)},
TestingProfile::TestingFactory{
file_manager::VolumeManagerFactory::GetInstance(),
base::BindRepeating(&BuildVolumeManager)}});
profile_ =
profile_manager()->CreateGuestProfile(std::move(guest_profile_builder));
return profile_;
}
std::unique_ptr<Browser> CreateBrowser(
Profile* profile,
Browser::Type browser_type,
bool hosted_app,
BrowserWindow* browser_window) override {
// Do not create browser.
return nullptr;
}
private:
raw_ptr<TestingProfile> profile_;
};
INSTANTIATE_TEST_SUITE_P(
All,
HoldingSpaceKeyedServiceWithExperimentalFeatureForGuestTest,
/*enabled_suggestions=*/testing::Bool());
TEST_P(HoldingSpaceKeyedServiceWithExperimentalFeatureForGuestTest,
GuestUserProfile) {
auto* guest_profile = profile();
// Service instances should be created for guest sessions but note that the
// service factory will redirect to use the primary OTR profile.
ASSERT_TRUE(guest_profile);
ASSERT_FALSE(guest_profile->IsOffTheRecord());
HoldingSpaceKeyedService* const guest_profile_service =
HoldingSpaceKeyedServiceFactory::GetInstance()->GetService(guest_profile);
ASSERT_TRUE(guest_profile_service);
// Since the service factory redirects to use the primary OTR profile in the
// case of guest sessions, retrieving the service instance for the primary OTR
// profile should yield the same result as retrieving the service instance for
// a non-OTR guest session profile.
ASSERT_TRUE(guest_profile->GetPrimaryOTRProfile(/*create_if_needed=*/true));
HoldingSpaceKeyedService* const primary_otr_guest_profile_service =
HoldingSpaceKeyedServiceFactory::GetInstance()->GetService(
guest_profile->GetPrimaryOTRProfile(/*create_if_needed=*/true));
ASSERT_EQ(guest_profile_service, primary_otr_guest_profile_service);
}
TEST_P(HoldingSpaceKeyedServiceWithExperimentalFeatureTest,
OffTheRecordProfile) {
// Service instances should be created for on the record profiles.
HoldingSpaceKeyedService* const primary_profile_service =
HoldingSpaceKeyedServiceFactory::GetInstance()->GetService(GetProfile());
ASSERT_TRUE(primary_profile_service);
// Construct an incognito profile from the primary profile.
TestingProfile::Builder incognito_primary_profile_builder;
incognito_primary_profile_builder.SetProfileName(
GetProfile()->GetProfileUserName());
Profile* const incognito_primary_profile =
incognito_primary_profile_builder.BuildIncognito(GetProfile());
ASSERT_TRUE(incognito_primary_profile);
ASSERT_TRUE(incognito_primary_profile->IsOffTheRecord());
// Service instances should *not* typically be created for OTR profiles. The
// once exception is for guest users who redirect to use original profile.
HoldingSpaceKeyedService* const incognito_primary_profile_service =
HoldingSpaceKeyedServiceFactory::GetInstance()->GetService(
incognito_primary_profile);
ASSERT_FALSE(incognito_primary_profile_service);
}
TEST_P(HoldingSpaceKeyedServiceWithExperimentalFeatureTest,
SecondaryUserProfile) {
HoldingSpaceKeyedService* const primary_holding_space_service =
HoldingSpaceKeyedServiceFactory::GetInstance()->GetService(GetProfile());
TestingProfile* const second_profile = CreateSecondaryProfile();
HoldingSpaceKeyedService* const secondary_holding_space_service =
HoldingSpaceKeyedServiceFactory::GetInstance()->GetService(
second_profile);
// Just creating a secondary profile shouldn't change the active client/model.
EXPECT_EQ(HoldingSpaceController::Get()->client(),
primary_holding_space_service->client());
EXPECT_EQ(HoldingSpaceController::Get()->model(),
primary_holding_space_service->model_for_testing());
// Switching the active user should change the active client/model (multi-user
// support).
ActivateSecondaryProfile();
EXPECT_EQ(HoldingSpaceController::Get()->client(),
secondary_holding_space_service->client());
EXPECT_EQ(HoldingSpaceController::Get()->model(),
secondary_holding_space_service->model_for_testing());
}
TEST_P(HoldingSpaceKeyedServiceWithExperimentalFeatureTest,
RecordsUserPreferencesAtStartUp) {
// Initially expect no user preferences recorded.
base::HistogramTester histogram_tester;
histogram_tester.ExpectTotalCount(
"HoldingSpace.UserPreferences.PreviewsEnabled", /*count=*/0u);
histogram_tester.ExpectTotalCount(
"HoldingSpace.UserPreferences.SuggestionsExpanded", /*count=*/0u);
constexpr bool kPreviewsEnabled = false;
constexpr bool kSuggestionsExpanded = false;
// Create a profile with explicitly set user preferences.
TestingProfile* const secondary_profile = CreateSecondaryProfile(
base::BindLambdaForTesting([&](TestingPrefStore* pref_store) {
pref_store->SetValueSilently(
"ash.holding_space.previews_enabled", base::Value(kPreviewsEnabled),
PersistentPrefStore::DEFAULT_PREF_WRITE_FLAGS);
pref_store->SetValueSilently(
"ash.holding_space.suggestions_expanded",
base::Value(kSuggestionsExpanded),
PersistentPrefStore::DEFAULT_PREF_WRITE_FLAGS);
}));
// Ensure service creation for the created profile.
HoldingSpaceKeyedServiceFactory::GetInstance()->GetService(secondary_profile);
// Expect user preferences recorded.
histogram_tester.ExpectTotalCount(
"HoldingSpace.UserPreferences.PreviewsEnabled", /*count=*/1u);
histogram_tester.ExpectBucketCount(
"HoldingSpace.UserPreferences.PreviewsEnabled",
/*sample=*/kPreviewsEnabled, /*expected_count=*/1u);
histogram_tester.ExpectTotalCount(
"HoldingSpace.UserPreferences.SuggestionsExpanded", /*count=*/1u);
histogram_tester.ExpectBucketCount(
"HoldingSpace.UserPreferences.SuggestionsExpanded",
/*sample=*/kSuggestionsExpanded,
/*expected_count=*/1u);
}
// Verifies that updates to the holding space model are persisted.
TEST_P(HoldingSpaceKeyedServiceWithExperimentalFeatureTest,
UpdatePersistentStorage) {
// Create a file system mount point.
std::unique_ptr<ScopedTestMountPoint> downloads_mount =
ScopedTestMountPoint::CreateAndMountDownloads(GetProfile());
ASSERT_TRUE(downloads_mount->IsValid());
HoldingSpaceKeyedService* const primary_holding_space_service =
HoldingSpaceKeyedServiceFactory::GetInstance()->GetService(GetProfile());
HoldingSpaceModel* const primary_holding_space_model =
HoldingSpaceController::Get()->model();
EXPECT_EQ(primary_holding_space_model,
primary_holding_space_service->model_for_testing());
base::Value::List persisted_holding_space_items;
// Verify persistent storage is updated when adding each type of item.
for (const auto type : holding_space_util::GetAllItemTypes()) {
const base::FilePath file_path = downloads_mount->CreateArbitraryFile();
const GURL file_system_url = GetFileSystemUrl(GetProfile(), file_path);
const HoldingSpaceFile::FileSystemType file_system_type =
holding_space_util::ResolveFileSystemType(GetProfile(),
file_system_url);
auto holding_space_item = HoldingSpaceItem::CreateFileBackedItem(
type, HoldingSpaceFile(file_path, file_system_type, file_system_url),
base::BindOnce(
&holding_space_util::ResolveImage,
primary_holding_space_service->thumbnail_loader_for_testing()));
persisted_holding_space_items.Append(holding_space_item->Serialize());
primary_holding_space_model->AddItem(std::move(holding_space_item));
EXPECT_EQ(GetProfile()->GetPrefs()->GetList(
HoldingSpacePersistenceDelegate::kPersistencePath),
persisted_holding_space_items);
}
// Verify persistent storage is updated when removing each type of item.
while (!primary_holding_space_model->items().empty()) {
const auto* holding_space_item =
primary_holding_space_model->items()[0].get();
persisted_holding_space_items.erase(persisted_holding_space_items.begin());
primary_holding_space_model->RemoveItem(holding_space_item->id());
EXPECT_EQ(GetProfile()->GetPrefs()->GetList(
HoldingSpacePersistenceDelegate::kPersistencePath),
persisted_holding_space_items);
}
}
// Verifies that only finalized holding space items are persisted and that,
// once finalized, previously in progress holding space items are persisted at
// the appropriate index.
TEST_P(HoldingSpaceKeyedServiceWithExperimentalFeatureTest,
PersistenceOfInProgressItems) {
// Create a file system mount point.
std::unique_ptr<ScopedTestMountPoint> downloads_mount =
ScopedTestMountPoint::CreateAndMountDownloads(GetProfile());
ASSERT_TRUE(downloads_mount->IsValid());
// Cache the holding space model.
HoldingSpaceKeyedService* const holding_space_service =
HoldingSpaceKeyedServiceFactory::GetInstance()->GetService(GetProfile());
HoldingSpaceModel* const holding_space_model =
HoldingSpaceController::Get()->model();
EXPECT_EQ(holding_space_model, holding_space_service->model_for_testing());
// Initially, both the model and persistent storage should be empty.
EXPECT_EQ(holding_space_model->items().size(), 0u);
EXPECT_EQ(GetProfile()
->GetPrefs()
->GetList(HoldingSpacePersistenceDelegate::kPersistencePath)
.size(),
0u);
// Add a finalized item to holding space. Because the item is finalized, it
// should immediately be added to persistent storage.
base::FilePath file_path = downloads_mount->CreateArbitraryFile();
GURL file_system_url = GetFileSystemUrl(GetProfile(), file_path);
HoldingSpaceFile::FileSystemType file_system_type =
holding_space_util::ResolveFileSystemType(GetProfile(), file_system_url);
auto finalized_holding_space_item = HoldingSpaceItem::CreateFileBackedItem(
HoldingSpaceItem::Type::kDownload,
HoldingSpaceFile(file_path, file_system_type, file_system_url),
base::BindOnce(&holding_space_util::ResolveImage,
holding_space_service->thumbnail_loader_for_testing()));
auto* finalized_holding_space_item_ptr = finalized_holding_space_item.get();
holding_space_model->AddItem(std::move(finalized_holding_space_item));
base::Value::List persisted_holding_space_items;
persisted_holding_space_items.Append(
finalized_holding_space_item_ptr->Serialize());
EXPECT_EQ(GetProfile()->GetPrefs()->GetList(
HoldingSpacePersistenceDelegate::kPersistencePath),
persisted_holding_space_items);
// Add an in-progress item to holding space. Because the item is in progress,
// it should *not* be added to persistent storage.
file_path = downloads_mount->CreateArbitraryFile();
file_system_url = GetFileSystemUrl(GetProfile(), file_path);
file_system_type =
holding_space_util::ResolveFileSystemType(GetProfile(), file_system_url);
auto in_progress_holding_space_item = HoldingSpaceItem::CreateFileBackedItem(
HoldingSpaceItem::Type::kDownload,
HoldingSpaceFile(file_path, file_system_type,
GetFileSystemUrl(GetProfile(), file_path)),
HoldingSpaceProgress(/*current_bytes=*/50, /*total_bytes=*/100),
base::BindOnce(&holding_space_util::ResolveImage,
holding_space_service->thumbnail_loader_for_testing()));
auto* in_progress_holding_space_item_ptr =
in_progress_holding_space_item.get();
holding_space_model->AddItem(std::move(in_progress_holding_space_item));
EXPECT_EQ(GetProfile()->GetPrefs()->GetList(
HoldingSpacePersistenceDelegate::kPersistencePath),
persisted_holding_space_items);
// Add another finalized item to holding space. Because the item is finalized,
// it should immediately be added to persistent storage.
file_path = downloads_mount->CreateArbitraryFile();
file_system_url = GetFileSystemUrl(GetProfile(), file_path);
file_system_type =
holding_space_util::ResolveFileSystemType(GetProfile(), file_system_url);
finalized_holding_space_item = HoldingSpaceItem::CreateFileBackedItem(
HoldingSpaceItem::Type::kDownload,
HoldingSpaceFile(file_path, file_system_type, file_system_url),
base::BindOnce(&holding_space_util::ResolveImage,
holding_space_service->thumbnail_loader_for_testing()));
finalized_holding_space_item_ptr = finalized_holding_space_item.get();
holding_space_model->AddItem(std::move(finalized_holding_space_item));
persisted_holding_space_items.Append(
finalized_holding_space_item_ptr->Serialize());
EXPECT_EQ(GetProfile()->GetPrefs()->GetList(
HoldingSpacePersistenceDelegate::kPersistencePath),
persisted_holding_space_items);
// Update the file path for a finalized item. Because the item is finalized,
// it should be updated immediately in persistent storage.
file_path = downloads_mount->CreateArbitraryFile();
file_system_url = GetFileSystemUrl(GetProfile(), file_path);
file_system_type =
holding_space_util::ResolveFileSystemType(GetProfile(), file_system_url);
holding_space_model->UpdateItem(finalized_holding_space_item_ptr->id())
->SetBackingFile(
HoldingSpaceFile(file_path, file_system_type, file_system_url));
ASSERT_EQ(persisted_holding_space_items.size(), 2u);
persisted_holding_space_items[1u] =
base::Value(finalized_holding_space_item_ptr->Serialize());
EXPECT_EQ(GetProfile()->GetPrefs()->GetList(
HoldingSpacePersistenceDelegate::kPersistencePath),
persisted_holding_space_items);
// Update the file path for the in-progress item. Because the item is still in
// progress, it should not be added/updated to/in persistent storage.
file_path = downloads_mount->CreateArbitraryFile();
file_system_url = GetFileSystemUrl(GetProfile(), file_path);
file_system_type =
holding_space_util::ResolveFileSystemType(GetProfile(), file_system_url);
holding_space_model->UpdateItem(in_progress_holding_space_item_ptr->id())
->SetBackingFile(
HoldingSpaceFile(file_path, file_system_type, file_system_url));
EXPECT_EQ(GetProfile()->GetPrefs()->GetList(
HoldingSpacePersistenceDelegate::kPersistencePath),
persisted_holding_space_items);
// Update the progress for the in-progress item. Because the item is still in
// progress it should not be added/updated to/in persistent storage.
holding_space_model->UpdateItem(in_progress_holding_space_item_ptr->id())
->SetProgress(
HoldingSpaceProgress(/*current_bytes=*/75, /*total_bytes=*/100));
EXPECT_EQ(GetProfile()->GetPrefs()->GetList(
HoldingSpacePersistenceDelegate::kPersistencePath),
persisted_holding_space_items);
// Mark the in-progress item as finalized. Because the item is finalized, it
// should be added to persistent storage at the appropriate index.
holding_space_model->UpdateItem(in_progress_holding_space_item_ptr->id())
->SetProgress(
HoldingSpaceProgress(/*current_bytes=*/100, /*total_bytes=*/100));
ASSERT_EQ(persisted_holding_space_items.size(), 2u);
persisted_holding_space_items.Insert(
persisted_holding_space_items.begin() + 1u,
base::Value(in_progress_holding_space_item_ptr->Serialize()));
EXPECT_EQ(GetProfile()->GetPrefs()->GetList(
HoldingSpacePersistenceDelegate::kPersistencePath),
persisted_holding_space_items);
}
// Verifies that when a file backing a holding space item is moved, the holding
// space item is updated in place and persistence storage is updated.
TEST_P(HoldingSpaceKeyedServiceWithExperimentalFeatureTest,
UpdatePersistentStorageAfterMove) {
// Create a file system mount point.
std::unique_ptr<ScopedTestMountPoint> downloads_mount =
ScopedTestMountPoint::CreateAndMountDownloads(GetProfile());
ASSERT_TRUE(downloads_mount->IsValid());
// Cache the holding space model for the primary profile.
HoldingSpaceKeyedService* const primary_holding_space_service =
HoldingSpaceKeyedServiceFactory::GetInstance()->GetService(GetProfile());
HoldingSpaceModel* const primary_holding_space_model =
HoldingSpaceController::Get()->model();
ASSERT_EQ(primary_holding_space_model,
primary_holding_space_service->model_for_testing());
// Cache the file system context.
storage::FileSystemContext* context =
file_manager::util::GetFileManagerFileSystemContext(GetProfile());
ASSERT_TRUE(context);
base::Value::List persisted_holding_space_items;
// Verify persistent storage is updated when adding each type of item.
for (const auto type : holding_space_util::GetAllItemTypes()) {
// Note that each item is being added to a unique parent directory so that
// moving the parent directory later will not affect other items.
const base::FilePath file_path = downloads_mount->CreateFile(
base::FilePath(base::NumberToString(static_cast<int>(type)))
.Append("foo.txt"),
/*content=*/std::string());
const GURL file_system_url = GetFileSystemUrl(GetProfile(), file_path);
const HoldingSpaceFile::FileSystemType file_system_type =
holding_space_util::ResolveFileSystemType(GetProfile(),
file_system_url);
// Create the holding space item.
auto holding_space_item = HoldingSpaceItem::CreateFileBackedItem(
type, HoldingSpaceFile(file_path, file_system_type, file_system_url),
base::BindOnce(
&holding_space_util::ResolveImage,
primary_holding_space_service->thumbnail_loader_for_testing()));
// Add the holding space item to the model and verify persistence.
persisted_holding_space_items.Append(holding_space_item->Serialize());
primary_holding_space_model->AddItem(std::move(holding_space_item));
EXPECT_EQ(GetProfile()->GetPrefs()->GetList(
HoldingSpacePersistenceDelegate::kPersistencePath),
persisted_holding_space_items);
}
// Verify persistent storage is updated when moving each type of item and
// that the holding space items themselves are updated in place.
for (size_t i = 0; i < primary_holding_space_model->items().size(); ++i) {
const auto* holding_space_item =
primary_holding_space_model->items()[i].get();
// Rename the file backing the holding space item.
base::FilePath file_path = holding_space_item->file().file_path;
base::FilePath new_file_path = file_path.InsertBeforeExtension(" (Moved)");
GURL file_path_url = GetFileSystemUrl(GetProfile(), file_path);
GURL new_file_path_url = GetFileSystemUrl(GetProfile(), new_file_path);
{
ItemUpdatedWaiter waiter(primary_holding_space_model, holding_space_item);
ASSERT_EQ(
storage::AsyncFileTestHelper::Move(
context, context->CrackURLInFirstPartyContext(file_path_url),
context->CrackURLInFirstPartyContext(new_file_path_url)),
base::File::FILE_OK);
// File changes must be posted to the UI thread, wait for the update to
// reach the holding space model.
waiter.Wait();
}
// Verify that the holding space item has been updated in place.
ASSERT_EQ(holding_space_item->file().file_path, new_file_path);
ASSERT_EQ(holding_space_item->file().file_system_url, new_file_path_url);
ASSERT_EQ(holding_space_item->GetText(),
new_file_path.BaseName().LossyDisplayName());
// Verify that persistence has been updated.
persisted_holding_space_items[i] =
base::Value(holding_space_item->Serialize());
ASSERT_EQ(GetProfile()->GetPrefs()->GetList(
HoldingSpacePersistenceDelegate::kPersistencePath),
persisted_holding_space_items);
// Cache the base name of the file backing the holding space item as it will
// not change due to rename of the holding space item's parent directory.
base::FilePath base_name = holding_space_item->file().file_path.BaseName();
// Rename the file backing the holding space item's parent directory.
file_path = new_file_path.DirName();
new_file_path = file_path.InsertBeforeExtension(" (Moved)");
file_path_url = GetFileSystemUrl(GetProfile(), file_path);
new_file_path_url = GetFileSystemUrl(GetProfile(), new_file_path);
{
ItemUpdatedWaiter waiter(primary_holding_space_model, holding_space_item);
ASSERT_EQ(
storage::AsyncFileTestHelper::Move(
context, context->CrackURLInFirstPartyContext(file_path_url),
context->CrackURLInFirstPartyContext(new_file_path_url)),
base::File::FILE_OK);
// File changes must be posted to the UI thread, wait for the update to
// reach the holding space model.
waiter.Wait();
}
// The file backing the holding space item is expected to have re-parented.
new_file_path = new_file_path.Append(base_name);
new_file_path_url = GetFileSystemUrl(GetProfile(), new_file_path);
// Verify that the holding space item has been updated in place.
ASSERT_EQ(holding_space_item->file().file_path, new_file_path);
ASSERT_EQ(holding_space_item->file().file_system_url, new_file_path_url);
ASSERT_EQ(holding_space_item->GetText(),
new_file_path.BaseName().LossyDisplayName());
// Verify that persistence has been updated.
persisted_holding_space_items[i] =
base::Value(holding_space_item->Serialize());
ASSERT_EQ(GetProfile()->GetPrefs()->GetList(
HoldingSpacePersistenceDelegate::kPersistencePath),
persisted_holding_space_items);
}
}
// Verifies that files that are trashed via the `TrashIOTask` are removed from
// the holding space model.
TEST_P(HoldingSpaceKeyedServiceWithExperimentalFeatureTest,
TrashedFilesAreRemovedFromTheModel) {
// Create a file system mount point.
std::unique_ptr<ScopedTestMountPoint> downloads_mount =
ScopedTestMountPoint::CreateAndMountDownloads(GetProfile());
ASSERT_TRUE(downloads_mount->IsValid());
// Ensure that required trash folders exist for the `downloads_mount`.
const base::FilePath trash_path = downloads_mount->GetRootPath().Append(
file_manager::trash::kTrashFolderName);
ASSERT_TRUE(base::CreateDirectory(
trash_path.Append(file_manager::trash::kFilesFolderName)));
ASSERT_TRUE(base::CreateDirectory(
trash_path.Append(file_manager::trash::kInfoFolderName)));
// Cache the holding space model for the primary profile.
HoldingSpaceKeyedService* const primary_holding_space_service =
HoldingSpaceKeyedServiceFactory::GetInstance()->GetService(GetProfile());
HoldingSpaceModel* const primary_holding_space_model =
HoldingSpaceController::Get()->model();
ASSERT_EQ(primary_holding_space_model,
primary_holding_space_service->model_for_testing());
// Add each item to the holding space model.
for (const auto type : holding_space_util::GetAllItemTypes()) {
const base::FilePath file_path = downloads_mount->CreateFile(
base::FilePath(base::NumberToString(static_cast<int>(type)))
.Append("foo.txt"),
/*content=*/std::string());
const GURL file_system_url = GetFileSystemUrl(GetProfile(), file_path);
const HoldingSpaceFile::FileSystemType file_system_type =
holding_space_util::ResolveFileSystemType(GetProfile(),
file_system_url);
// Create the holding space item.
auto holding_space_item = HoldingSpaceItem::CreateFileBackedItem(
type, HoldingSpaceFile(file_path, file_system_type, file_system_url),
base::BindOnce(
&holding_space_util::ResolveImage,
primary_holding_space_service->thumbnail_loader_for_testing()));
// Add the holding space item to the model.
primary_holding_space_model->AddItem(std::move(holding_space_item));
}
// Use the File Manager's context for testing. Note that we specifically do
// not use a test context since we want a production context which uses file
// system operations that notify the `FileChangeService` on completion.
storage::FileSystemContext* file_system_context =
file_manager::util::GetFileManagerFileSystemContext(GetProfile());
const blink::StorageKey kTestStorageKey =
blink::StorageKey::CreateFromStringForTesting("chrome-extension://abc");
// Keep sending the items in the model to the trash as each "trash" operation
// should remove the item from the model.
while (!primary_holding_space_model->items().empty()) {
const auto* holding_space_item =
primary_holding_space_model->items()[0].get();
base::FilePath file_path = holding_space_item->file().file_path;
ItemRemovedWaiter waiter(primary_holding_space_model, holding_space_item);
base::test::TestFuture<file_manager::io_task::ProgressStatus> status;
file_manager::io_task::TrashIOTask task(
{file_system_context->CrackURLInFirstPartyContext(
GetFileSystemUrl(GetProfile(), file_path))},
GetProfile(), file_system_context, /*base_path=*/base::FilePath());
task.Execute(base::DoNothing(), status.GetCallback());
EXPECT_EQ(status.Get().state, file_manager::io_task::State::kSuccess);
waiter.Wait();
}
// After trashing all the items (they now reside in .Trash/files/foo.txt) they
// should not be visible in the holding space model.
ASSERT_EQ(primary_holding_space_model->items().size(), 0u);
}
// Tests that holding space item's image representation gets updated when the
// backing file is changed using move operation. Furthermore, verifies that
// conflicts caused by moving a holding space item file to another path present
// in the holding space get resolved.
TEST_P(HoldingSpaceKeyedServiceWithExperimentalFeatureTest,
UpdateItemsOverwrittenByMove) {
// Create a file system mount point.
std::unique_ptr<ScopedTestMountPoint> downloads_mount =
ScopedTestMountPoint::CreateAndMountDownloads(GetProfile());
ASSERT_TRUE(downloads_mount->IsValid());
// Cache the holding space model for the primary profile.
HoldingSpaceKeyedService* const primary_holding_space_service =
HoldingSpaceKeyedServiceFactory::GetInstance()->GetService(GetProfile());
HoldingSpaceModel* const primary_holding_space_model =
HoldingSpaceController::Get()->model();
ASSERT_EQ(primary_holding_space_model,
primary_holding_space_service->model_for_testing());
// Cache the file system context.
storage::FileSystemContext* context =
file_manager::util::GetFileManagerFileSystemContext(GetProfile());
ASSERT_TRUE(context);
struct ItemInfo {
std::string item_id;
base::FilePath path;
GURL file_system_url;
HoldingSpaceFile::FileSystemType file_system_type;
};
struct TestCase {
ItemInfo src;
ItemInfo dst;
};
std::map<HoldingSpaceItem::Type, TestCase> test_config;
base::Value::List persisted_holding_space_items;
// Configure holding space state for the test. For each item adds two holding
// space items to the model - "src" and "dst" (during the test, the src item's
// file will be moved to the dst item's path).
for (const auto type : holding_space_util::GetAllItemTypes()) {
auto add_item = [&](const std::string& file_name, ItemInfo* info) {
info->path = downloads_mount->CreateFile(
base::FilePath(base::NumberToString(static_cast<int>(type)))
.Append(file_name),
/*content=*/std::string());
info->file_system_url = GetFileSystemUrl(GetProfile(), info->path);
info->file_system_type = holding_space_util::ResolveFileSystemType(
GetProfile(), info->file_system_url);
// Create the holding space item.
auto holding_space_item = HoldingSpaceItem::CreateFileBackedItem(
type,
HoldingSpaceFile(info->path, info->file_system_type,
info->file_system_url),
base::BindOnce(
&holding_space_util::ResolveImage,
primary_holding_space_service->thumbnail_loader_for_testing()));
info->item_id = holding_space_item->id();
// Add the holding space item to the model and verify persistence.
persisted_holding_space_items.Append(holding_space_item->Serialize());
primary_holding_space_model->AddItem(std::move(holding_space_item));
};
TestCase& test_case = test_config[type];
add_item("src.txt", &test_case.src);
add_item("dst.txt", &test_case.dst);
ASSERT_NE(test_case.src.item_id, test_case.dst.item_id);
}
EXPECT_EQ(GetProfile()->GetPrefs()->GetList(
HoldingSpacePersistenceDelegate::kPersistencePath),
persisted_holding_space_items);
base::Value::List final_persisted_holding_space_items;
// Runs the test logic.
for (const auto type : holding_space_util::GetAllItemTypes()) {
const TestCase& test_case = test_config[type];
const HoldingSpaceItem* src_item =
primary_holding_space_model->GetItem(test_case.src.item_id);
ASSERT_TRUE(src_item);
// Move a file that was not in the holding space to the src path. Verify the
// holding space item associated with this path remains in the holding space
// in this case, and that its image representation gets updated.
const base::FilePath path_not_in_holding_space =
downloads_mount->CreateFile(
base::FilePath(base::NumberToString(static_cast<int>(type)))
.Append("not_in_holding_space.txt"),
/*content=*/std::string());
ItemImageUpdateWaiter image_update_waiter(src_item);
ASSERT_EQ(storage::AsyncFileTestHelper::Move(
context,
context->CrackURLInFirstPartyContext(GetFileSystemUrl(
GetProfile(), path_not_in_holding_space)),
context->CrackURLInFirstPartyContext(
src_item->file().file_system_url)),
base::File::FILE_OK);
image_update_waiter.Wait();
ASSERT_EQ(src_item,
primary_holding_space_model->GetItem(test_case.src.item_id));
EXPECT_TRUE(primary_holding_space_model->GetItem(test_case.dst.item_id));
ASSERT_EQ(src_item->file().file_path, test_case.src.path);
ASSERT_EQ(src_item->file().file_system_url, test_case.src.file_system_url);
ASSERT_EQ(src_item->file().file_system_type,
test_case.src.file_system_type);
{
ItemUpdatedWaiter waiter(primary_holding_space_model, src_item);
// Move the file at the source item path to the destination item path.
// Verify that, given that both paths are represented in the holding
// space, the item initially associated with the destination path is
// removed from the holding space (to avoid two items with the same
// backing file).
ASSERT_EQ(storage::AsyncFileTestHelper::Move(
context,
context->CrackURLInFirstPartyContext(
test_case.src.file_system_url),
context->CrackURLInFirstPartyContext(
test_case.dst.file_system_url)),
base::File::FILE_OK);
// File changes must be posted to the UI thread, wait for the update to
// reach the holding space model.
waiter.Wait();
}
const HoldingSpaceItem* item =
primary_holding_space_model->GetItem(test_case.src.item_id);
ASSERT_EQ(src_item,
primary_holding_space_model->GetItem(test_case.src.item_id));
EXPECT_FALSE(primary_holding_space_model->GetItem(test_case.dst.item_id));
// Verify that the holding space item has been updated in place.
ASSERT_EQ(src_item->file().file_path, test_case.dst.path);
ASSERT_EQ(src_item->file().file_system_url, test_case.dst.file_system_url);
ASSERT_EQ(src_item->file().file_system_type,
test_case.dst.file_system_type);
final_persisted_holding_space_items.Append(item->Serialize());
}
EXPECT_EQ(GetProfile()->GetPrefs()->GetList(
HoldingSpacePersistenceDelegate::kPersistencePath),
final_persisted_holding_space_items);
}
// Verifies that the holding space model is restored from persistence. Note that
// when restoring from persistence, existence of backing files is verified and
// any stale holding space items are removed.
TEST_P(HoldingSpaceKeyedServiceWithExperimentalFeatureTest,
RestorePersistentStorage) {
// Verify expected histograms.
base::HistogramTester histogram_tester;
EXPECT_THAT(
histogram_tester.GetTotalCountsForPrefix(kTotalCountV2HistogramPrefix),
IsEmpty());
// Create file system mount point.
std::unique_ptr<ScopedTestMountPoint> downloads_mount =
ScopedTestMountPoint::CreateAndMountDownloads(GetProfile());
ASSERT_TRUE(downloads_mount->IsValid());
HoldingSpaceKeyedService* const primary_holding_space_service =
HoldingSpaceKeyedServiceFactory::GetInstance()->GetService(GetProfile());
// Verify `expected_histograms` after "waiting" for metrics debounce.
task_environment()->FastForwardBy(base::Seconds(30));
auto expected_histograms = GetExpectedTotalCountV2HistogramSamples(
primary_holding_space_service->model_for_testing());
for (const auto& [name, expected_buckets] : expected_histograms) {
EXPECT_THAT(histogram_tester.GetAllSamples(name),
BucketsAreArray(expected_buckets));
}
HoldingSpaceModel::ItemList restored_holding_space_items;
base::Value::List persisted_holding_space_items_after_restoration;
// Create a secondary profile w/ a pre-populated pref store.
TestingProfile* const secondary_profile = CreateSecondaryProfile(
base::BindLambdaForTesting([&](TestingPrefStore* pref_store) {
base::Value::List persisted_holding_space_items_before_restoration;
// Persist some holding space items of each type.
for (const auto type : holding_space_util::GetAllItemTypes()) {
const base::FilePath file = downloads_mount->CreateArbitraryFile();
const GURL file_system_url = GetFileSystemUrl(GetProfile(), file);
const HoldingSpaceFile::FileSystemType file_system_type =
holding_space_util::ResolveFileSystemType(GetProfile(),
file_system_url);
auto fresh_holding_space_item =
HoldingSpaceItem::CreateFileBackedItem(
type,
HoldingSpaceFile(file, file_system_type, file_system_url),
base::BindOnce(&holding_space_util::ResolveImage,
primary_holding_space_service
->thumbnail_loader_for_testing()));
persisted_holding_space_items_before_restoration.Append(
fresh_holding_space_item->Serialize());
if (ShouldRestoreFromPersistence(type)) {
// We expect the `fresh_holding_space_item` to still be in
// persistence after model restoration since its backing file
// exists.
persisted_holding_space_items_after_restoration.Append(
fresh_holding_space_item->Serialize());
// We expect the `fresh_holding_space_item` to be restored from
// persistence since its backing file exists.
restored_holding_space_items.push_back(
std::move(fresh_holding_space_item));
}
base::FilePath file_path = downloads_mount->GetRootPath().AppendASCII(
base::UnguessableToken::Create().ToString());
auto stale_holding_space_item =
HoldingSpaceItem::CreateFileBackedItem(
type,
HoldingSpaceFile(file_path,
HoldingSpaceFile::FileSystemType::kTest,
GURL("filesystem:fake_file_system_url")),
base::BindOnce(&CreateTestHoldingSpaceImage));
// NOTE: While the `stale_holding_space_item` is persisted here, we do
// *not* expect it to be restored or to be persisted after model
// restoration since its backing file does *not* exist.
persisted_holding_space_items_before_restoration.Append(
stale_holding_space_item->Serialize());
}
pref_store->SetValueSilently(
HoldingSpacePersistenceDelegate::kPersistencePath,
base::Value(
std::move(persisted_holding_space_items_before_restoration)),
PersistentPrefStore::DEFAULT_PREF_WRITE_FLAGS);
}));
ActivateSecondaryProfile();
HoldingSpaceModelAttachedWaiter(secondary_profile).Wait();
HoldingSpaceKeyedService* const secondary_holding_space_service =
HoldingSpaceKeyedServiceFactory::GetInstance()->GetService(
secondary_profile);
HoldingSpaceModel* const secondary_holding_space_model =
HoldingSpaceController::Get()->model();
ASSERT_EQ(secondary_holding_space_model,
secondary_holding_space_service->model_for_testing());
ItemsInitializedWaiter(secondary_holding_space_model).Wait();
ASSERT_EQ(secondary_holding_space_model->items().size(),
restored_holding_space_items.size());
// Verify in-memory holding space items.
for (size_t i = 0; i < secondary_holding_space_model->items().size(); ++i) {
const auto& item = secondary_holding_space_model->items()[i];
const auto& restored_item = restored_holding_space_items[i];
EXPECT_EQ(*item, *restored_item) << "Expected equality of values at index "
<< i << ":" << "\n\tActual: " << item->id()
<< "\n\rRestored: " << restored_item->id();
}
// Verify persisted holding space items.
EXPECT_EQ(secondary_profile->GetPrefs()->GetList(
HoldingSpacePersistenceDelegate::kPersistencePath),
persisted_holding_space_items_after_restoration);
// Verify expected histograms after "waiting" for metrics debounce.
// NOTE: Histograms are profile-agnostic and cumulative so we need to merge
// `expected_histograms` from the primary profile with those of the secondary.
task_environment()->FastForwardBy(base::Seconds(30));
expected_histograms = MergeHistogramSamples(
expected_histograms,
GetExpectedTotalCountV2HistogramSamples(secondary_holding_space_model));
for (const auto& [name, expected_buckets] : expected_histograms) {
EXPECT_THAT(histogram_tester.GetAllSamples(name),
BucketsAreArray(expected_buckets));
}
}
// Verifies that items from volumes that are not immediately mounted during
// startup get restored into the holding space.
TEST_P(HoldingSpaceKeyedServiceWithExperimentalFeatureTest,
RestorePersistentStorageForDelayedVolumeMount) {
// Create file system mount point.
std::unique_ptr<ScopedTestMountPoint> downloads_mount =
ScopedTestMountPoint::CreateAndMountDownloads(GetProfile());
ASSERT_TRUE(downloads_mount->IsValid());
auto delayed_mount = std::make_unique<ScopedTestMountPoint>(
"drivefs-delayed_mount", storage::kFileSystemTypeDriveFs,
file_manager::VOLUME_TYPE_GOOGLE_DRIVE);
base::FilePath delayed_mount_file_name = base::FilePath("delayed file");
HoldingSpaceKeyedService* const primary_holding_space_service =
HoldingSpaceKeyedServiceFactory::GetInstance()->GetService(GetProfile());
std::vector<std::string> initialized_items_before_delayed_mount;
HoldingSpaceModel::ItemList restored_holding_space_items;
base::Value::List persisted_holding_space_items_after_restoration;
base::Value::List persisted_holding_space_items_after_delayed_mount;
// Create a secondary profile w/ a pre-populated pref store.
TestingProfile* const secondary_profile = CreateSecondaryProfile(
base::BindLambdaForTesting([&](TestingPrefStore* pref_store) {
base::Value::List persisted_holding_space_items_before_restoration;
// Persist some holding space items of each type.
for (const auto type : holding_space_util::GetAllItemTypes()) {
const base::FilePath delayed_mount_file =
delayed_mount->GetRootPath().Append(delayed_mount_file_name);
auto delayed_holding_space_item =
HoldingSpaceItem::CreateFileBackedItem(
type,
HoldingSpaceFile(delayed_mount_file,
HoldingSpaceFile::FileSystemType::kTest,
GURL("filesystem:fake")),
base::BindOnce(&CreateTestHoldingSpaceImage));
persisted_holding_space_items_before_restoration.Append(
delayed_holding_space_item->Serialize());
const bool should_restore = ShouldRestoreFromPersistence(type);
// If an item should be restored, it should be restored after delayed
// volume mount, and remain in persistent storage.
if (should_restore) {
persisted_holding_space_items_after_restoration.Append(
delayed_holding_space_item->Serialize());
persisted_holding_space_items_after_delayed_mount.Append(
delayed_holding_space_item->Serialize());
restored_holding_space_items.push_back(
std::move(delayed_holding_space_item));
}
const base::FilePath non_existent_path =
delayed_mount->GetRootPath().Append("non-existent");
auto non_existant_delayed_holding_space_item =
HoldingSpaceItem::CreateFileBackedItem(
type,
HoldingSpaceFile(non_existent_path,
HoldingSpaceFile::FileSystemType::kTest,
GURL("filesystem:fake")),
base::BindOnce(&CreateTestHoldingSpaceImage));
// The item should be removed from the model and persistent storage
// after delayed volume mount (when it can be confirmed the backing
// file does not exist) - the item should remain in persistent storage
// until the associated volume is mounted.
persisted_holding_space_items_before_restoration.Append(
non_existant_delayed_holding_space_item->Serialize());
if (should_restore) {
persisted_holding_space_items_after_restoration.Append(
non_existant_delayed_holding_space_item->Serialize());
}
const base::FilePath file = downloads_mount->CreateArbitraryFile();
const GURL file_system_url = GetFileSystemUrl(GetProfile(), file);
const HoldingSpaceFile::FileSystemType file_system_type =
holding_space_util::ResolveFileSystemType(GetProfile(),
file_system_url);
auto fresh_holding_space_item =
HoldingSpaceItem::CreateFileBackedItem(
type,
HoldingSpaceFile(file, file_system_type, file_system_url),
base::BindOnce(&holding_space_util::ResolveImage,
primary_holding_space_service
->thumbnail_loader_for_testing()));
persisted_holding_space_items_before_restoration.Append(
fresh_holding_space_item->Serialize());
// The item should be immediately added to the model, and remain in
// the persistent storage if it should be restored.
if (should_restore) {
initialized_items_before_delayed_mount.push_back(
fresh_holding_space_item->id());
persisted_holding_space_items_after_restoration.Append(
fresh_holding_space_item->Serialize());
persisted_holding_space_items_after_delayed_mount.Append(
fresh_holding_space_item->Serialize());
restored_holding_space_items.push_back(
std::move(fresh_holding_space_item));
}
}
pref_store->SetValueSilently(
HoldingSpacePersistenceDelegate::kPersistencePath,
base::Value(
std::move(persisted_holding_space_items_before_restoration)),
PersistentPrefStore::DEFAULT_PREF_WRITE_FLAGS);
}));
ActivateSecondaryProfile();
HoldingSpaceModelAttachedWaiter(secondary_profile).Wait();
HoldingSpaceKeyedService* const secondary_holding_space_service =
HoldingSpaceKeyedServiceFactory::GetInstance()->GetService(
secondary_profile);
HoldingSpaceModel* const secondary_holding_space_model =
HoldingSpaceController::Get()->model();
EXPECT_EQ(secondary_holding_space_model,
secondary_holding_space_service->model_for_testing());
ItemsInitializedWaiter(secondary_holding_space_model)
.Wait(
/*filter=*/base::BindLambdaForTesting(
[&downloads_mount](const HoldingSpaceItem* item) -> bool {
return downloads_mount->GetRootPath().IsParent(
item->file().file_path);
}));
std::vector<std::string> initialized_items;
for (const auto& item : secondary_holding_space_model->items()) {
if (item->IsInitialized()) {
initialized_items.push_back(item->id());
}
}
EXPECT_EQ(initialized_items_before_delayed_mount, initialized_items);
// Verify persisted holding space items.
EXPECT_EQ(secondary_profile->GetPrefs()->GetList(
HoldingSpacePersistenceDelegate::kPersistencePath),
persisted_holding_space_items_after_restoration);
delayed_mount->CreateFile(delayed_mount_file_name, "fake");
delayed_mount->Mount(secondary_profile);
ItemsInitializedWaiter(secondary_holding_space_model).Wait();
EXPECT_EQ(secondary_holding_space_model->items().size(),
restored_holding_space_items.size());
// Verify in-memory holding space items.
for (size_t i = 0; i < secondary_holding_space_model->items().size(); ++i) {
const auto& item = secondary_holding_space_model->items()[i];
const auto& restored_item = restored_holding_space_items[i];
SCOPED_TRACE(testing::Message() << "Item at index " << i);
EXPECT_TRUE(item->IsInitialized());
EXPECT_EQ(item->id(), restored_item->id());
EXPECT_EQ(item->type(), restored_item->type());
EXPECT_EQ(item->GetText(), restored_item->GetText());
EXPECT_EQ(item->file().file_path, restored_item->file().file_path);
// NOTE: `restored_item` was created with a fake file system URL (as it
// could not be properly resolved at the time of item creation).
EXPECT_EQ(
item->file().file_system_url,
GetFileSystemUrl(secondary_profile, restored_item->file().file_path));
}
// Verify persisted holding space items.
EXPECT_EQ(secondary_profile->GetPrefs()->GetList(
HoldingSpacePersistenceDelegate::kPersistencePath),
persisted_holding_space_items_after_delayed_mount);
}
// Verifies that items from volumes that are not immediately mounted during
// startup get restored into the holding space - same as
// RestorePersistentStorageForDelayedVolumeMount, but the volume gets mounted
// while item restoration is in progress.
TEST_P(HoldingSpaceKeyedServiceWithExperimentalFeatureTest,
RestorePersistentStorageForDelayedVolumeMountDuringRestoration) {
// Create file system mount point.
std::unique_ptr<ScopedTestMountPoint> downloads_mount =
ScopedTestMountPoint::CreateAndMountDownloads(GetProfile());
ASSERT_TRUE(downloads_mount->IsValid());
auto delayed_mount = std::make_unique<ScopedTestMountPoint>(
"drivefs-delayed_mount", storage::kFileSystemTypeDriveFs,
file_manager::VOLUME_TYPE_GOOGLE_DRIVE);
base::FilePath delayed_mount_file_name = base::FilePath("delayed file");
HoldingSpaceKeyedService* const primary_holding_space_service =
HoldingSpaceKeyedServiceFactory::GetInstance()->GetService(GetProfile());
HoldingSpaceModel::ItemList restored_holding_space_items;
base::Value::List persisted_holding_space_items_after_delayed_mount;
// Create a secondary profile w/ a pre-populated pref store.
TestingProfile* const secondary_profile = CreateSecondaryProfile(
base::BindLambdaForTesting([&](TestingPrefStore* pref_store) {
base::Value::List persisted_holding_space_items_before_restoration;
// Persist some holding space items of each type.
for (const auto type : holding_space_util::GetAllItemTypes()) {
const base::FilePath delayed_mount_file =
delayed_mount->GetRootPath().Append(delayed_mount_file_name);
auto delayed_holding_space_item =
HoldingSpaceItem::CreateFileBackedItem(
type,
HoldingSpaceFile(delayed_mount_file,
HoldingSpaceFile::FileSystemType::kTest,
GURL("filesystem:fake")),
base::BindOnce(&CreateTestHoldingSpaceImage));
persisted_holding_space_items_before_restoration.Append(
delayed_holding_space_item->Serialize());
const bool should_restore = ShouldRestoreFromPersistence(type);
// The item is restored after delayed volume mount, and remain
// in persistent storage if it should be restored.
if (should_restore) {
persisted_holding_space_items_after_delayed_mount.Append(
delayed_holding_space_item->Serialize());
restored_holding_space_items.push_back(
std::move(delayed_holding_space_item));
}
base::FilePath non_existent_path =
delayed_mount->GetRootPath().Append("non-existent");
auto non_existant_delayed_holding_space_item =
HoldingSpaceItem::CreateFileBackedItem(
type,
HoldingSpaceFile(non_existent_path,
HoldingSpaceFile::FileSystemType::kTest,
GURL("filesystem:fake")),
base::BindOnce(&CreateTestHoldingSpaceImage));
// The item should be removed from the model and persistent storage
// after delayed volume mount (when it can be confirmed the backing
// file does not exist) - the item should remain in persistent storage
// until the associated volume is mounted.
persisted_holding_space_items_before_restoration.Append(
non_existant_delayed_holding_space_item->Serialize());
const base::FilePath file = downloads_mount->CreateArbitraryFile();
const GURL file_system_url = GetFileSystemUrl(GetProfile(), file);
const HoldingSpaceFile::FileSystemType file_system_type =
holding_space_util::ResolveFileSystemType(GetProfile(),
file_system_url);
auto fresh_holding_space_item =
HoldingSpaceItem::CreateFileBackedItem(
type,
HoldingSpaceFile(file, file_system_type, file_system_url),
base::BindOnce(&holding_space_util::ResolveImage,
primary_holding_space_service
->thumbnail_loader_for_testing()));
persisted_holding_space_items_before_restoration.Append(
fresh_holding_space_item->Serialize());
// The item should be immediately added to the model, and remain in
// the persistent storage if it should be restored.
if (should_restore) {
persisted_holding_space_items_after_delayed_mount.Append(
fresh_holding_space_item->Serialize());
restored_holding_space_items.push_back(
std::move(fresh_holding_space_item));
}
}
pref_store->SetValueSilently(
HoldingSpacePersistenceDelegate::kPersistencePath,
base::Value(
std::move(persisted_holding_space_items_before_restoration)),
PersistentPrefStore::DEFAULT_PREF_WRITE_FLAGS);
}));
ActivateSecondaryProfile();
delayed_mount->CreateFile(delayed_mount_file_name, "fake");
delayed_mount->Mount(secondary_profile);
HoldingSpaceModelAttachedWaiter(secondary_profile).Wait();
HoldingSpaceKeyedService* const secondary_holding_space_service =
HoldingSpaceKeyedServiceFactory::GetInstance()->GetService(
secondary_profile);
HoldingSpaceModel* const secondary_holding_space_model =
HoldingSpaceController::Get()->model();
EXPECT_EQ(secondary_holding_space_model,
secondary_holding_space_service->model_for_testing());
ItemsInitializedWaiter(secondary_holding_space_model).Wait();
ASSERT_EQ(secondary_holding_space_model->items().size(),
restored_holding_space_items.size());
// Verify in-memory holding space items.
for (size_t i = 0; i < secondary_holding_space_model->items().size(); ++i) {
const auto& item = secondary_holding_space_model->items()[i];
const auto& restored_item = restored_holding_space_items[i];
SCOPED_TRACE(testing::Message() << "Item at index " << i);
EXPECT_TRUE(item->IsInitialized());
EXPECT_EQ(item->id(), restored_item->id());
EXPECT_EQ(item->type(), restored_item->type());
EXPECT_EQ(item->GetText(), restored_item->GetText());
EXPECT_EQ(item->file().file_path, restored_item->file().file_path);
// NOTE: `restored_item` was created with a fake file system URL (as it
// could not be properly resolved at the time of item creation).
EXPECT_EQ(
item->file().file_system_url,
GetFileSystemUrl(secondary_profile, restored_item->file().file_path));
}
// Verify persisted holding space items.
EXPECT_EQ(secondary_profile->GetPrefs()->GetList(
HoldingSpacePersistenceDelegate::kPersistencePath),
persisted_holding_space_items_after_delayed_mount);
}
// Verifies that mounting volumes that contain no holding space items does not
// interfere with holding space restoration.
TEST_P(HoldingSpaceKeyedServiceWithExperimentalFeatureTest,
RestorePersistentStorageWithUnrelatedVolumeMounts) {
// Create file system mount point.
std::unique_ptr<ScopedTestMountPoint> downloads_mount =
ScopedTestMountPoint::CreateAndMountDownloads(GetProfile());
ASSERT_TRUE(downloads_mount->IsValid());
auto delayed_mount_1 = std::make_unique<ScopedTestMountPoint>(
"drivefs-delayed_mount_1", storage::kFileSystemTypeDriveFs,
file_manager::VOLUME_TYPE_GOOGLE_DRIVE);
auto delayed_mount_2 = std::make_unique<ScopedTestMountPoint>(
"drivefs-delayed_mount_2", storage::kFileSystemTypeDriveFs,
file_manager::VOLUME_TYPE_GOOGLE_DRIVE);
HoldingSpaceKeyedService* const primary_holding_space_service =
HoldingSpaceKeyedServiceFactory::GetInstance()->GetService(GetProfile());
std::vector<std::string> initialized_items_before_delayed_mount;
HoldingSpaceModel::ItemList restored_holding_space_items;
base::Value::List persisted_holding_space_items_after_restoration;
base::Value::List persisted_holding_space_items_after_delayed_mount;
// Create a secondary profile w/ a pre-populated pref store.
TestingProfile* const secondary_profile = CreateSecondaryProfile(
base::BindLambdaForTesting([&](TestingPrefStore* pref_store) {
base::Value::List persisted_holding_space_items_before_restoration;
// Persist some holding space items of each type.
for (const auto type : holding_space_util::GetAllItemTypes()) {
const base::FilePath file = downloads_mount->CreateArbitraryFile();
const GURL file_system_url = GetFileSystemUrl(GetProfile(), file);
const HoldingSpaceFile::FileSystemType file_system_type =
holding_space_util::ResolveFileSystemType(GetProfile(),
file_system_url);
auto fresh_holding_space_item =
HoldingSpaceItem::CreateFileBackedItem(
type,
HoldingSpaceFile(file, file_system_type, file_system_url),
base::BindOnce(&holding_space_util::ResolveImage,
primary_holding_space_service
->thumbnail_loader_for_testing()));
persisted_holding_space_items_before_restoration.Append(
fresh_holding_space_item->Serialize());
// The item should be immediately added to the model, and remain in
// the persistent storage if it should be restored.
if (ShouldRestoreFromPersistence(type)) {
initialized_items_before_delayed_mount.push_back(
fresh_holding_space_item->id());
persisted_holding_space_items_after_restoration.Append(
fresh_holding_space_item->Serialize());
persisted_holding_space_items_after_delayed_mount.Append(
fresh_holding_space_item->Serialize());
restored_holding_space_items.push_back(
std::move(fresh_holding_space_item));
}
}
pref_store->SetValueSilently(
HoldingSpacePersistenceDelegate::kPersistencePath,
base::Value(
std::move(persisted_holding_space_items_before_restoration)),
PersistentPrefStore::DEFAULT_PREF_WRITE_FLAGS);
}));
ActivateSecondaryProfile();
delayed_mount_1->Mount(secondary_profile);
HoldingSpaceModelAttachedWaiter(secondary_profile).Wait();
HoldingSpaceKeyedService* const secondary_holding_space_service =
HoldingSpaceKeyedServiceFactory::GetInstance()->GetService(
secondary_profile);
HoldingSpaceModel* const secondary_holding_space_model =
HoldingSpaceController::Get()->model();
EXPECT_EQ(secondary_holding_space_model,
secondary_holding_space_service->model_for_testing());
ItemsInitializedWaiter(secondary_holding_space_model).Wait();
std::vector<std::string> initialized_items;
for (const auto& item : secondary_holding_space_model->items()) {
if (item->IsInitialized()) {
initialized_items.push_back(item->id());
}
}
EXPECT_EQ(initialized_items_before_delayed_mount, initialized_items);
// Verify persisted holding space items.
EXPECT_EQ(secondary_profile->GetPrefs()->GetList(
HoldingSpacePersistenceDelegate::kPersistencePath),
persisted_holding_space_items_after_restoration);
delayed_mount_2->Mount(secondary_profile);
ItemsInitializedWaiter(secondary_holding_space_model).Wait();
EXPECT_EQ(secondary_holding_space_model->items().size(),
restored_holding_space_items.size());
// Verify in-memory holding space items.
for (size_t i = 0; i < secondary_holding_space_model->items().size(); ++i) {
const auto& item = secondary_holding_space_model->items()[i];
const auto& restored_item = restored_holding_space_items[i];
SCOPED_TRACE(testing::Message() << "Item at index " << i);
EXPECT_TRUE(item->IsInitialized());
EXPECT_EQ(item->id(), restored_item->id());
EXPECT_EQ(item->type(), restored_item->type());
EXPECT_EQ(item->GetText(), restored_item->GetText());
EXPECT_EQ(item->file().file_path, restored_item->file().file_path);
// NOTE: `restored_item` was created with a fake file system URL (as it
// could not be properly resolved at the time of item creation).
EXPECT_EQ(
item->file().file_system_url,
GetFileSystemUrl(secondary_profile, restored_item->file().file_path));
}
// Verify persisted holding space items.
EXPECT_EQ(secondary_profile->GetPrefs()->GetList(
HoldingSpacePersistenceDelegate::kPersistencePath),
persisted_holding_space_items_after_delayed_mount);
}
// Tests that items from an unmounted volume get removed from the holding space.
TEST_P(HoldingSpaceKeyedServiceWithExperimentalFeatureTest,
RemoveItemsFromUnmountedVolumes) {
auto test_mount_1 = std::make_unique<ScopedTestMountPoint>(
"test_mount_1", storage::kFileSystemTypeLocal,
file_manager::VOLUME_TYPE_TESTING);
test_mount_1->Mount(GetProfile());
HoldingSpaceModelAttachedWaiter(GetProfile()).Wait();
auto test_mount_2 = std::make_unique<ScopedTestMountPoint>(
"test_mount_2", storage::kFileSystemTypeLocal,
file_manager::VOLUME_TYPE_TESTING);
test_mount_2->Mount(GetProfile());
HoldingSpaceModelAttachedWaiter(GetProfile()).Wait();
HoldingSpaceKeyedService* const holding_space_service =
HoldingSpaceKeyedServiceFactory::GetInstance()->GetService(GetProfile());
const HoldingSpaceModel* holding_space_model =
holding_space_service->model_for_testing();
const base::FilePath file_path_1 = test_mount_1->CreateArbitraryFile();
holding_space_service->AddItemOfType(HoldingSpaceItem::Type::kScreenshot,
file_path_1);
const base::FilePath file_path_2 = test_mount_2->CreateArbitraryFile();
holding_space_service->AddItemOfType(HoldingSpaceItem::Type::kDownload,
file_path_2);
const base::FilePath file_path_3 = test_mount_1->CreateArbitraryFile();
holding_space_service->AddItemOfType(HoldingSpaceItem::Type::kDownload,
file_path_3);
EXPECT_EQ(3u, GetProfile()
->GetPrefs()
->GetList(HoldingSpacePersistenceDelegate::kPersistencePath)
.size());
EXPECT_EQ(3u, holding_space_model->items().size());
test_mount_1.reset();
base::RunLoop().RunUntilIdle();
EXPECT_EQ(1u, GetProfile()
->GetPrefs()
->GetList(HoldingSpacePersistenceDelegate::kPersistencePath)
.size());
ASSERT_EQ(1u, holding_space_model->items().size());
EXPECT_EQ(file_path_2, holding_space_model->items()[0]->file().file_path);
}
// Verifies that files restored from persistence are not older than
// `kMaxFileAge`.
// TODO(crbug.com/1427927): Flaky on Linux.
#if BUILDFLAG(IS_LINUX)
#define MAYBE_RemoveOlderFilesFromPersistence \
DISABLED_RemoveOlderFilesFromPersistence
#else
#define MAYBE_RemoveOlderFilesFromPersistence RemoveOlderFilesFromPersistence
#endif
TEST_P(HoldingSpaceKeyedServiceWithExperimentalFeatureTest,
MAYBE_RemoveOlderFilesFromPersistence) {
// Create file system mount point.
std::unique_ptr<ScopedTestMountPoint> downloads_mount =
ScopedTestMountPoint::CreateAndMountDownloads(GetProfile());
ASSERT_TRUE(downloads_mount->IsValid());
HoldingSpaceKeyedService* const primary_holding_space_service =
HoldingSpaceKeyedServiceFactory::GetInstance()->GetService(GetProfile());
HoldingSpaceModel::ItemList restored_holding_space_items;
base::Value::List persisted_holding_space_items_after_restoration;
base::Time last_creation_time = base::Time::Now();
// Create a secondary profile w/ a pre-populated pref store.
TestingProfile* const secondary_profile = CreateSecondaryProfile(
base::BindLambdaForTesting([&](TestingPrefStore* pref_store) {
base::Value::List persisted_holding_space_items_before_restoration;
// Persist some holding space items of each type.
for (const auto type : holding_space_util::GetAllItemTypes()) {
const base::FilePath file = downloads_mount->CreateArbitraryFile();
const GURL file_system_url = GetFileSystemUrl(GetProfile(), file);
const HoldingSpaceFile::FileSystemType file_system_type =
holding_space_util::ResolveFileSystemType(GetProfile(),
file_system_url);
auto fresh_holding_space_item =
HoldingSpaceItem::CreateFileBackedItem(
type,
HoldingSpaceFile(file, file_system_type, file_system_url),
base::BindOnce(&holding_space_util::ResolveImage,
primary_holding_space_service
->thumbnail_loader_for_testing()));
persisted_holding_space_items_before_restoration.Append(
fresh_holding_space_item->Serialize());
bool should_restore = ShouldRestoreFromPersistence(type);
if (should_restore) {
// We expect all holding space items of other types to be removed
// from persistence during restoration due to being older than
// `kMaxFileAge`.
should_restore = type == HoldingSpaceItem::Type::kPinnedFile;
}
if (should_restore) {
persisted_holding_space_items_after_restoration.Append(
fresh_holding_space_item->Serialize());
restored_holding_space_items.push_back(
std::move(fresh_holding_space_item));
}
base::File::Info file_info;
ASSERT_TRUE(base::GetFileInfo(file, &file_info));
last_creation_time = file_info.creation_time;
}
pref_store->SetValueSilently(
HoldingSpacePersistenceDelegate::kPersistencePath,
base::Value(
std::move(persisted_holding_space_items_before_restoration)),
PersistentPrefStore::DEFAULT_PREF_WRITE_FLAGS);
}));
// Fast-forward to a point where the created files are too old to be restored
// from persistence.
task_environment()->FastForwardBy(last_creation_time - base::Time::Now() +
kMaxFileAge);
ActivateSecondaryProfile();
HoldingSpaceModelAttachedWaiter(secondary_profile).Wait();
HoldingSpaceKeyedService* const secondary_holding_space_service =
HoldingSpaceKeyedServiceFactory::GetInstance()->GetService(
secondary_profile);
HoldingSpaceModel* const secondary_holding_space_model =
HoldingSpaceController::Get()->model();
ASSERT_EQ(secondary_holding_space_model,
secondary_holding_space_service->model_for_testing());
ItemsInitializedWaiter(secondary_holding_space_model).Wait();
ASSERT_EQ(secondary_holding_space_model->items().size(),
restored_holding_space_items.size());
// Verify in-memory holding space items.
for (size_t i = 0; i < secondary_holding_space_model->items().size(); ++i) {
const auto& item = secondary_holding_space_model->items()[i];
const auto& restored_item = restored_holding_space_items[i];
EXPECT_EQ(*item, *restored_item) << "Expected equality of values at index "
<< i << ":" << "\n\tActual: " << item->id()
<< "\n\rRestored: " << restored_item->id();
}
// Verify persisted holding space items.
EXPECT_EQ(secondary_profile->GetPrefs()->GetList(
HoldingSpacePersistenceDelegate::kPersistencePath),
persisted_holding_space_items_after_restoration);
}
TEST_P(HoldingSpaceKeyedServiceWithExperimentalFeatureTest,
AddArcDownloadItem) {
// Wait for the holding space model to attach.
TestingProfile* profile = GetProfile();
HoldingSpaceModelAttachedWaiter(profile).Wait();
// Verify the holding space `model` is empty.
HoldingSpaceModel* const model = HoldingSpaceController::Get()->model();
ASSERT_EQ(0u, model->items().size());
// Create a test downloads mount point.
std::unique_ptr<ScopedTestMountPoint> downloads_mount =
ScopedTestMountPoint::CreateAndMountDownloads(profile);
ASSERT_TRUE(downloads_mount->IsValid());
// Create a fake download file on the local file system.
const base::FilePath file_path = downloads_mount->CreateFile(
/*relative_path=*/base::FilePath("Download.png"),
/*content=*/"foo");
// Simulate an `OnMediaStoreUriAdded()` event from ARC.
auto* arc_file_system_bridge =
arc::ArcFileSystemBridge::GetForBrowserContext(profile);
ASSERT_TRUE(arc_file_system_bridge);
arc_file_system_bridge->OnMediaStoreUriAdded(
GURL("uri"), arc::mojom::MediaStoreMetadata::NewDownload(
arc::mojom::MediaStoreDownloadMetadata::New(
/*display_name=*/file_path.BaseName().value(),
/*owner_package_name=*/"com.bar.foo",
/*relative_path=*/base::FilePath("Download/"))));
// Verify that an item of type `kArcDownload` was added to holding space.
ASSERT_EQ(1u, model->items().size());
const HoldingSpaceItem* arc_download_item = model->items()[0].get();
EXPECT_EQ(arc_download_item->type(), HoldingSpaceItem::Type::kArcDownload);
EXPECT_EQ(arc_download_item->file().file_path,
file_manager::util::GetDownloadsFolderForProfile(profile).Append(
base::FilePath("Download.png")));
}
TEST_P(HoldingSpaceKeyedServiceWithExperimentalFeatureTest,
AddInProgressDownloadItem) {
// Wait for the holding space model to attach.
TestingProfile* profile = GetProfile();
HoldingSpaceModelAttachedWaiter(profile).Wait();
// Verify the holding space model is empty.
HoldingSpaceModel* const model = HoldingSpaceController::Get()->model();
ASSERT_TRUE(model);
EXPECT_EQ(model->items().size(), 0u);
// Create a downloads mount point.
std::unique_ptr<ScopedTestMountPoint> downloads_mount =
ScopedTestMountPoint::CreateAndMountDownloads(profile);
ASSERT_TRUE(downloads_mount->IsValid());
// Cache current state, file paths, received bytes, and total bytes.
auto current_state = download::DownloadItem::IN_PROGRESS;
base::FilePath current_path;
base::FilePath current_target_path;
int64_t current_received_bytes = 0;
int64_t current_total_bytes = 100;
bool current_is_dangerous = false;
download::DownloadDangerType current_danger_type =
download::DownloadDangerType::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS;
// Create a fake download item and cache a function to update it.
std::unique_ptr<content::FakeDownloadItem> fake_download_item =
CreateFakeDownloadItem(profile, current_state, current_path,
current_target_path, current_received_bytes,
current_total_bytes);
auto UpdateFakeDownloadItem = [&]() {
fake_download_item->SetDummyFilePath(current_path);
fake_download_item->SetReceivedBytes(current_received_bytes);
fake_download_item->SetState(current_state);
fake_download_item->SetTargetFilePath(current_target_path);
fake_download_item->SetTotalBytes(current_total_bytes);
fake_download_item->SetIsDangerous(current_is_dangerous);
fake_download_item->SetDangerType(current_danger_type);
fake_download_item->NotifyDownloadUpdated();
};
// Verify that no holding space item has been created since the download does
// not yet have file path set.
EXPECT_EQ(model->items().size(), 0u);
// Update the file paths for the download.
current_path = downloads_mount->CreateFile(base::FilePath("foo.crdownload"));
current_target_path = downloads_mount->CreateFile(base::FilePath("foo.png"));
UpdateFakeDownloadItem();
// Verify that a holding space item has been created.
ASSERT_EQ(model->items().size(), 1u);
EXPECT_EQ(model->items()[0]->type(), HoldingSpaceItem::Type::kDownload);
EXPECT_EQ(model->items()[0]->file().file_path, current_path);
EXPECT_EQ(model->items()[0]->progress().GetValue(), 0.f);
constexpr gfx::Size kImageSize(20, 20);
constexpr bool kDarkBackground = false;
{
// Once the `ThumbnailLoader` has finished processing the initial request,
// the image should represent the file type of the *target* file for the
// underlying download, not its current backing file.
base::RunLoop run_loop;
auto image_skia_changed_subscription =
model->items()[0]->image().AddImageSkiaChangedCallback(
base::BindLambdaForTesting([&]() {
gfx::ImageSkia actual_image =
model->items()[0]->image().GetImageSkia(kImageSize,
kDarkBackground);
gfx::ImageSkia expected_image = chromeos::GetIconForPath(
current_target_path, kDarkBackground);
EXPECT_TRUE(BitmapsAreEqual(actual_image, expected_image));
run_loop.Quit();
}));
// But initially the holding space image should be an empty bitmap. Note
// that requesting the image is what spawns the initial request.
gfx::ImageSkia actual_image =
model->items()[0]->image().GetImageSkia(kImageSize, kDarkBackground);
gfx::ImageSkia expected_image = image_util::CreateEmptyImage(kImageSize);
EXPECT_TRUE(BitmapsAreEqual(actual_image, expected_image));
// Wait for the `ThumbnailLoader` to finish processing the initial request.
run_loop.Run();
}
// Update the total bytes for the download.
current_total_bytes = -1;
UpdateFakeDownloadItem();
// Verify that the holding space item has indeterminate progress.
ASSERT_EQ(model->items().size(), 1u);
EXPECT_EQ(model->items()[0]->type(), HoldingSpaceItem::Type::kDownload);
EXPECT_EQ(model->items()[0]->file().file_path, current_path);
EXPECT_TRUE(model->items()[0]->progress().IsIndeterminate());
// Update the received bytes and total bytes for the download.
current_received_bytes = 50;
current_total_bytes = 100;
UpdateFakeDownloadItem();
// Verify that the holding space item has expected progress.
ASSERT_EQ(model->items().size(), 1u);
EXPECT_EQ(model->items()[0]->type(), HoldingSpaceItem::Type::kDownload);
EXPECT_EQ(model->items()[0]->file().file_path, current_path);
EXPECT_EQ(model->items()[0]->progress().GetValue(), 0.5f);
// Remove the holding space item from the model.
model->RemoveIf(
base::BindRepeating([](const HoldingSpaceItem* item) { return true; }));
EXPECT_EQ(model->items().size(), 0u);
// Complete the download.
current_state = download::DownloadItem::COMPLETE;
current_path = current_target_path;
current_received_bytes = current_total_bytes;
UpdateFakeDownloadItem();
// Verify that no holding space item has been created since the holding space
// associated with the completed download was previously removed.
EXPECT_EQ(model->items().size(), 0u);
// Create a new download.
current_state = download::DownloadItem::IN_PROGRESS;
current_path = base::FilePath();
current_target_path = base::FilePath();
current_received_bytes = 0;
fake_download_item = CreateFakeDownloadItem(
profile, current_state, current_path, current_target_path,
current_received_bytes, current_total_bytes);
// Verify that no holding space item has been created since the download does
// not yet have file path set.
EXPECT_EQ(model->items().size(), 0u);
// Update the file paths and received bytes for the download.
current_path = downloads_mount->CreateFile(base::FilePath("bar.crdownload"));
current_target_path = downloads_mount->CreateFile(base::FilePath("bar.zip"));
current_received_bytes = 50;
UpdateFakeDownloadItem();
// Verify that a holding space item has been created.
ASSERT_EQ(model->items().size(), 1u);
EXPECT_EQ(model->items()[0]->type(), HoldingSpaceItem::Type::kDownload);
EXPECT_EQ(model->items()[0]->file().file_path, current_path);
EXPECT_EQ(model->items()[0]->progress().GetValue(), 0.5f);
// Not dangerous in-progress items should only have Cancel and Pause
// in-progress commands.
EXPECT_EQ(model->items()[0]->in_progress_commands().size(), 2u);
EXPECT_TRUE(holding_space_util::SupportsInProgressCommand(
model->items()[0].get(), HoldingSpaceCommandId::kCancelItem));
EXPECT_TRUE(holding_space_util::SupportsInProgressCommand(
model->items()[0].get(), HoldingSpaceCommandId::kPauseItem));
{
// Once the `ThumbnailLoader` has finished processing the request, the image
// should represent the file type of the *target* file for the underlying
// download, not its current backing file.
base::RunLoop run_loop;
auto image_skia_changed_subscription =
model->items()[0]->image().AddImageSkiaChangedCallback(
base::BindLambdaForTesting([&]() {
gfx::ImageSkia actual_image =
model->items()[0]->image().GetImageSkia(kImageSize,
kDarkBackground);
gfx::ImageSkia expected_image = chromeos::GetIconForPath(
current_target_path, kDarkBackground);
EXPECT_TRUE(BitmapsAreEqual(actual_image, expected_image));
run_loop.Quit();
}));
// But initially the holding space image should be an empty bitmap. Note
// that requesting the image is what spawns the initial request.
gfx::ImageSkia actual_image =
model->items()[0]->image().GetImageSkia(kImageSize, kDarkBackground);
gfx::ImageSkia expected_image = image_util::CreateEmptyImage(kImageSize);
EXPECT_TRUE(BitmapsAreEqual(actual_image, expected_image));
// Wait for the `ThumbnailLoader` to finish processing the initial request.
run_loop.Run();
}
// Mark the download as dangerous and maybe malicious.
current_is_dangerous = true;
current_danger_type = download::DownloadDangerType::
DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT;
UpdateFakeDownloadItem();
// Dangerous in-progress items should only have Cancel in-progress commands.
EXPECT_EQ(model->items()[0]->in_progress_commands().size(), 1u);
EXPECT_TRUE(holding_space_util::SupportsInProgressCommand(
model->items()[0].get(), HoldingSpaceCommandId::kCancelItem));
{
// Because the download has been marked as dangerous and maybe malicious,
// the image should represent that the underlying download is in error.
base::RunLoop run_loop;
auto image_skia_changed_subscription =
model->items()[0]->image().AddImageSkiaChangedCallback(
base::BindLambdaForTesting([&]() {
gfx::ImageSkia actual_image =
model->items()[0]->image().GetImageSkia(kImageSize,
kDarkBackground);
gfx::ImageSkia expected_image =
gfx::ImageSkiaOperations::CreateSuperimposedImage(
image_util::CreateEmptyImage(kImageSize),
gfx::CreateVectorIcon(
vector_icons::kErrorOutlineIcon,
kHoldingSpaceIconSize,
cros_styles::ResolveColor(
cros_styles::ColorName::kIconColorAlert,
kDarkBackground)));
EXPECT_TRUE(BitmapsAreEqual(actual_image, expected_image));
run_loop.Quit();
}));
// Force a thumbnail request and wait for the `ThumbnailLoader` to finish
// processing the request.
model->items()[0]->image().GetImageSkia(kImageSize, kDarkBackground);
run_loop.Run();
}
// Mark the download as *not* being malicious.
current_danger_type =
download::DownloadDangerType::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE;
UpdateFakeDownloadItem();
// Dangerous in-progress items should only have Cancel in-progress commands.
EXPECT_EQ(model->items()[0]->in_progress_commands().size(), 1u);
EXPECT_TRUE(holding_space_util::SupportsInProgressCommand(
model->items()[0].get(), HoldingSpaceCommandId::kCancelItem));
{
// Because the download has been marked as dangerous but *not* malicious,
// the image should represent that the underlying download is in warning.
base::RunLoop run_loop;
auto image_skia_changed_subscription =
model->items()[0]->image().AddImageSkiaChangedCallback(
base::BindLambdaForTesting([&]() {
gfx::ImageSkia actual_image =
model->items()[0]->image().GetImageSkia(kImageSize,
kDarkBackground);
gfx::ImageSkia expected_image =
gfx::ImageSkiaOperations::CreateSuperimposedImage(
image_util::CreateEmptyImage(kImageSize),
gfx::CreateVectorIcon(
vector_icons::kErrorOutlineIcon,
kHoldingSpaceIconSize,
cros_styles::ResolveColor(
cros_styles::ColorName::kIconColorWarning,
kDarkBackground)));
EXPECT_TRUE(BitmapsAreEqual(actual_image, expected_image));
run_loop.Quit();
}));
// Force a thumbnail request and wait for the `ThumbnailLoader` to finish
// processing the request.
model->items()[0]->image().GetImageSkia(kImageSize, kDarkBackground);
run_loop.Run();
}
// Complete the download.
current_state = download::DownloadItem::COMPLETE;
current_path = current_target_path;
current_received_bytes = current_total_bytes;
UpdateFakeDownloadItem();
// Verify that the holding space item has been updated.
ASSERT_EQ(model->items().size(), 1u);
EXPECT_EQ(model->items()[0]->type(), HoldingSpaceItem::Type::kDownload);
EXPECT_EQ(model->items()[0]->file().file_path, current_path);
EXPECT_TRUE(model->items()[0]->progress().IsComplete());
// The image should be representative of the file type of the *target* file
// for the underlying download which by this point is actually the same file
// path as the backing file path.
gfx::ImageSkia actual_image =
model->items()[0]->image().GetImageSkia(kImageSize, kDarkBackground);
gfx::ImageSkia expected_image =
chromeos::GetIconForPath(current_target_path, kDarkBackground);
EXPECT_TRUE(BitmapsAreEqual(actual_image, expected_image));
}
TEST_P(HoldingSpaceKeyedServiceWithExperimentalFeatureTest, RemoveAll) {
// Wait for the holding space model to attach.
TestingProfile* profile = GetProfile();
HoldingSpaceModelAttachedWaiter(profile).Wait();
// Verify the holding space `model` is empty.
HoldingSpaceModel* const model = HoldingSpaceController::Get()->model();
ASSERT_EQ(0u, model->items().size());
// Create a test mount point.
std::unique_ptr<ScopedTestMountPoint> mount_point =
ScopedTestMountPoint::CreateAndMountDownloads(profile);
ASSERT_TRUE(mount_point->IsValid());
auto* service =
HoldingSpaceKeyedServiceFactory::GetInstance()->GetService(profile);
// Create files on the file system.
const base::FilePath download_path = mount_point->CreateFile(
/*relative_path=*/base::FilePath("bar"), /*content=*/"bar");
const base::FilePath pinned_file_path = mount_point->CreateFile(
/*relative_path=*/base::FilePath("foo"), /*content=*/"foo");
// Add them both to holding space, one in pinned files the other in downloads.
service->AddItemOfType(HoldingSpaceItem::Type::kDownload, download_path);
service->AddPinnedFiles(
{file_manager::util::GetFileManagerFileSystemContext(profile)
->CrackURLInFirstPartyContext(
holding_space_util::ResolveFileSystemUrl(profile,
pinned_file_path))});
ASSERT_EQ(2u, model->items().size());
service->RemoveAll();
EXPECT_EQ(0u, model->items().size());
}
TEST_P(HoldingSpaceKeyedServiceWithExperimentalFeatureTest,
CreateInterruptedDownloadItem) {
// Wait for the holding space model to attach.
TestingProfile* profile = GetProfile();
HoldingSpaceModelAttachedWaiter(profile).Wait();
// Verify the holding space model is empty.
HoldingSpaceModel* const model = HoldingSpaceController::Get()->model();
ASSERT_TRUE(model);
EXPECT_EQ(model->items().size(), 0u);
// Create a downloads mount point.
std::unique_ptr<ScopedTestMountPoint> downloads_mount =
ScopedTestMountPoint::CreateAndMountDownloads(profile);
ASSERT_TRUE(downloads_mount->IsValid());
// Cache current state, file paths, received bytes, and total bytes.
auto current_state = download::DownloadItem::INTERRUPTED;
base::FilePath current_path;
base::FilePath current_target_path;
int64_t current_received_bytes = 0;
int64_t current_total_bytes = 100;
bool current_is_dangerous = false;
// Create a fake download item and cache a function to update it.
std::unique_ptr<content::FakeDownloadItem> fake_download_item =
CreateFakeDownloadItem(profile, current_state, current_path,
current_target_path, current_received_bytes,
current_total_bytes);
auto UpdateFakeDownloadItem = [&]() {
fake_download_item->SetDummyFilePath(current_path);
fake_download_item->SetReceivedBytes(current_received_bytes);
fake_download_item->SetState(current_state);
fake_download_item->SetTargetFilePath(current_target_path);
fake_download_item->SetTotalBytes(current_total_bytes);
fake_download_item->SetIsDangerous(current_is_dangerous);
fake_download_item->NotifyDownloadUpdated();
};
// Verify that no holding space item has been created since the download does
// not yet have file path set.
EXPECT_EQ(model->items().size(), 0u);
// Update the file paths for the download.
current_path = downloads_mount->CreateFile(base::FilePath("foo.crdownload"));
current_target_path = downloads_mount->CreateFile(base::FilePath("foo.png"));
UpdateFakeDownloadItem();
// Verify that no holding space item has been created since the download is
// not in progress yet.
EXPECT_EQ(model->items().size(), 0u);
current_state = download::DownloadItem::IN_PROGRESS;
UpdateFakeDownloadItem();
// Verify that a holding space item is created.
ASSERT_EQ(model->items().size(), 1u);
EXPECT_EQ(model->items()[0]->type(), HoldingSpaceItem::Type::kDownload);
EXPECT_EQ(model->items()[0]->file().file_path, current_path);
EXPECT_EQ(model->items()[0]->progress().GetValue(), 0.f);
// Complete the download.
current_state = download::DownloadItem::COMPLETE;
current_path = current_target_path;
current_received_bytes = current_total_bytes;
UpdateFakeDownloadItem();
// Verify that completing a download results in exactly one holding space item
// existing for it, regardless of whether the in-progress downloads feature is
// enabled.
ASSERT_EQ(model->items().size(), 1u);
EXPECT_EQ(model->items()[0]->type(), HoldingSpaceItem::Type::kDownload);
EXPECT_EQ(model->items()[0]->file().file_path, current_path);
EXPECT_TRUE(model->items()[0]->progress().IsComplete());
}
TEST_P(HoldingSpaceKeyedServiceWithExperimentalFeatureTest,
InterruptAndResumeDownload) {
// Wait for the holding space model to attach.
TestingProfile* profile = GetProfile();
HoldingSpaceModelAttachedWaiter(profile).Wait();
// Verify the holding space model is empty.
HoldingSpaceModel* const model = HoldingSpaceController::Get()->model();
ASSERT_TRUE(model);
EXPECT_EQ(model->items().size(), 0u);
// Create a downloads mount point.
std::unique_ptr<ScopedTestMountPoint> downloads_mount =
ScopedTestMountPoint::CreateAndMountDownloads(profile);
ASSERT_TRUE(downloads_mount->IsValid());
// Cache current state, file paths, received bytes, and total bytes.
auto current_state = download::DownloadItem::IN_PROGRESS;
base::FilePath current_path;
base::FilePath current_target_path;
int64_t current_received_bytes = 0;
int64_t current_total_bytes = 100;
bool current_is_dangerous = false;
// Create a fake download item and cache a function to update it.
std::unique_ptr<content::FakeDownloadItem> fake_download_item =
CreateFakeDownloadItem(profile, current_state, current_path,
current_target_path, current_received_bytes,
current_total_bytes);
auto UpdateFakeDownloadItem = [&]() {
fake_download_item->SetDummyFilePath(current_path);
fake_download_item->SetReceivedBytes(current_received_bytes);
fake_download_item->SetState(current_state);
fake_download_item->SetTargetFilePath(current_target_path);
fake_download_item->SetTotalBytes(current_total_bytes);
fake_download_item->SetIsDangerous(current_is_dangerous);
fake_download_item->NotifyDownloadUpdated();
};
// Verify that no holding space item has been created since the download does
// not yet have file path set.
EXPECT_EQ(model->items().size(), 0u);
// Update the file paths for the download.
current_path = downloads_mount->CreateFile(base::FilePath("foo.crdownload"));
current_target_path = downloads_mount->CreateFile(base::FilePath("foo.png"));
UpdateFakeDownloadItem();
// Verify that a holding space item is created.
ASSERT_EQ(model->items().size(), 1u);
EXPECT_EQ(model->items()[0]->type(), HoldingSpaceItem::Type::kDownload);
EXPECT_EQ(model->items()[0]->file().file_path, current_path);
EXPECT_EQ(model->items()[0]->progress().GetValue(), 0.f);
// Make some progress and interrupt the download.
current_received_bytes = 50;
current_state = download::DownloadItem::INTERRUPTED;
UpdateFakeDownloadItem();
// Verify that interrupting an in-progress download destroys its holding
// space item (if the in-progress downloads feature is enabled).
ASSERT_EQ(model->items().size(), 0u);
// Resume the download.
current_state = download::DownloadItem::IN_PROGRESS;
UpdateFakeDownloadItem();
// Verify that resuming an interrupted download creates a new holding space
// item.
ASSERT_EQ(model->items().size(), 1u);
EXPECT_EQ(model->items()[0]->type(), HoldingSpaceItem::Type::kDownload);
EXPECT_EQ(model->items()[0]->file().file_path, current_path);
EXPECT_EQ(model->items()[0]->progress().GetValue(), 0.5f);
// Complete the download.
current_state = download::DownloadItem::COMPLETE;
current_path = current_target_path;
current_received_bytes = current_total_bytes;
UpdateFakeDownloadItem();
// Verify that completing a download results in exactly one holding space item
// existing for it, regardless of whether the in-progress downloads feature is
// enabled.
ASSERT_EQ(model->items().size(), 1u);
EXPECT_EQ(model->items()[0]->type(), HoldingSpaceItem::Type::kDownload);
EXPECT_EQ(model->items()[0]->file().file_path, current_path);
EXPECT_TRUE(model->items()[0]->progress().IsComplete());
}
// Base class for tests which verify adding and removing items from holding
// space works as intended, parameterized by holding space item type.
class HoldingSpaceKeyedServiceAddAndRemoveItemTest
: public HoldingSpaceKeyedServiceTest,
public ::testing::WithParamInterface<HoldingSpaceItem::Type> {
public:
// Returns the holding space service associated with the specified `profile`.
HoldingSpaceKeyedService* GetService(Profile* profile) {
return HoldingSpaceKeyedServiceFactory::GetInstance()->GetService(profile);
}
// Returns the type of holding space item under test.
HoldingSpaceItem::Type GetType() const { return GetParam(); }
// Adds an item of `type` to the holding space belonging to `profile`, backed
// by the file at the specified absolute `file_path`. Returns the `id` of the
// added holding space item.
const std::string& AddItem(Profile* profile,
HoldingSpaceItem::Type type,
const base::FilePath& file_path) {
auto* const holding_space_service = GetService(profile);
EXPECT_TRUE(holding_space_service);
const auto* holding_space_model =
holding_space_service->model_for_testing();
EXPECT_TRUE(holding_space_model);
switch (type) {
case HoldingSpaceItem::Type::kArcDownload:
case HoldingSpaceItem::Type::kDownload:
EXPECT_EQ(
holding_space_model->ContainsItem(type, file_path),
holding_space_service->AddItemOfType(type, file_path).empty());
break;
case HoldingSpaceItem::Type::kDiagnosticsLog:
case HoldingSpaceItem::Type::kNearbyShare:
holding_space_service->AddItemOfType(type, file_path);
break;
case HoldingSpaceItem::Type::kDriveSuggestion:
case HoldingSpaceItem::Type::kLocalSuggestion:
holding_space_service->SetSuggestions(
/*suggestions=*/{{type, file_path}});
break;
case HoldingSpaceItem::Type::kPinnedFile:
holding_space_service->AddPinnedFiles(
{file_manager::util::GetFileManagerFileSystemContext(profile)
->CrackURLInFirstPartyContext(
holding_space_util::ResolveFileSystemUrl(profile,
file_path))});
break;
case HoldingSpaceItem::Type::kPhoneHubCameraRoll:
EXPECT_EQ(
holding_space_model->ContainsItem(type, file_path),
holding_space_service
->AddItemOfType(HoldingSpaceItem::Type::kPhoneHubCameraRoll,
file_path, HoldingSpaceProgress())
.empty());
break;
case HoldingSpaceItem::Type::kPhotoshopWeb:
case HoldingSpaceItem::Type::kPrintedPdf:
case HoldingSpaceItem::Type::kScan:
case HoldingSpaceItem::Type::kScreenRecording:
case HoldingSpaceItem::Type::kScreenRecordingGif:
case HoldingSpaceItem::Type::kScreenshot:
holding_space_service->AddItemOfType(type, file_path);
break;
}
const auto* item = holding_space_model->GetItem(type, file_path);
EXPECT_TRUE(item);
return item->id();
}
};
INSTANTIATE_TEST_SUITE_P(
All,
HoldingSpaceKeyedServiceAddAndRemoveItemTest,
testing::ValuesIn(holding_space_util::GetAllItemTypes()));
TEST_P(HoldingSpaceKeyedServiceAddAndRemoveItemTest, AddAndRemoveItem) {
// Wait for the holding space model to attach.
TestingProfile* profile = GetProfile();
HoldingSpaceModelAttachedWaiter(profile).Wait();
// Verify the holding space `model` is empty.
HoldingSpaceModel* const model = HoldingSpaceController::Get()->model();
ASSERT_EQ(0u, model->items().size());
// Verify expected histograms.
base::HistogramTester histogram_tester;
EXPECT_THAT(
histogram_tester.GetTotalCountsForPrefix(kTotalCountV2HistogramPrefix),
IsEmpty());
// Create a test mount point.
std::unique_ptr<ScopedTestMountPoint> mount_point =
ScopedTestMountPoint::CreateAndMountDownloads(profile);
ASSERT_TRUE(mount_point->IsValid());
// Create a file on the file system.
const base::FilePath file_path = mount_point->CreateFile(
/*relative_path=*/base::FilePath("foo"), /*content=*/"foo");
// Add a holding space item of the type under test.
const std::string id = AddItem(profile, GetType(), file_path);
// Verify a holding space item has been added to the model.
ASSERT_EQ(model->items().size(), 1u);
HoldingSpaceKeyedService* const service = GetService(profile);
ASSERT_TRUE(service);
EXPECT_TRUE(service->ContainsItem(id));
// Verify holding space `item` metadata.
HoldingSpaceItem* const item = model->items()[0].get();
EXPECT_EQ(item->id(), id);
EXPECT_EQ(item->type(), GetType());
EXPECT_EQ(item->GetText(), file_path.BaseName().LossyDisplayName());
EXPECT_EQ(item->file().file_path, file_path);
EXPECT_EQ(item->file().file_system_url,
holding_space_util::ResolveFileSystemUrl(profile, file_path));
// Verify holding space `item` image.
EXPECT_TRUE(gfx::BitmapsAreEqual(
*holding_space_util::ResolveImage(
GetService(profile)->thumbnail_loader_for_testing(), GetType(),
file_path)
->GetImageSkia()
.bitmap(),
*item->image().GetImageSkia().bitmap()));
// Verify `expected_histograms` after "waiting" for metrics debounce.
task_environment()->FastForwardBy(base::Seconds(30));
auto expected_histograms = GetExpectedTotalCountV2HistogramSamples(model);
for (const auto& [name, expected_buckets] : expected_histograms) {
EXPECT_THAT(histogram_tester.GetAllSamples(name),
BucketsAreArray(expected_buckets));
}
// Attempt to add a holding space item of the same type and `file_path`.
const std::string& id2 = AddItem(profile, GetType(), file_path);
ASSERT_EQ(model->items().size(), 1u);
// Attempts to add already represented items should be ignored.
EXPECT_EQ(model->items()[0].get(), item);
EXPECT_EQ(id, id2);
EXPECT_TRUE(service->ContainsItem(id));
EXPECT_TRUE(service->ContainsItem(id2));
// Remove the holding space item.
service->RemoveItem(id);
EXPECT_TRUE(model->items().empty());
EXPECT_FALSE(service->ContainsItem(id));
EXPECT_FALSE(service->ContainsItem(id2));
// Verify `expected_histograms` after "waiting" for metrics debounce.
// NOTE: Histograms are cumulative so we need to merge `expected_histograms`
// from the previous state with those of the current.
task_environment()->FastForwardBy(base::Seconds(30));
expected_histograms = MergeHistogramSamples(
expected_histograms, GetExpectedTotalCountV2HistogramSamples(model));
for (const auto& [name, expected_buckets] : expected_histograms) {
EXPECT_THAT(histogram_tester.GetAllSamples(name),
BucketsAreArray(expected_buckets));
}
}
TEST_P(HoldingSpaceKeyedServiceAddAndRemoveItemTest, AddAndRemoveItemOfType) {
// Wait for the holding space model to attach.
TestingProfile* profile = GetProfile();
HoldingSpaceModelAttachedWaiter(profile).Wait();
// Verify the holding space `model` is empty.
HoldingSpaceModel* const model = HoldingSpaceController::Get()->model();
ASSERT_EQ(0u, model->items().size());
// Create a test mount point.
std::unique_ptr<ScopedTestMountPoint> mount_point =
ScopedTestMountPoint::CreateAndMountDownloads(profile);
ASSERT_TRUE(mount_point->IsValid());
// Create a file on the file system.
const base::FilePath file_path = mount_point->CreateFile(
/*relative_path=*/base::FilePath("foo"), /*content=*/"foo");
// Add a holding space item of the type under test.
const auto& id = GetService(profile)->AddItemOfType(GetType(), file_path);
// Verify a holding space item has been added to the model.
ASSERT_EQ(model->items().size(), 1u);
// Verify holding space `item` metadata.
HoldingSpaceItem* const item = model->items()[0].get();
EXPECT_EQ(item->id(), id);
EXPECT_EQ(item->type(), GetType());
EXPECT_EQ(item->GetText(), file_path.BaseName().LossyDisplayName());
EXPECT_EQ(item->file().file_path, file_path);
EXPECT_EQ(item->file().file_system_url,
holding_space_util::ResolveFileSystemUrl(profile, file_path));
// Verify holding space `item` image.
EXPECT_TRUE(gfx::BitmapsAreEqual(
*holding_space_util::ResolveImage(
GetService(profile)->thumbnail_loader_for_testing(), GetType(),
file_path)
->GetImageSkia()
.bitmap(),
*item->image().GetImageSkia().bitmap()));
// Attempt to add a holding space item of the same type and `file_path`.
EXPECT_TRUE(GetService(profile)->AddItemOfType(GetType(), file_path).empty());
// Attempts to add already represented items should be ignored.
ASSERT_EQ(model->items().size(), 1u);
EXPECT_EQ(model->items()[0].get(), item);
// Remove the holding space item.
GetService(profile)->RemoveItem(id);
EXPECT_TRUE(model->items().empty());
}
using HoldingSpaceKeyedServiceNearbySharingTest = HoldingSpaceKeyedServiceTest;
TEST_F(HoldingSpaceKeyedServiceNearbySharingTest, AddNearbyShareItem) {
// Create a test downloads mount point.
std::unique_ptr<ScopedTestMountPoint> downloads_mount =
ScopedTestMountPoint::CreateAndMountDownloads(GetProfile());
ASSERT_TRUE(downloads_mount->IsValid());
// Wait for the holding space model.
HoldingSpaceModelAttachedWaiter(GetProfile()).Wait();
// Verify that the holding space model gets set even if the holding space
// keyed service is not explicitly created.
HoldingSpaceModel* const initial_model =
HoldingSpaceController::Get()->model();
EXPECT_TRUE(initial_model);
HoldingSpaceKeyedService* const holding_space_service =
HoldingSpaceKeyedServiceFactory::GetInstance()->GetService(GetProfile());
const base::FilePath item_1_virtual_path("File 1.png");
// Create a fake nearby shared file on the local file system - later parts of
// the test will try to resolve the file's file system URL, which fails if the
// file does not exist.
const base::FilePath item_1_full_path =
downloads_mount->CreateFile(item_1_virtual_path, "red");
ASSERT_FALSE(item_1_full_path.empty());
holding_space_service->AddItemOfType(HoldingSpaceItem::Type::kNearbyShare,
item_1_full_path);
const base::FilePath item_2_virtual_path = base::FilePath("Alt/File 2.png");
// Create a fake nearby shared file on the local file system - later parts of
// the test will try to resolve the file's file system URL, which fails if the
// file does not exist.
const base::FilePath item_2_full_path =
downloads_mount->CreateFile(item_2_virtual_path, "blue");
ASSERT_FALSE(item_2_full_path.empty());
holding_space_service->AddItemOfType(HoldingSpaceItem::Type::kNearbyShare,
item_2_full_path);
EXPECT_EQ(initial_model, HoldingSpaceController::Get()->model());
EXPECT_EQ(HoldingSpaceController::Get()->model(),
holding_space_service->model_for_testing());
HoldingSpaceModel* const model = HoldingSpaceController::Get()->model();
ASSERT_EQ(2u, model->items().size());
const HoldingSpaceItem* item_1 = model->items()[0].get();
EXPECT_EQ(item_1_full_path, item_1->file().file_path);
EXPECT_TRUE(gfx::BitmapsAreEqual(
*holding_space_util::ResolveImage(
holding_space_service->thumbnail_loader_for_testing(),
HoldingSpaceItem::Type::kNearbyShare, item_1_full_path)
->GetImageSkia()
.bitmap(),
*item_1->image().GetImageSkia().bitmap()));
// Verify the item file system URL resolves to the correct file in the file
// manager's context.
EXPECT_EQ(item_1_virtual_path,
GetVirtualPathFromUrl(item_1->file().file_system_url,
downloads_mount->name()));
EXPECT_EQ(u"File 1.png", item_1->GetText());
const HoldingSpaceItem* item_2 = model->items()[1].get();
EXPECT_EQ(item_2_full_path, item_2->file().file_path);
EXPECT_TRUE(gfx::BitmapsAreEqual(
*holding_space_util::ResolveImage(
holding_space_service->thumbnail_loader_for_testing(),
HoldingSpaceItem::Type::kNearbyShare, item_2_full_path)
->GetImageSkia()
.bitmap(),
*item_2->image().GetImageSkia().bitmap()));
// Verify the item file system URL resolves to the correct file in the file
// manager's context.
EXPECT_EQ(item_2_virtual_path,
GetVirtualPathFromUrl(item_2->file().file_system_url,
downloads_mount->name()));
EXPECT_EQ(u"File 2.png", item_2->GetText());
}
// Test parameters for tests of Photoshop Web integration. Used to wrap `GURL`
// so that value-param representation can be overridden. See `PrintToString()`
// below as well as https://crbug.com/410764102 for additional details.
struct HoldingSpaceKeyedServicePhotoshopWebIntegrationTestParams {
GURL file_picker_binding_context;
};
// NOTE: Used by `::testing::PrintToStringParamName()`. Per
// https://crbug.com/410764102, return value must be non-empty.
std::string PrintToString(
const HoldingSpaceKeyedServicePhotoshopWebIntegrationTestParams& params) {
const GURL& context = params.file_picker_binding_context;
return context.is_empty() ? "(empty)" : context.spec();
}
// Base class for tests of Photoshop Web integration. Parameterized by the
// binding context to use for the file picker during testing.
class HoldingSpaceKeyedServicePhotoshopWebIntegrationTest
: public HoldingSpaceKeyedServiceTest,
public ::testing::WithParamInterface<
HoldingSpaceKeyedServicePhotoshopWebIntegrationTestParams> {
public:
// The binding context to use for the file picker given test parameterization.
const GURL& GetFilePickerBindingContext() const {
return GetParam().file_picker_binding_context;
}
};
INSTANTIATE_TEST_SUITE_P(
All,
HoldingSpaceKeyedServicePhotoshopWebIntegrationTest,
/*file_picker_binding_context=*/
::testing::Values(
HoldingSpaceKeyedServicePhotoshopWebIntegrationTestParams{
.file_picker_binding_context = GURL()},
HoldingSpaceKeyedServicePhotoshopWebIntegrationTestParams{
.file_picker_binding_context = GURL("https://google.com/")},
HoldingSpaceKeyedServicePhotoshopWebIntegrationTestParams{
.file_picker_binding_context =
GURL("https://photoshop.adobe.com/")}));
// Verifies that a Photoshop Web item will be added to the user's Holding Space
// under expected circumstances.
TEST_P(HoldingSpaceKeyedServicePhotoshopWebIntegrationTest,
AddPhotoshopWebItem) {
// Cache `profile`.
TestingProfile* const profile = GetProfile();
// Wait for `model` attachment and verify initial state.
HoldingSpaceModelAttachedWaiter(profile).Wait();
const HoldingSpaceModel* const model = HoldingSpaceController::Get()->model();
ASSERT_TRUE(model);
ASSERT_EQ(model->items().size(), 0u);
// Create `mount_point`.
std::unique_ptr<ScopedTestMountPoint> mount_point =
ScopedTestMountPoint::CreateAndMountDownloads(profile);
ASSERT_TRUE(mount_point->IsValid());
// Create file and resolve metadata.
const base::FilePath file_path =
mount_point->CreateFile(/*relative_path=*/base::FilePath("foo"));
const GURL file_system_url =
holding_space_util::ResolveFileSystemUrl(profile, file_path);
const HoldingSpaceFile::FileSystemType file_system_type =
holding_space_util::ResolveFileSystemType(profile, file_system_url);
// Verify initial histogram state.
base::HistogramTester histogram_tester;
EXPECT_THAT(histogram_tester.GetTotalCountsForPrefix(
"HoldingSpace.FileCreatedFromShowSaveFilePicker."),
IsEmpty());
// Propagate file creation event from a file picker with the binding context
// specified by test parameterization.
FileSystemAccessPermissionContextFactory::GetForProfile(profile)
->OnFileCreatedFromShowSaveFilePicker(
GetFilePickerBindingContext(),
file_manager::util::GetFileManagerFileSystemContext(profile)
->CrackURLInFirstPartyContext(file_system_url));
// A Photoshop Web item should be added to the user's Holding Space iff the
// binding context for the file picker is from the domain associated with
// Photoshop Web.
const bool is_file_picker_binding_context_photoshop_web =
GetFilePickerBindingContext().DomainIs("photoshop.adobe.com");
// Verify model state.
EXPECT_THAT(
model->items(),
Conditional(
is_file_picker_binding_context_photoshop_web,
ElementsAre(Pointee(AllOf(
Property(&HoldingSpaceItem::type,
HoldingSpaceItem::Type::kPhotoshopWeb),
Property(&HoldingSpaceItem::file,
AllOf(Field(&HoldingSpaceFile::file_path, file_path),
Field(&HoldingSpaceFile::file_system_type,
file_system_type),
Field(&HoldingSpaceFile::file_system_url,
file_system_url)))))),
IsEmpty()));
// Verify histogram state.
EXPECT_THAT(histogram_tester.GetAllSamples(
"HoldingSpace.FileCreatedFromShowSaveFilePicker.Extension"),
BucketsAre(Bucket(
holding_space_metrics::FilePathToExtension(file_path), 1u)));
EXPECT_THAT(
histogram_tester.GetAllSamples(
"HoldingSpace.FileCreatedFromShowSaveFilePicker."
"FilePickerBindingContext"),
Conditional(
is_file_picker_binding_context_photoshop_web,
BucketsAre(Bucket(FilePickerBindingContext::kPhotoshopWeb, 1u)),
BucketsAre(Bucket(FilePickerBindingContext::kUnknown, 1u))));
}
// Base class for tests of print-to-PDF integration. Parameterized by whether
// tests should use an incognito browser.
class HoldingSpaceKeyedServicePrintToPdfIntegrationTest
: public HoldingSpaceKeyedServiceTest,
public testing::WithParamInterface<bool /* from_incognito_profile */> {
public:
// Starts a job to print an empty PDF to the specified `file_path`.
// NOTE: This method will not return until the print job completes.
void StartPrintToPdfAndWaitForSave(const std::u16string& job_title,
const base::FilePath& file_path) {
base::RunLoop run_loop;
pdf_printer_handler_->SetPdfSavedClosureForTesting(run_loop.QuitClosure());
pdf_printer_handler_->SetPrintToPdfPathForTesting(file_path);
pdf_printer_handler_->StartPrint(
job_title,
/*settings=*/base::Value::Dict(),
base::MakeRefCounted<base::RefCountedString>(std::string()),
/*callback=*/base::DoNothing());
run_loop.Run();
}
// Returns true if the test should use an incognito browser, false otherwise.
bool UseIncognitoBrowser() const { return GetParam(); }
private:
// HoldingSpaceKeyedServiceTest:
void SetUp() override {
HoldingSpaceKeyedServiceTest::SetUp();
// Create the PDF printer handler.
Browser* browser = GetBrowserForPdfPrinterHandler();
pdf_printer_handler_ = std::make_unique<::printing::PdfPrinterHandler>(
browser->profile(), browser->tab_strip_model()->GetActiveWebContents(),
/*sticky_settings=*/nullptr);
}
void TearDown() override {
incognito_browser_.reset();
HoldingSpaceKeyedServiceTest::TearDown();
}
Browser* GetBrowserForPdfPrinterHandler() {
if (!UseIncognitoBrowser()) {
return browser();
}
if (!incognito_browser_) {
incognito_browser_ =
CreateBrowserWithTestWindowForParams(Browser::CreateParams(
profile()->GetPrimaryOTRProfile(/*create_if_needed=*/true),
/*user_gesture=*/true));
}
return incognito_browser_.get();
}
std::unique_ptr<::printing::PdfPrinterHandler> pdf_printer_handler_;
std::unique_ptr<Browser> incognito_browser_;
};
INSTANTIATE_TEST_SUITE_P(All,
HoldingSpaceKeyedServicePrintToPdfIntegrationTest,
/*from_incognito_profile=*/::testing::Bool());
// Verifies that print-to-PDF adds an associated item to holding space.
TEST_P(HoldingSpaceKeyedServicePrintToPdfIntegrationTest, AddPrintedPdfItem) {
// Create a file system mount point.
std::unique_ptr<ScopedTestMountPoint> mount_point =
ScopedTestMountPoint::CreateAndMountDownloads(GetProfile());
ASSERT_TRUE(mount_point->IsValid());
// Cache a pointer to the holding space model.
const HoldingSpaceModel* model =
HoldingSpaceKeyedServiceFactory::GetInstance()
->GetService(GetProfile())
->model_for_testing();
// Verify that the holding space is initially empty.
EXPECT_EQ(model->items().size(), 0u);
// Start a job to print an empty PDF to `file_path`.
base::FilePath file_path = mount_point->GetRootPath().Append("foo.pdf");
StartPrintToPdfAndWaitForSave(u"job_title", file_path);
// Verify that holding space is populated with the expected item.
ASSERT_EQ(model->items().size(), 1u);
EXPECT_EQ(model->items()[0]->type(), HoldingSpaceItem::Type::kPrintedPdf);
EXPECT_EQ(model->items()[0]->file().file_path, file_path);
}
// Base class for tests of incognito profile integration.
class HoldingSpaceKeyedServiceIncognitoDownloadsTest
: public HoldingSpaceKeyedServiceTest {
public:
// HoldingSpaceKeyedServiceTest:
TestingProfile* CreateProfile(const std::string& profile_name) override {
TestingProfile* profile =
HoldingSpaceKeyedServiceTest::CreateProfile(profile_name);
// Construct an incognito profile from the primary profile.
TestingProfile::Builder incognito_profile_builder;
incognito_profile_builder.SetProfileName(profile->GetProfileUserName());
incognito_profile_ = incognito_profile_builder.BuildIncognito(profile);
EXPECT_TRUE(incognito_profile_);
EXPECT_TRUE(incognito_profile_->IsIncognitoProfile());
SetUpDownloadManager(incognito_profile_);
EXPECT_NE(incognito_profile_->GetDownloadManager(),
profile->GetDownloadManager());
return profile;
}
// Returns the incognito profile spawned from the test's main profile.
TestingProfile* incognito_profile() { return incognito_profile_; }
private:
raw_ptr<TestingProfile, DanglingUntriaged> incognito_profile_ = nullptr;
};
TEST_F(HoldingSpaceKeyedServiceIncognitoDownloadsTest, AddDownloadItem) {
TestingProfile* profile = GetProfile();
HoldingSpaceModelAttachedWaiter(profile).Wait();
// Create a test downloads mount point.
std::unique_ptr<ScopedTestMountPoint> downloads_mount =
ScopedTestMountPoint::CreateAndMountDownloads(profile);
ASSERT_TRUE(downloads_mount->IsValid());
// Cache current state, file path, received bytes, and total bytes.
auto current_state = download::DownloadItem::IN_PROGRESS;
base::FilePath current_path;
int64_t current_received_bytes = 0;
int64_t current_total_bytes = 100;
// Create a fake in-progress download item for the incognito profile and cache
// a function to update it.
std::unique_ptr<content::FakeDownloadItem> fake_download_item =
CreateFakeDownloadItem(incognito_profile(), current_state, current_path,
/*target_file_path=*/base::FilePath(),
current_received_bytes, current_total_bytes);
auto UpdateFakeDownloadItem = [&]() {
fake_download_item->SetDummyFilePath(current_path);
fake_download_item->SetReceivedBytes(current_received_bytes);
fake_download_item->SetState(current_state);
fake_download_item->SetTotalBytes(current_total_bytes);
fake_download_item->NotifyDownloadUpdated();
};
// Verify holding space is empty.
HoldingSpaceModel* const model = HoldingSpaceController::Get()->model();
ASSERT_EQ(0u, model->items().size());
// Update the file path for the download.
current_path = downloads_mount->CreateFile(base::FilePath("tmp/temp_path"));
UpdateFakeDownloadItem();
// Verify that a holding space item is created.
ASSERT_EQ(1u, model->items().size());
HoldingSpaceItem* download_item = model->items()[0].get();
EXPECT_EQ(download_item->type(), HoldingSpaceItem::Type::kDownload);
EXPECT_EQ(download_item->file().file_path, current_path);
EXPECT_EQ(download_item->progress().GetValue(), 0.f);
// Complete the download.
current_state = download::DownloadItem::COMPLETE;
current_path = downloads_mount->CreateFile(base::FilePath("tmp/final_path"));
current_received_bytes = current_total_bytes;
UpdateFakeDownloadItem();
// Verify that a completed holding space item exists.
ASSERT_EQ(1u, model->items().size());
download_item = model->items()[0].get();
EXPECT_EQ(download_item->type(), HoldingSpaceItem::Type::kDownload);
EXPECT_EQ(download_item->file().file_path, current_path);
EXPECT_TRUE(download_item->progress().IsComplete());
}
TEST_F(HoldingSpaceKeyedServiceIncognitoDownloadsTest,
AddInProgressDownloadItem) {
TestingProfile* profile = GetProfile();
HoldingSpaceModelAttachedWaiter(profile).Wait();
// Verify the holding space model is empty.
HoldingSpaceModel* const model = HoldingSpaceController::Get()->model();
ASSERT_TRUE(model);
EXPECT_EQ(model->items().size(), 0u);
// Create a test downloads mount point.
std::unique_ptr<ScopedTestMountPoint> downloads_mount =
ScopedTestMountPoint::CreateAndMountDownloads(profile);
ASSERT_TRUE(downloads_mount->IsValid());
// Cache current state, file paths, received bytes, and total bytes.
auto current_state = download::DownloadItem::IN_PROGRESS;
base::FilePath current_path;
base::FilePath current_target_path;
int64_t current_received_bytes = 0;
int64_t current_total_bytes = 100;
bool current_is_dangerous = false;
// Create a fake download item and cache a function to update it.
std::unique_ptr<content::FakeDownloadItem> fake_download_item =
CreateFakeDownloadItem(incognito_profile(), current_state, current_path,
current_target_path, current_received_bytes,
current_total_bytes);
auto UpdateFakeDownloadItem = [&]() {
fake_download_item->SetDummyFilePath(current_path);
fake_download_item->SetReceivedBytes(current_received_bytes);
fake_download_item->SetState(current_state);
fake_download_item->SetTargetFilePath(current_target_path);
fake_download_item->SetTotalBytes(current_total_bytes);
fake_download_item->SetIsDangerous(current_is_dangerous);
fake_download_item->NotifyDownloadUpdated();
};
// Verify that no holding space item has been created since the download does
// not yet have file path set.
EXPECT_EQ(model->items().size(), 0u);
// Update the file paths for the download.
current_path = downloads_mount->CreateFile(base::FilePath("foo.crdownload"));
current_target_path = downloads_mount->CreateFile(base::FilePath("foo.png"));
UpdateFakeDownloadItem();
// Verify that a holding space item is created.
ASSERT_EQ(1u, model->items().size());
HoldingSpaceItem* download_item = model->items()[0].get();
EXPECT_EQ(download_item->type(), HoldingSpaceItem::Type::kDownload);
EXPECT_EQ(download_item->file().file_path, current_path);
EXPECT_FALSE(download_item->progress().IsComplete());
// Verify that destroying a profile with an in-progress download destroys
// the holding space item.
profile->DestroyOffTheRecordProfile(incognito_profile());
ASSERT_EQ(0u, model->items().size());
}
class HoldingSpaceSuggestionsDelegateTest
: public HoldingSpaceKeyedServiceTest,
public testing::WithParamInterface<bool> {
public:
HoldingSpaceSuggestionsDelegateTest() {
scoped_feature_list_.InitWithFeatureState(
features::kHoldingSpaceSuggestions, GetParam());
}
void SetUp() override {
HoldingSpaceKeyedServiceTest::SetUp();
// Create mount points to host test files.
TestingProfile* profile = GetProfile();
drive_mount_point_ = std::make_unique<ScopedTestMountPoint>(
"drive_test_mount", storage::kFileSystemTypeDriveFs,
file_manager::VOLUME_TYPE_TESTING);
drive_mount_point_->Mount(profile);
local_mount_point_ = std::make_unique<ScopedTestMountPoint>(
"local_test_mount", storage::kFileSystemTypeLocal,
file_manager::VOLUME_TYPE_TESTING);
local_mount_point_->Mount(profile);
HoldingSpaceModelAttachedWaiter(profile).Wait();
}
void TearDown() override {
drive_mount_point_.reset();
local_mount_point_.reset();
HoldingSpaceKeyedServiceTest::TearDown();
}
MockFileSuggestKeyedService* GetFileSuggestKeyedService() {
return static_cast<MockFileSuggestKeyedService*>(
FileSuggestKeyedServiceFactory::GetInstance()->GetService(
GetProfile()));
}
ScopedTestMountPoint* drive_mount_point() { return drive_mount_point_.get(); }
ScopedTestMountPoint* local_mount_point() { return local_mount_point_.get(); }
private:
base::test::ScopedFeatureList scoped_feature_list_;
std::unique_ptr<ScopedTestMountPoint> drive_mount_point_;
std::unique_ptr<ScopedTestMountPoint> local_mount_point_;
};
INSTANTIATE_TEST_SUITE_P(All,
HoldingSpaceSuggestionsDelegateTest,
/*enable_suggestion_feature=*/testing::Bool());
// Verifies that suggestion refresh through the holding space client is WAI.
TEST_P(HoldingSpaceSuggestionsDelegateTest, SuggestionRefresh) {
using Type = HoldingSpaceItem::Type;
// Populate drive and local file suggestions.
const base::FilePath file_path_1 = drive_mount_point()->CreateArbitraryFile();
const base::FilePath file_path_2 = local_mount_point()->CreateArbitraryFile();
GetFileSuggestKeyedService()->SetSuggestionsForType(
FileSuggestionType::kDriveFile,
/*suggestions=*/std::vector<FileSuggestData>{
{FileSuggestionType::kDriveFile, file_path_1,
/*title=*/std::nullopt,
/*new_prediction_reason=*/std::nullopt,
/*modified_time=*/std::nullopt,
/*viewed_time=*/std::nullopt,
/*shared_time=*/std::nullopt,
/*new_score=*/std::nullopt,
/*drive_file_id=*/std::nullopt,
/*icon_url=*/std::nullopt}});
GetFileSuggestKeyedService()->SetSuggestionsForType(
FileSuggestionType::kLocalFile,
/*suggestions=*/std::vector<FileSuggestData>{
{FileSuggestionType::kLocalFile, file_path_2,
/*title=*/std::nullopt,
/*new_prediction_reason=*/std::nullopt,
/*modified_time=*/std::nullopt,
/*viewed_time=*/std::nullopt,
/*shared_time=*/std::nullopt,
/*new_score=*/std::nullopt,
/*drive_file_id=*/std::nullopt,
/*icon_url=*/std::nullopt}});
task_environment()->FastForwardBy(base::Seconds(1));
// Verify initial suggestions. Note that suggestions are reversed in the
// holding space model to account for the fact that items are presented in
// reverse-chronological order.
const bool suggestion_feature_enabled =
features::IsHoldingSpaceSuggestionsEnabled();
HoldingSpaceModel* model = HoldingSpaceController::Get()->model();
EXPECT_THAT(GetSuggestionsInModel(*model),
::testing::Conditional(
suggestion_feature_enabled,
::testing::ElementsAre(
std::make_pair(Type::kLocalSuggestion, file_path_2),
std::make_pair(Type::kDriveSuggestion, file_path_1)),
::testing::IsEmpty()));
// Create additional files to back refreshed suggestions.
const base::FilePath file_path_3 = drive_mount_point()->CreateArbitraryFile();
const base::FilePath file_path_4 = local_mount_point()->CreateArbitraryFile();
// Refresh suggestions through the holding space client. Verify that
// `FileSuggestKeyedService::GetSuggestFileData()` is called if and only if
// the suggestions feature is enabled.
EXPECT_CALL(*GetFileSuggestKeyedService(),
GetSuggestFileData(FileSuggestionType::kDriveFile, ::testing::_))
.Times(suggestion_feature_enabled ? 1u : 0u)
.WillOnce(base::test::RunOnceCallback<1u>(
std::make_optional(std::vector<FileSuggestData>{
{FileSuggestionType::kDriveFile, file_path_3,
/*title=*/std::nullopt,
/*new_prediction_reason=*/std::nullopt,
/*modified_time=*/std::nullopt,
/*viewed_time=*/std::nullopt,
/*shared_time=*/std::nullopt,
/*new_score=*/std::nullopt,
/*drive_file_id=*/std::nullopt,
/*icon_url=*/std::nullopt}})));
EXPECT_CALL(*GetFileSuggestKeyedService(),
GetSuggestFileData(FileSuggestionType::kLocalFile, ::testing::_))
.Times(suggestion_feature_enabled ? 1u : 0u)
.WillOnce(base::test::RunOnceCallback<1u>(
std::make_optional(std::vector<FileSuggestData>{
{FileSuggestionType::kLocalFile, file_path_4,
/*title=*/std::nullopt,
/*new_prediction_reason=*/std::nullopt,
/*modified_time=*/std::nullopt,
/*viewed_time=*/std::nullopt,
/*shared_time=*/std::nullopt,
/*new_score=*/std::nullopt,
/*drive_file_id=*/std::nullopt,
/*icon_url=*/std::nullopt}})));
HoldingSpaceController::Get()->client()->RefreshSuggestions();
// Verify that all suggestions have been updated in the model if and only if
// the suggestions feature is enabled.
EXPECT_THAT(GetSuggestionsInModel(*model),
::testing::Conditional(
suggestion_feature_enabled,
::testing::ElementsAre(
std::make_pair(Type::kLocalSuggestion, file_path_4),
std::make_pair(Type::kDriveSuggestion, file_path_3)),
::testing::IsEmpty()));
}
// Verifies that suggestion removal through the holding space client is WAI.
TEST_P(HoldingSpaceSuggestionsDelegateTest, SuggestionRemoval) {
using Type = HoldingSpaceItem::Type;
// Populate drive and local file suggestions.
const base::FilePath file_path_1 = drive_mount_point()->CreateArbitraryFile();
const base::FilePath file_path_2 = local_mount_point()->CreateArbitraryFile();
GetFileSuggestKeyedService()->SetSuggestionsForType(
FileSuggestionType::kDriveFile,
/*suggestions=*/std::vector<FileSuggestData>{
{FileSuggestionType::kDriveFile, file_path_1,
/*title=*/std::nullopt,
/*new_prediction_reason=*/std::nullopt,
/*modified_time=*/std::nullopt,
/*viewed_time=*/std::nullopt,
/*shared_time=*/std::nullopt,
/*new_score=*/std::nullopt,
/*drive_file_id=*/std::nullopt,
/*icon_url=*/std::nullopt}});
GetFileSuggestKeyedService()->SetSuggestionsForType(
FileSuggestionType::kLocalFile,
/*suggestions=*/std::vector<FileSuggestData>{
{FileSuggestionType::kLocalFile, file_path_2,
/*title=*/std::nullopt,
/*new_prediction_reason=*/std::nullopt,
/*modified_time=*/std::nullopt,
/*viewed_time=*/std::nullopt,
/*shared_time=*/std::nullopt,
/*new_score=*/std::nullopt,
/*drive_file_id=*/std::nullopt,
/*icon_url=*/std::nullopt}});
task_environment()->FastForwardBy(base::Seconds(1));
// Verify initial suggestions. Note that suggestions are reversed in the
// holding space model to account for the fact that items are presented in
// reverse-chronological order.
const bool suggestion_feature_enabled =
features::IsHoldingSpaceSuggestionsEnabled();
HoldingSpaceModel* model = HoldingSpaceController::Get()->model();
EXPECT_THAT(GetSuggestionsInModel(*model),
::testing::Conditional(
suggestion_feature_enabled,
::testing::ElementsAre(
std::make_pair(Type::kLocalSuggestion, file_path_2),
std::make_pair(Type::kDriveSuggestion, file_path_1)),
::testing::IsEmpty()));
// Remove all suggestions through the holding space client. Verify that
// `FileSuggestKeyedService::RemoveSuggestionsAndNotify()` is called if and
// only if the suggestions feature is enabled.
EXPECT_CALL(*GetFileSuggestKeyedService(),
RemoveSuggestionsAndNotify(
std::vector<base::FilePath>({file_path_1, file_path_2})))
.Times(suggestion_feature_enabled ? 1u : 0u);
HoldingSpaceController::Get()->client()->RemoveSuggestions(
{file_path_1, file_path_2});
task_environment()->FastForwardBy(base::Seconds(1));
// Verify that all suggestions have been removed from the `model`.
EXPECT_THAT(GetSuggestionsInModel(*model), IsEmpty());
}
TEST_P(HoldingSpaceSuggestionsDelegateTest, VerifySuggestionsInModel) {
const base::FilePath file_path_1 = drive_mount_point()->CreateArbitraryFile();
// Update Drive file suggestions. Fast-forward to ensure the suggestion fetch
// completes.
GetFileSuggestKeyedService()->SetSuggestionsForType(
FileSuggestionType::kDriveFile,
/*suggestions=*/std::vector<FileSuggestData>{
{FileSuggestionType::kDriveFile, file_path_1,
/*title=*/std::nullopt,
/*new_prediction_reason=*/std::nullopt,
/*modified_time=*/std::nullopt,
/*viewed_time=*/std::nullopt,
/*shared_time=*/std::nullopt,
/*new_score=*/std::nullopt,
/*drive_file_id=*/std::nullopt,
/*icon_url=*/std::nullopt}});
task_environment()->FastForwardBy(base::Seconds(1));
const bool suggestion_feature_enabled =
features::IsHoldingSpaceSuggestionsEnabled();
// Populate the expected suggestions array if the holding space suggestion
// feature is enabled. There should be no suggestions in the model when the
// feature is disabled.
std::vector<std::pair<HoldingSpaceItem::Type, base::FilePath>> expected;
if (suggestion_feature_enabled) {
expected = {{HoldingSpaceItem::Type::kDriveSuggestion, file_path_1}};
}
// Check the model after Drive file suggestions update.
HoldingSpaceModel* const model = HoldingSpaceController::Get()->model();
EXPECT_EQ(GetSuggestionsInModel(*model), expected);
const base::FilePath file_path_2 = local_mount_point()->CreateArbitraryFile();
// Update local file suggestions and check the model.
GetFileSuggestKeyedService()->SetSuggestionsForType(
FileSuggestionType::kLocalFile,
/*suggestions=*/std::vector<FileSuggestData>{
{FileSuggestionType::kLocalFile, file_path_2,
/*title=*/std::nullopt,
/*new_prediction_reason=*/std::nullopt,
/*modified_time=*/std::nullopt,
/*viewed_time=*/std::nullopt,
/*shared_time=*/std::nullopt,
/*new_score=*/std::nullopt,
/*drive_file_id=*/std::nullopt,
/*icon_url=*/std::nullopt}});
task_environment()->RunUntilIdle();
if (suggestion_feature_enabled) {
expected = {{HoldingSpaceItem::Type::kLocalSuggestion, file_path_2},
{HoldingSpaceItem::Type::kDriveSuggestion, file_path_1}};
}
EXPECT_EQ(GetSuggestionsInModel(*model), expected);
const base::FilePath file_path_3 = drive_mount_point()->CreateArbitraryFile();
// Update Drive file suggestions again and check the model.
GetFileSuggestKeyedService()->SetSuggestionsForType(
FileSuggestionType::kDriveFile,
/*suggestions=*/
std::vector<FileSuggestData>{{FileSuggestionType::kDriveFile, file_path_1,
/*title=*/std::nullopt,
/*new_prediction_reason=*/std::nullopt,
/*modified_time=*/std::nullopt,
/*viewed_time=*/std::nullopt,
/*shared_time=*/std::nullopt,
/*new_score=*/std::nullopt,
/*drive_file_id=*/std::nullopt,
/*icon_url=*/std::nullopt},
{FileSuggestionType::kDriveFile, file_path_3,
/*title=*/std::nullopt,
/*new_prediction_reason=*/std::nullopt,
/*modified_time=*/std::nullopt,
/*viewed_time=*/std::nullopt,
/*shared_time=*/std::nullopt,
/*new_score=*/std::nullopt,
/*drive_file_id=*/std::nullopt,
/*icon_url=*/std::nullopt}});
task_environment()->FastForwardBy(base::Seconds(1));
if (suggestion_feature_enabled) {
expected = {{HoldingSpaceItem::Type::kLocalSuggestion, file_path_2},
{HoldingSpaceItem::Type::kDriveSuggestion, file_path_3},
{HoldingSpaceItem::Type::kDriveSuggestion, file_path_1}};
}
EXPECT_EQ(GetSuggestionsInModel(*model), expected);
// Update Drive file suggestions with an empty array.
GetFileSuggestKeyedService()->SetSuggestionsForType(
FileSuggestionType::kDriveFile,
/*suggestions=*/std::vector<FileSuggestData>{});
task_environment()->FastForwardBy(base::Seconds(1));
// Drive file suggestions should be removed from the model if suggestions are
// enabled.
if (suggestion_feature_enabled) {
expected = {{HoldingSpaceItem::Type::kLocalSuggestion, file_path_2}};
}
EXPECT_EQ(GetSuggestionsInModel(*model), expected);
// Update local file suggestions with an empty array.
GetFileSuggestKeyedService()->SetSuggestionsForType(
FileSuggestionType::kLocalFile,
/*suggestions=*/std::vector<FileSuggestData>{});
task_environment()->FastForwardBy(base::Seconds(1));
// There should be no suggestions in the model.
expected.clear();
EXPECT_EQ(GetSuggestionsInModel(*model), expected);
}
TEST_P(HoldingSpaceSuggestionsDelegateTest, DownloadsFolderNotSuggested) {
auto downloads_mount =
local_mount_point()->CreateAndMountDownloads(GetProfile());
auto downloads_path =
file_manager::util::GetDownloadsFolderForProfile(GetProfile());
auto other_folder_path = downloads_path.Append("contained_folder");
ASSERT_TRUE(base::CreateDirectory(other_folder_path));
const base::FilePath file_path = local_mount_point()->CreateArbitraryFile();
GetFileSuggestKeyedService()->SetSuggestionsForType(
FileSuggestionType::kLocalFile,
/*suggestions=*/std::vector<FileSuggestData>{
{FileSuggestionType::kLocalFile, downloads_path,
/*title=*/std::nullopt,
/*new_prediction_reason=*/std::nullopt,
/*modified_time=*/std::nullopt,
/*viewed_time=*/std::nullopt,
/*shared_time=*/std::nullopt,
/*new_score=*/std::nullopt,
/*drive_file_id=*/std::nullopt,
/*icon_url=*/std::nullopt},
{FileSuggestionType::kLocalFile, other_folder_path,
/*title=*/std::nullopt,
/*new_prediction_reason=*/std::nullopt,
/*modified_time=*/std::nullopt,
/*viewed_time=*/std::nullopt,
/*shared_time=*/std::nullopt,
/*new_score=*/std::nullopt,
/*drive_file_id=*/std::nullopt,
/*icon_url=*/std::nullopt},
{FileSuggestionType::kLocalFile, file_path,
/*title=*/std::nullopt,
/*new_prediction_reason=*/std::nullopt,
/*modified_time=*/std::nullopt,
/*viewed_time=*/std::nullopt,
/*shared_time=*/std::nullopt,
/*new_score=*/std::nullopt,
/*drive_file_id=*/std::nullopt,
/*icon_url=*/std::nullopt}});
task_environment()->FastForwardBy(base::Seconds(1));
std::vector<std::pair<HoldingSpaceItem::Type, base::FilePath>> expected;
if (features::IsHoldingSpaceSuggestionsEnabled()) {
expected = {{HoldingSpaceItem::Type::kLocalSuggestion, file_path},
{HoldingSpaceItem::Type::kLocalSuggestion, other_folder_path}};
}
EXPECT_EQ(GetSuggestionsInModel(*HoldingSpaceController::Get()->model()),
expected);
}
TEST_P(HoldingSpaceSuggestionsDelegateTest, PinAndUnpinSuggestions) {
const base::FilePath file_path_1 = drive_mount_point()->CreateArbitraryFile();
const GURL file_system_url_1 = GetFileSystemUrl(GetProfile(), file_path_1);
const HoldingSpaceFile::FileSystemType file_system_type_1 =
holding_space_util::ResolveFileSystemType(GetProfile(),
file_system_url_1);
// Update Drive file suggestions. Fast-forward to ensure the suggestion fetch
// completes.
GetFileSuggestKeyedService()->SetSuggestionsForType(
FileSuggestionType::kDriveFile,
/*suggestions=*/std::vector<FileSuggestData>{
{FileSuggestionType::kDriveFile, file_path_1,
/*title=*/std::nullopt,
/*new_prediction_reason=*/std::nullopt,
/*modified_time=*/std::nullopt,
/*viewed_time=*/std::nullopt,
/*shared_time=*/std::nullopt,
/*new_score=*/std::nullopt,
/*drive_file_id=*/std::nullopt,
/*icon_url=*/std::nullopt}});
task_environment()->FastForwardBy(base::Seconds(1));
const bool suggestion_feature_enabled =
features::IsHoldingSpaceSuggestionsEnabled();
// Populate the expected suggestions array if the holding space suggestion
// feature is enabled. There should be no suggestions in the model when the
// feature is disabled.
std::vector<std::pair<HoldingSpaceItem::Type, base::FilePath>> expected;
if (suggestion_feature_enabled) {
expected = {{HoldingSpaceItem::Type::kDriveSuggestion, file_path_1}};
}
// Check the model after Drive file suggestions update.
HoldingSpaceModel* const model = HoldingSpaceController::Get()->model();
EXPECT_EQ(GetSuggestionsInModel(*model), expected);
const base::FilePath file_path_2 = local_mount_point()->CreateArbitraryFile();
// Update local file suggestions and check the model.
GetFileSuggestKeyedService()->SetSuggestionsForType(
FileSuggestionType::kLocalFile,
/*suggestions=*/std::vector<FileSuggestData>{
{FileSuggestionType::kLocalFile, file_path_2,
/*title=*/std::nullopt,
/*new_prediction_reason=*/std::nullopt,
/*modified_time=*/std::nullopt,
/*viewed_time=*/std::nullopt,
/*shared_time=*/std::nullopt,
/*new_score=*/std::nullopt,
/*drive_file_id=*/std::nullopt,
/*icon_url=*/std::nullopt}});
task_environment()->RunUntilIdle();
if (suggestion_feature_enabled) {
expected = {{HoldingSpaceItem::Type::kLocalSuggestion, file_path_2},
{HoldingSpaceItem::Type::kDriveSuggestion, file_path_1}};
}
EXPECT_EQ(GetSuggestionsInModel(*model), expected);
// Pin the suggested Drive file and verify that the suggestion is removed
// from the model if suggestions are enabled.
auto pinned_item = HoldingSpaceItem::CreateFileBackedItem(
HoldingSpaceItem::Type::kPinnedFile,
HoldingSpaceFile(file_path_1, file_system_type_1, file_system_url_1),
base::BindOnce(&CreateTestHoldingSpaceImage));
const auto& pinned_item_id = pinned_item->id();
model->AddItem(std::move(pinned_item));
task_environment()->RunUntilIdle();
if (suggestion_feature_enabled) {
expected = {{HoldingSpaceItem::Type::kLocalSuggestion, file_path_2}};
}
EXPECT_EQ(GetSuggestionsInModel(*model), expected);
// Unpin the suggested Drive file and verify that the suggestion is re-added
// to the model if suggestions are enabled.
model->RemoveItem(pinned_item_id);
task_environment()->RunUntilIdle();
if (suggestion_feature_enabled) {
expected = {{HoldingSpaceItem::Type::kLocalSuggestion, file_path_2},
{HoldingSpaceItem::Type::kDriveSuggestion, file_path_1}};
}
EXPECT_EQ(GetSuggestionsInModel(*model), expected);
// Add an uninitialized pinned item for the suggested local file to the model
// and verify that there is no change to the model's suggestions.
auto* uninitialized_pinned_item_ptr = AddUninitializedItem(
model, HoldingSpaceItem::Type::kPinnedFile, file_path_2);
// The `expected` suggestions should not have changed.
EXPECT_EQ(GetSuggestionsInModel(*model), expected);
// Remove the suggested local file's uninitialized pinned item and verify
// that there is no change to the model's suggestions.
model->RemoveItem(uninitialized_pinned_item_ptr->id());
// The `expected` suggestions should not have changed.
EXPECT_EQ(GetSuggestionsInModel(*model), expected);
// Add an uninitialized pinned item for the suggested local file to the model
// and verify that there is no change to the model's suggestions.
auto* partially_initialized_pinned_item_ptr = AddUninitializedItem(
model, HoldingSpaceItem::Type::kPinnedFile, file_path_2);
// The `expected` suggestions should not have changed.
EXPECT_EQ(GetSuggestionsInModel(*model), expected);
// Initialize the pinned item for the suggested local file and verify that
// the suggestion is removed from the model if suggestions are enabled.
model->InitializeOrRemoveItem(
partially_initialized_pinned_item_ptr->id(),
HoldingSpaceFile(file_path_2, HoldingSpaceFile::FileSystemType::kTest,
GetFileSystemUrl(GetProfile(), file_path_2)));
task_environment()->RunUntilIdle();
if (suggestion_feature_enabled) {
expected = {{HoldingSpaceItem::Type::kDriveSuggestion, file_path_1}};
}
EXPECT_EQ(GetSuggestionsInModel(*model), expected);
}
// Verifies the file suggestion update on a profile with restored suggestions.
TEST_P(HoldingSpaceSuggestionsDelegateTest, RestoreSuggestions) {
const base::FilePath drive_file = drive_mount_point()->CreateArbitraryFile();
const GURL drive_file_system_url = GetFileSystemUrl(GetProfile(), drive_file);
const HoldingSpaceFile::FileSystemType drive_file_system_type =
holding_space_util::ResolveFileSystemType(GetProfile(),
drive_file_system_url);
std::unique_ptr<HoldingSpaceItem> drive_file_suggestion =
HoldingSpaceItem::CreateFileBackedItem(
HoldingSpaceItem::Type::kDriveSuggestion,
HoldingSpaceFile(drive_file, drive_file_system_type,
drive_file_system_url),
base::BindOnce(&CreateTestHoldingSpaceImage));
// Create a secondary profile with a persisted drive file suggestion.
TestingProfile* const secondary_profile = CreateSecondaryProfile(
base::BindLambdaForTesting([&](TestingPrefStore* pref_store) {
base::Value::List persisted_items;
persisted_items.Append(drive_file_suggestion->Serialize());
pref_store->SetValueSilently(
HoldingSpacePersistenceDelegate::kPersistencePath,
base::Value(std::move(persisted_items)),
PersistentPrefStore::DEFAULT_PREF_WRITE_FLAGS);
}));
// Activate `secondary_profile`. Wait until the model updates.
ActivateSecondaryProfile();
HoldingSpaceModelAttachedWaiter(secondary_profile).Wait();
HoldingSpaceModel* const secondary_holding_space_model =
HoldingSpaceController::Get()->model();
ItemsInitializedWaiter(secondary_holding_space_model).Wait();
const bool suggestion_feature_enabled =
features::IsHoldingSpaceSuggestionsEnabled();
EXPECT_EQ(secondary_holding_space_model->items().size(),
suggestion_feature_enabled ? 1u : 0u);
// Update local file suggestions on the secondary profile. Fast-forward to
// ensure the suggestion fetch completes.
const base::FilePath local_file = local_mount_point()->CreateArbitraryFile();
static_cast<MockFileSuggestKeyedService*>(
FileSuggestKeyedServiceFactory::GetInstance()->GetService(
secondary_profile))
->SetSuggestionsForType(FileSuggestionType::kLocalFile,
/*suggestions=*/std::vector<FileSuggestData>{
{FileSuggestionType::kLocalFile, local_file,
/*title=*/std::nullopt,
/*new_prediction_reason=*/std::nullopt,
/*modified_time=*/std::nullopt,
/*viewed_time=*/std::nullopt,
/*shared_time=*/std::nullopt,
/*new_score=*/std::nullopt,
/*drive_file_id=*/std::nullopt,
/*icon_url=*/std::nullopt}});
task_environment()->FastForwardBy(base::Seconds(1));
const auto& model_items = secondary_holding_space_model->items();
if (suggestion_feature_enabled) {
// The drive and local file suggestions should coexist in the model.
ASSERT_EQ(model_items.size(), 2u);
EXPECT_EQ(model_items[0]->file().file_path, local_file);
EXPECT_EQ(model_items[1]->file().file_path, drive_file);
} else {
EXPECT_TRUE(model_items.empty());
}
}
// Verifies by updating file suggestions in the holding space model which
// contains the suggested files from an unmounted file system.
TEST_P(HoldingSpaceSuggestionsDelegateTest, UpdateSuggestionsWithDelayedMount) {
auto delayed_mount = std::make_unique<ScopedTestMountPoint>(
"drivefs-delayed_mount",
/*file_system_type=*/storage::kFileSystemTypeDriveFs,
/*volume_type=*/file_manager::VOLUME_TYPE_GOOGLE_DRIVE);
const base::FilePath delayed_mount_file_path =
delayed_mount->GetRootPath().Append("delayed file");
auto delayed_holding_space_item = HoldingSpaceItem::CreateFileBackedItem(
HoldingSpaceItem::Type::kDriveSuggestion,
HoldingSpaceFile(delayed_mount_file_path,
HoldingSpaceFile::FileSystemType::kTest,
GURL("filesystem:fake")),
base::BindOnce(&CreateTestHoldingSpaceImage));
// Create a secondary profile with a persisted delayed file suggestion.
TestingProfile* const secondary_profile = CreateSecondaryProfile(
base::BindLambdaForTesting([&](TestingPrefStore* pref_store) {
base::Value::List persisted_items;
persisted_items.Append(delayed_holding_space_item->Serialize());
pref_store->SetValueSilently(
HoldingSpacePersistenceDelegate::kPersistencePath,
base::Value(std::move(persisted_items)),
PersistentPrefStore::DEFAULT_PREF_WRITE_FLAGS);
}));
// Activate `secondary_profile`. Wait until the model updates.
ActivateSecondaryProfile();
HoldingSpaceModelAttachedWaiter(secondary_profile).Wait();
HoldingSpaceModel* const secondary_holding_space_model =
HoldingSpaceController::Get()->model();
const bool suggestion_feature_enabled =
features::IsHoldingSpaceSuggestionsEnabled();
EXPECT_EQ(secondary_holding_space_model->items().size(),
suggestion_feature_enabled ? 1u : 0u);
// Update with a local file suggestion.
const base::FilePath local_file = local_mount_point()->CreateArbitraryFile();
static_cast<MockFileSuggestKeyedService*>(
FileSuggestKeyedServiceFactory::GetInstance()->GetService(
secondary_profile))
->SetSuggestionsForType(FileSuggestionType::kLocalFile,
/*suggestions=*/std::vector<FileSuggestData>{
{FileSuggestionType::kLocalFile, local_file,
/*title=*/std::nullopt,
/*new_prediction_reason=*/std::nullopt,
/*modified_time=*/std::nullopt,
/*viewed_time=*/std::nullopt,
/*shared_time=*/std::nullopt,
/*new_score=*/std::nullopt,
/*drive_file_id=*/std::nullopt,
/*icon_url=*/std::nullopt}});
task_environment()->FastForwardBy(base::Seconds(1));
const auto& model_items = secondary_holding_space_model->items();
if (suggestion_feature_enabled) {
ASSERT_EQ(model_items.size(), 2u);
EXPECT_EQ(model_items[0]->file().file_path, local_file);
EXPECT_EQ(model_items[0]->type(), HoldingSpaceItem::Type::kLocalSuggestion);
EXPECT_TRUE(model_items[0]->IsInitialized());
EXPECT_EQ(model_items[1]->file().file_path, delayed_mount_file_path);
EXPECT_EQ(model_items[1]->type(), HoldingSpaceItem::Type::kDriveSuggestion);
EXPECT_FALSE(model_items[1]->IsInitialized());
} else {
EXPECT_TRUE(model_items.empty());
}
}
} // namespace ash
|