File: app_list_controller_impl.cc

package info (click to toggle)
chromium 139.0.7258.127-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 6,122,156 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (2230 lines) | stat: -rw-r--r-- 81,770 bytes parent folder | download | duplicates (3)
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
// Copyright 2018 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ash/app_list/app_list_controller_impl.h"

#include <memory>
#include <optional>
#include <string_view>
#include <utility>
#include <vector>

#include "ash/app_list/app_list_badge_controller.h"
#include "ash/app_list/app_list_bubble_presenter.h"
#include "ash/app_list/app_list_model_provider.h"
#include "ash/app_list/app_list_presenter_impl.h"
#include "ash/app_list/app_list_view_delegate.h"
#include "ash/app_list/apps_collections_controller.h"
#include "ash/app_list/model/app_list_item.h"
#include "ash/app_list/model/app_list_item_observer.h"
#include "ash/app_list/model/app_list_model.h"
#include "ash/app_list/model/app_list_model_observer.h"
#include "ash/app_list/model/search/search_box_model.h"
#include "ash/app_list/model/search/search_model.h"
#include "ash/app_list/quick_app_access_model.h"
#include "ash/app_list/views/app_list_bubble_view.h"
#include "ash/app_list/views/app_list_item_view.h"
#include "ash/app_list/views/app_list_main_view.h"
#include "ash/app_list/views/app_list_toast_container_view.h"
#include "ash/app_list/views/app_list_toast_view.h"
#include "ash/app_list/views/app_list_view.h"
#include "ash/app_list/views/contents_view.h"
#include "ash/app_list/views/search_box_view.h"
#include "ash/assistant/assistant_controller_impl.h"
#include "ash/assistant/model/assistant_ui_model.h"
#include "ash/assistant/ui/assistant_view_delegate.h"
#include "ash/assistant/util/assistant_util.h"
#include "ash/assistant/util/deep_link_util.h"
#include "ash/capture_mode/capture_mode_constants.h"
#include "ash/capture_mode/sunfish_scanner_feature_watcher.h"
#include "ash/constants/ash_features.h"
#include "ash/constants/ash_pref_names.h"
#include "ash/constants/ash_switches.h"
#include "ash/constants/web_app_id_constants.h"
#include "ash/keyboard/ui/keyboard_ui_controller.h"
#include "ash/public/cpp/app_list/app_list_client.h"
#include "ash/public/cpp/app_list/app_list_controller_observer.h"
#include "ash/public/cpp/app_list/app_list_metrics.h"
#include "ash/public/cpp/app_list/app_list_notifier.h"
#include "ash/public/cpp/app_list/app_list_types.h"
#include "ash/public/cpp/assistant/controller/assistant_controller.h"
#include "ash/public/cpp/assistant/controller/assistant_ui_controller.h"
#include "ash/public/cpp/capture_mode/capture_mode_api.h"
#include "ash/public/cpp/feature_discovery_duration_reporter.h"
#include "ash/public/cpp/feature_discovery_metric_util.h"
#include "ash/public/cpp/shelf_config.h"
#include "ash/public/cpp/shelf_types.h"
#include "ash/public/cpp/shell_window_ids.h"
#include "ash/public/cpp/wallpaper/wallpaper_controller.h"
#include "ash/root_window_controller.h"
#include "ash/scanner/scanner_controller.h"
#include "ash/scanner/scanner_metrics.h"
#include "ash/screen_util.h"
#include "ash/session/session_controller_impl.h"
#include "ash/shelf/home_button.h"
#include "ash/shelf/shelf_navigation_widget.h"
#include "ash/shell.h"
#include "ash/system/toast/anchored_nudge_manager_impl.h"
#include "ash/user_education/welcome_tour/welcome_tour_metrics.h"
#include "ash/wm/float/float_controller.h"
#include "ash/wm/mru_window_tracker.h"
#include "ash/wm/overview/overview_controller.h"
#include "ash/wm/overview/overview_session.h"
#include "ash/wm/splitview/split_view_controller.h"
#include "ash/wm/window_state.h"
#include "ash/wm/window_util.h"
#include "base/barrier_closure.h"
#include "base/callback_list.h"
#include "base/check.h"
#include "base/command_line.h"
#include "base/containers/adapters.h"
#include "base/containers/contains.h"
#include "base/functional/bind.h"
#include "base/functional/callback_helpers.h"
#include "base/logging.h"
#include "base/memory/raw_ptr.h"
#include "base/metrics/histogram_macros.h"
#include "base/metrics/user_metrics.h"
#include "base/scoped_observation.h"
#include "base/strings/string_util.h"
#include "base/trace_event/trace_event.h"
#include "chromeos/ash/services/assistant/public/cpp/assistant_browser_delegate.h"
#include "chromeos/ash/services/assistant/public/cpp/assistant_enums.h"
#include "chromeos/ash/services/assistant/public/cpp/features.h"
#include "components/account_id/account_id.h"
#include "components/pref_registry/pref_registry_syncable.h"
#include "components/prefs/pref_member.h"
#include "components/prefs/pref_registry_simple.h"
#include "components/services/app_service/public/cpp/app_registry_cache.h"
#include "components/services/app_service/public/cpp/app_registry_cache_wrapper.h"
#include "ui/base/models/image_model.h"
#include "ui/base/mojom/menu_source_type.mojom-forward.h"
#include "ui/compositor/compositor.h"
#include "ui/compositor/layer.h"
#include "ui/compositor/layer_animation_sequence.h"
#include "ui/display/display_observer.h"
#include "ui/display/manager/display_manager.h"
#include "ui/display/screen.h"
#include "ui/display/util/display_util.h"
#include "ui/views/controls/textfield/textfield.h"
#include "ui/wm/core/scoped_animation_disabler.h"
#include "ui/wm/core/window_animations.h"

namespace ash {

using assistant::AssistantEntryPoint;
using assistant::AssistantExitPoint;

namespace {

constexpr char kHomescreenAnimationHistogram[] =
    "Ash.Homescreen.AnimationSmoothness";

// The target scale to which (or from which) the home launcher will animate when
// overview is being shown (or hidden) using fade transitions while home
// launcher is shown.
constexpr float kOverviewFadeAnimationScale = 0.92f;

// The home launcher animation duration for transitions that accompany overview
// fading transitions.
constexpr base::TimeDelta kOverviewFadeAnimationDuration =
    base::Milliseconds(350);

bool g_sunfish_nudge_disabled_for_test = false;

// Update layer animation settings for launcher scale and opacity animation that
// runs on overview mode change.
void UpdateOverviewSettings(base::TimeDelta duration,
                            ui::ScopedLayerAnimationSettings* settings) {
  settings->SetTransitionDuration(kOverviewFadeAnimationDuration);
  settings->SetTweenType(gfx::Tween::FAST_OUT_SLOW_IN);
  settings->SetPreemptionStrategy(
      ui::LayerAnimator::IMMEDIATELY_ANIMATE_TO_NEW_TARGET);
}

// Layer animation observer that waits for layer animator to schedule, and
// complete animations. When all animations complete, it fires |callback| and
// deletes itself.
class WindowAnimationsCallback : public ui::LayerAnimationObserver {
 public:
  WindowAnimationsCallback(base::OnceClosure callback,
                           ui::LayerAnimator* animator)
      : callback_(std::move(callback)), animator_(animator) {
    subscription_ = animator_->AddSequenceScheduledCallback(
        base::BindRepeating(&WindowAnimationsCallback::OnSequenceScheduled,
                            base::Unretained(this)));
  }
  WindowAnimationsCallback(const WindowAnimationsCallback&) = delete;
  WindowAnimationsCallback& operator=(const WindowAnimationsCallback&) = delete;
  ~WindowAnimationsCallback() override = default;

  // ui::LayerAnimationObserver:
  void OnLayerAnimationEnded(ui::LayerAnimationSequence* sequence) override {
    FireCallbackIfDone();
  }
  void OnLayerAnimationAborted(ui::LayerAnimationSequence* sequence) override {
    FireCallbackIfDone();
  }
  void OnLayerAnimationScheduled(
      ui::LayerAnimationSequence* sequence) override {}

  void OnDetachedFromSequence(ui::LayerAnimationSequence* sequence) override {
    FireCallbackIfDone();
  }

 private:
  void OnSequenceScheduled(ui::LayerAnimationSequence* sequence) {
    // LayerAnimationSequence::RemoveObserver is called by the ancestor during
    // destruction.
    sequence->AddObserver(this);
  }

  // Fires the callback if all scheduled animations completed (either ended or
  // got aborted).
  void FireCallbackIfDone() {
    if (!callback_ || animator_->is_animating())
      return;
    std::move(callback_).Run();
    delete this;
  }

  base::OnceClosure callback_;
  raw_ptr<ui::LayerAnimator>
      animator_;  // Owned by the layer that is animating.
  base::CallbackListSubscription subscription_;
};

// Minimizes all windows in |windows| that aren't in the home screen container,
// and are not in |windows_to_ignore|. Done in reverse order to preserve the mru
// ordering.
// Returns true if any windows are minimized.
bool MinimizeAllWindows(const aura::Window::Windows& windows,
                        const aura::Window::Windows& windows_to_ignore) {
  aura::Window* container = Shell::Get()->GetPrimaryRootWindow()->GetChildById(
      kShellWindowId_HomeScreenContainer);
  aura::Window::Windows windows_to_minimize;
  for (aura::Window* window : base::Reversed(windows)) {
    if (!container->Contains(window) &&
        !base::Contains(windows_to_ignore, window) &&
        !WindowState::Get(window)->IsMinimized()) {
      windows_to_minimize.push_back(window);
    }
  }

  window_util::MinimizeAndHideWithoutAnimation(windows_to_minimize);
  return !windows_to_minimize.empty();
}

TabletModeAnimationTransition CalculateAnimationTransitionForMetrics(
    HomeLauncherAnimationTrigger trigger,
    bool launcher_should_show) {
  switch (trigger) {
    case HomeLauncherAnimationTrigger::kHideForWindow:
      return TabletModeAnimationTransition::kHideHomeLauncherForWindow;
    case HomeLauncherAnimationTrigger::kLauncherButton:
      return TabletModeAnimationTransition::kHomeButtonShow;
    case HomeLauncherAnimationTrigger::kOverviewModeFade:
      return launcher_should_show
                 ? TabletModeAnimationTransition::kFadeOutOverview
                 : TabletModeAnimationTransition::kFadeInOverview;
  }
}

PrefService* GetLastActiveUserPrefService() {
  return Shell::Get()->session_controller()->GetLastActiveUserPrefService();
}

// Gets the MRU window shown over the applist when in tablet mode.
// Returns nullptr if no windows are shown over the applist.
aura::Window* GetTopVisibleWindow() {
  std::vector<raw_ptr<aura::Window, VectorExperimental>> window_list =
      Shell::Get()->mru_window_tracker()->BuildWindowListIgnoreModal(
          DesksMruType::kActiveDesk);
  for (aura::Window* window : window_list) {
    if (!window->TargetVisibility() || WindowState::Get(window)->IsMinimized())
      continue;

    // Floated windows can be tucked offscreen in tablet mode. Their target
    // visibility is true but the app list is fully visible under them.
    if (WindowState::Get(window)->IsFloated() &&
        Shell::Get()->float_controller()->IsFloatedWindowTuckedForTablet(
            window)) {
      continue;
    }

    return window;
  }
  return nullptr;
}

void LogAppListShowSource(AppListShowSource show_source, bool app_list_bubble) {
  if (app_list_bubble) {
    UMA_HISTOGRAM_ENUMERATION("Apps.AppListBubbleShowSource", show_source);
    return;
  }
  UMA_HISTOGRAM_ENUMERATION("Apps.AppListShowSource", show_source);
}

std::optional<TabletModeAnimationTransition>
GetTransitionFromMetricsAnimationInfo(
    std::optional<HomeLauncherAnimationInfo> animation_info) {
  if (!animation_info.has_value())
    return std::nullopt;

  return CalculateAnimationTransitionForMetrics(animation_info->trigger,
                                                animation_info->showing);
}

bool IsKioskSession() {
  return Shell::Get()->session_controller()->IsRunningInAppMode();
}

void MaybeLogWelcomeTourInteraction(AppListShowSource show_source) {
  if (features::IsWelcomeTourEnabled() &&
      IsAppListShowSourceUserTriggered(show_source)) {
    welcome_tour_metrics::RecordInteraction(
        GetLastActiveUserPrefService(),
        welcome_tour_metrics::Interaction::kLauncher);
  }
}

bool IsAssistantExitPointScreenshot(
    std::optional<assistant::AssistantExitPoint> exit_point) {
  return exit_point == AssistantExitPoint::kScreenshot;
}

bool IsAssistantExitPointInsideLauncher(
    std::optional<assistant::AssistantExitPoint> exit_point) {
  return exit_point == AssistantExitPoint::kBackInLauncher ||
         exit_point == AssistantExitPoint::kLauncherSearchIphChip;
}

SearchBoxModel::SunfishButtonVisibility GetSunfishButtonVisibility(
    const SunfishScannerFeatureWatcher& feature_watcher) {
  if (feature_watcher.CanShowSunfishUi()) {
    return SearchBoxModel::SunfishButtonVisibility::kShownWithSunfishIcon;
  }

  if (feature_watcher.CanShowScannerUi()) {
    return SearchBoxModel::SunfishButtonVisibility::kShownWithScannerIcon;
  }

  return SearchBoxModel::SunfishButtonVisibility::kHidden;
}

}  // namespace

AppListControllerImpl::AppListControllerImpl()
    : model_provider_(std::make_unique<AppListModelProvider>()),
      fullscreen_presenter_(std::make_unique<AppListPresenterImpl>(this)),
      bubble_presenter_(std::make_unique<AppListBubblePresenter>(this)),
      badge_controller_(std::make_unique<AppListBadgeController>()),
      apps_collections_controller_(
          std::make_unique<AppsCollectionsController>()) {
  SessionControllerImpl* session_controller =
      Shell::Get()->session_controller();
  session_controller->AddObserver(this);

  // In case of crash-and-restart case where session state starts with ACTIVE
  // and does not change to trigger OnSessionStateChanged(), notify the current
  // session state here to ensure that the app list is shown.
  OnSessionStateChanged(session_controller->GetSessionState());

  Shell* shell = Shell::Get();
  sunfish_scanner_feature_observation_.Observe(
      shell->sunfish_scanner_feature_watcher());
  // Get the initial Sunfish-session button state.
  OnSunfishScannerFeatureStatesChanged(
      *sunfish_scanner_feature_observation_.GetSource());
  WallpaperController::Get()->AddObserver(this);
  shell->AddShellObserver(this);
  shell->overview_controller()->AddObserver(this);
  display::Screen::GetScreen()->AddObserver(this);
  keyboard::KeyboardUIController::Get()->AddObserver(this);
  AssistantState::Get()->AddObserver(this);
  shell->display_manager()->AddDisplayManagerObserver(this);
  AssistantController::Get()->AddObserver(this);
  AssistantUiController::Get()->GetModel()->AddObserver(this);
  FeatureDiscoveryDurationReporter::GetInstance()->AddObserver(this);
}

AppListControllerImpl::~AppListControllerImpl() {
  if (tracked_app_window_) {
    tracked_app_window_->RemoveObserver(this);
    tracked_app_window_ = nullptr;
  }

  if (has_session_started_)
    RecordMetricsOnSessionEnd();

  // If this is being destroyed before the Shell starts shutting down, first
  // remove this from objects it's observing.
  if (!is_shutdown_)
    Shutdown();

  if (client_)
    client_->OnAppListControllerDestroyed();

  // Dismiss the window before `fullscreen_presenter_` is reset, because
  // Dimiss() may call back into this object and access `fullscreen_presenter_`.
  fullscreen_presenter_->Dismiss(base::TimeTicks());
}

// static
void AppListControllerImpl::RegisterProfilePrefs(PrefRegistrySimple* registry) {
  registry->RegisterBooleanPref(
      prefs::kLauncherFeedbackOnContinueSectionSent, false,
      user_prefs::PrefRegistrySyncable::SYNCABLE_OS_PREF);
  registry->RegisterBooleanPref(
      prefs::kLauncherContinueSectionHidden, false,
      user_prefs::PrefRegistrySyncable::SYNCABLE_OS_PREF);
  registry->RegisterTimePref(prefs::kLauncherLastContinueRequestTime,
                             base::Time());
  registry->RegisterBooleanPref(prefs::kLauncherUseLongContinueDelay, false);

  // The prefs for launcher search controls.
  registry->RegisterDictionaryPref(prefs::kLauncherSearchCategoryControlStatus);

  registry->RegisterTimePref(prefs::kLauncherSearchLastFileScanLogTime,
                             base::Time());

  // The prefs for apps collections experiment.
  registry->RegisterIntegerPref(
      prefs::kLauncherAppsCollectionsExperimentArm,
      static_cast<int>(
          AppsCollectionsController::ExperimentalArm::kDefaultValue));

  // The prefs for the Sunfish launcher nudge.
  registry->RegisterIntegerPref(prefs::kSunfishLauncherNudgeShownCount, 0);
  registry->RegisterTimePref(prefs::kSunfishLauncherNudgeLastShown,
                             base::Time());
}

void AppListControllerImpl::SetClient(AppListClient* client) {
  client_ = client;
  apps_collections_controller_->SetClient(client);
}

AppListClient* AppListControllerImpl::GetClient() {
  DCHECK(client_);
  return client_;
}

AppListNotifier* AppListControllerImpl::GetNotifier() {
  if (!client_)
    return nullptr;
  return client_->GetNotifier();
}

std::unique_ptr<ScopedIphSession>
AppListControllerImpl::CreateLauncherSearchIphSession() {
  if (!client_) {
    return nullptr;
  }
  return client_->CreateLauncherSearchIphSession();
}

void AppListControllerImpl::SetActiveModel(
    int profile_id,
    AppListModel* model,
    SearchModel* search_model,
    QuickAppAccessModel* quick_app_access_model) {
  profile_id_ = profile_id;
  model_provider_->SetActiveModel(model, search_model, quick_app_access_model);
  UpdateSearchBoxUiVisibilities();
}

void AppListControllerImpl::ClearActiveModel() {
  profile_id_ = kAppListInvalidProfileID;
  model_provider_->ClearActiveModel();
  UpdateSearchBoxUiVisibilities();
}

void AppListControllerImpl::DismissAppList() {
  if (tracked_app_window_) {
    tracked_app_window_->RemoveObserver(this);
    tracked_app_window_ = nullptr;
  }

  // Don't check tablet mode here. This function can be called during tablet
  // mode transitions and we always want to close anyway.
  bubble_presenter_->Dismiss();

  fullscreen_presenter_->Dismiss(base::TimeTicks());
}

void AppListControllerImpl::ShowAppList(AppListShowSource source) {
  if (Shell::Get()->session_controller()->GetSessionState() !=
      session_manager::SessionState::ACTIVE) {
    return;
  }

  last_open_source_ = source;
  Show(GetDisplayIdToShowAppListOn(), source, base::TimeTicks(),
       /*should_record_metrics=*/true);
}

AppListShowSource AppListControllerImpl::LastAppListShowSource() {
  DCHECK(last_open_source_.has_value());
  return last_open_source_.value();
}

aura::Window* AppListControllerImpl::GetWindow() {
  if (IsInTabletMode()) {
    return fullscreen_presenter_->GetWindow();
  }
  return bubble_presenter_->GetWindow();
}

bool AppListControllerImpl::IsVisible(
    const std::optional<int64_t>& display_id) {
  return last_visible_ && (!display_id.has_value() ||
                           display_id.value() == last_visible_display_id_);
}

bool AppListControllerImpl::IsVisible() {
  return IsVisible(std::nullopt);
}

void AppListControllerImpl::OnActiveUserPrefServiceChanged(
    PrefService* pref_service) {
  if (IsKioskSession()) {
    return;
  }

  UpdateSearchBoxUiVisibilities();

  if (!IsInTabletMode()) {
    DismissAppList();
    return;
  }

  // The app list is not dismissed before switching user, suggestion chips will
  // not be shown. So reset app list state and trigger an initial search here to
  // update the suggestion results.
  if (fullscreen_presenter_->GetView()) {
    fullscreen_presenter_->GetView()->CloseOpenedPage();
    fullscreen_presenter_->GetView()->search_box_view()->ClearSearch();
  }
}

void AppListControllerImpl::OnSessionStateChanged(
    session_manager::SessionState state) {
  if (state == session_manager::SessionState::ACTIVE)
    has_session_started_ = true;

  const bool in_clamshell = !IsInTabletMode();
  if (state != session_manager::SessionState::ACTIVE || IsKioskSession()) {
    if (in_clamshell)
      DismissAppList();
    return;
  }

  if (base::FeatureList::IsEnabled(features::kQuickAppAccessTestUI)) {
    SetHomeButtonQuickApp(kOsSettingsAppId);
  }

  if (in_clamshell)
    return;

  // Show the app list after signing in in tablet mode. For metrics, the app
  // list is not considered shown since the browser window is shown over app
  // list upon login.
  if (!fullscreen_presenter_->GetTargetVisibility())
    ShowHomeScreen(AppListShowSource::kTabletMode);

  // Hide app list UI initially to prevent app list from flashing in background
  // while the initial app window is being shown.
  if (!last_target_visible_ && !ShouldHomeLauncherBeVisible())
    fullscreen_presenter_->SetViewVisibility(false);
  else
    OnVisibilityChanged(true, last_visible_display_id_);
}

void AppListControllerImpl::OnUserSessionAdded(const AccountId& account_id) {
  if (!client_)
    return;

  ash::ReportPrefSortOrderOnSessionStart(client_->GetPermanentSortingOrder(),
                                         IsInTabletMode());

  auto* prefs =
      Shell::Get()->session_controller()->GetUserPrefServiceForUser(account_id);
  if (features::IsLauncherNudgeSessionResetEnabled()) {
    AppListNudgeController::ResetPrefsForNewUserSession(prefs);
  }
}

void AppListControllerImpl::OnSunfishScannerFeatureStatesChanged(
    SunfishScannerFeatureWatcher& source) {
  GetSearchModel()->search_box()->SetSunfishButtonVisibility(
      GetSunfishButtonVisibility(source));
}

////////////////////////////////////////////////////////////////////////////////
// Methods used in Ash

bool AppListControllerImpl::GetTargetVisibility(
    const std::optional<int64_t>& display_id) const {
  return last_target_visible_ &&
         (!display_id.has_value() ||
          display_id.value() == last_target_visible_display_id_);
}

void AppListControllerImpl::Show(int64_t display_id,
                                 AppListShowSource show_source,
                                 base::TimeTicks event_time_stamp,
                                 bool should_record_metrics) {
  if (IsKioskSession())
    return;

  last_open_source_ = show_source;
  if (should_record_metrics)
    LogAppListShowSource(show_source, !IsInTabletMode());

  // Checking `should_record_metrics` is redundant here, since this helper
  // function never logs metrics when the app list was shown by tablet mode.
  MaybeLogWelcomeTourInteraction(show_source);

  if (IsInTabletMode()) {
    fullscreen_presenter_->Show(AppListViewState::kFullscreenAllApps,
                                display_id, event_time_stamp, show_source);
    return;
  }

  bubble_presenter_->Show(display_id);
}

void AppListControllerImpl::UpdateAppListWithNewTemporarySortOrder(
    const std::optional<AppListSortOrder>& new_order,
    bool animate,
    base::OnceClosure update_position_closure) {
  TRACE_EVENT0("ui",
               "AppListControllerImpl::UpdateAppListWithNewTemporarySortOrder");
  if (new_order) {
    RecordAppListSortAction(*new_order, IsInTabletMode());

    FeatureDiscoveryDurationReporter* reporter =
        FeatureDiscoveryDurationReporter::GetInstance();
    reporter->MaybeFinishObservation(feature_discovery::TrackableFeature::
                                         kAppListReorderAfterEducationNudge);
    reporter->MaybeFinishObservation(
        feature_discovery::TrackableFeature::
            kAppListReorderAfterEducationNudgePerTabletMode);
    reporter->MaybeFinishObservation(feature_discovery::TrackableFeature::
                                         kAppListReorderAfterSessionActivation);
  }

  // Adapt the bubble app list to the new sorting order. NOTE: the bubble app
  // list is visible only in clamshell mode. Therefore do not animate in tablet
  // mode.
  const bool is_tablet_mode = IsInTabletMode();
  bubble_presenter_->UpdateForNewSortingOrder(
      new_order, !is_tablet_mode && animate,
      is_tablet_mode ? base::NullCallback()
                     : std::move(update_position_closure));

  // Adapt the fullscreen app list to the new sorting order. NOTE: the full
  // screen app list is visible only in tablet mode. Therefore do not animate in
  // clamshell mode.
  fullscreen_presenter_->UpdateForNewSortingOrder(
      new_order, is_tablet_mode && animate,
      is_tablet_mode ? std::move(update_position_closure)
                     : base::NullCallback());

  // Notify the AppsCollectionsController that there was a reorder.
  apps_collections_controller_->SetAppsReordered();
}

ShelfAction AppListControllerImpl::ToggleAppList(
    int64_t display_id,
    AppListShowSource show_source,
    base::TimeTicks event_time_stamp) {
  if (Shell::Get()->session_controller()->GetSessionState() !=
      session_manager::SessionState::ACTIVE) {
    return SHELF_ACTION_APP_LIST_DISMISSED;
  }

  if (IsKioskSession())
    return SHELF_ACTION_APP_LIST_DISMISSED;

  if (IsInTabletMode()) {
    bool handled = GoHome(display_id);

    // Perform the "back" action for the app list.
    if (!handled) {
      Back();
      return SHELF_ACTION_APP_LIST_BACK;
    }
    LogAppListShowSource(show_source, /*app_list_bubble=*/false);
    last_open_source_ = show_source;

    MaybeLogWelcomeTourInteraction(show_source);

    return SHELF_ACTION_APP_LIST_SHOWN;
  }

  ShelfAction action = bubble_presenter_->Toggle(display_id);
  if (action == SHELF_ACTION_APP_LIST_SHOWN) {
    LogAppListShowSource(show_source, /*app_list_bubble=*/true);
    last_open_source_ = show_source;

    MaybeLogWelcomeTourInteraction(show_source);
  }
  return action;
}

bool AppListControllerImpl::GoHome(int64_t display_id) {
  if (IsKioskSession())
    return false;

  DCHECK(IsInTabletMode());

  if (fullscreen_presenter_->IsShowingEmbeddedAssistantUI()) {
    // OnHomeLauncherAnimationComplete() may not be called if the
    // `foreground_windows` is empty. Call AssistantUiController::CloseUi() here
    // directly.
    AssistantUiController::Get()->CloseUi(AssistantExitPoint::kLauncherClose);
    fullscreen_presenter_->ShowEmbeddedAssistantUI(false);
  }

  SplitViewController* split_view_controller =
      SplitViewController::Get(Shell::GetPrimaryRootWindow());
  const bool split_view_active = split_view_controller->InSplitViewMode();

  // The home screen opens for the current active desk, there's no need to
  // minimize windows in the inactive desks.
  aura::Window::Windows windows =
      Shell::Get()->mru_window_tracker()->BuildWindowForCycleList(kActiveDesk);

  // The foreground window or windows (for split mode) - the windows that will
  // not be minimized without animations (instead they will be animated into the
  // home screen).
  std::vector<raw_ptr<aura::Window, VectorExperimental>> foreground_windows;
  if (split_view_active) {
    foreground_windows = {split_view_controller->primary_window(),
                          split_view_controller->secondary_window()};
    std::erase_if(foreground_windows,
                  [](aura::Window* window) { return !window; });
  } else if (!windows.empty() && !WindowState::Get(windows[0])->IsMinimized()) {
    foreground_windows.push_back(windows[0]);
  }

  OverviewController* overview_controller = Shell::Get()->overview_controller();
  if (split_view_active) {
    // If overview session is active (e.g. on one side of the split view), end
    // it immediately, to prevent overview UI being visible while transitioning
    // to home screen.
    if (overview_controller->InOverviewSession()) {
      overview_controller->EndOverview(OverviewEndAction::kEnterHomeLauncher,
                                       OverviewEnterExitType::kImmediateExit);
    }

    // End split view mode.
    split_view_controller->EndSplitView(
        SplitViewController::EndReason::kHomeLauncherPressed);
  }

  // If overview is active (if overview was active in split view, it exited by
  // this point), just fade it out to home screen.
  if (overview_controller->InOverviewSession()) {
    overview_controller->EndOverview(OverviewEndAction::kEnterHomeLauncher,
                                     OverviewEnterExitType::kFadeOutExit);
    return true;
  }

  // First minimize all inactive windows.
  const bool window_minimized =
      MinimizeAllWindows(windows, foreground_windows /*windows_to_ignore*/);

  if (foreground_windows.empty())
    return window_minimized;

  {
    // Disable window animations before updating home launcher target
    // position. Calling OnHomeLauncherPositionChanged() can cause
    // display work area update, and resulting cross-fade window bounds change
    // animation can interfere with WindowTransformToHomeScreenAnimation
    // visuals.
    //
    // TODO(crbug.com/40656009): This can be removed once transitions
    // between in-app state and home do not cause work area updates.
    std::vector<std::unique_ptr<wm::ScopedAnimationDisabler>>
        animation_disablers;
    for (aura::Window* window : foreground_windows) {
      animation_disablers.push_back(
          std::make_unique<wm::ScopedAnimationDisabler>(window));
    }

    OnHomeLauncherPositionChanged(/*percent_shown=*/100, display_id);
  }

  StartTrackingAnimationSmoothness(display_id);

  base::RepeatingClosure window_transforms_callback = base::BarrierClosure(
      foreground_windows.size(),
      base::BindOnce(&AppListControllerImpl::OnGoHomeWindowAnimationsEnded,
                     weak_ptr_factory_.GetWeakPtr(), display_id));

  // Minimize currently active windows, but this time, using animation.
  // Home screen will show when all the windows are done minimizing.
  for (aura::Window* foreground_window : foreground_windows) {
    if (::wm::WindowAnimationsDisabled(foreground_window)) {
      WindowState::Get(foreground_window)->Minimize();
      window_transforms_callback.Run();
    } else {
      // Create animator observer that will fire |window_transforms_callback|
      // once the window layer stops animating - it deletes itself when
      // animations complete.
      new WindowAnimationsCallback(window_transforms_callback,
                                   foreground_window->layer()->GetAnimator());
      WindowState::Get(foreground_window)->Minimize();
    }
  }

  return true;
}

bool AppListControllerImpl::ShouldHomeLauncherBeVisible() const {
  if (!IsInTabletMode() || IsKioskSession()) {
    return false;
  }

  if (home_launcher_transition_state_ ==
      HomeLauncherTransitionState::kMostlyShown) {
    return true;
  }

  return !Shell::Get()->overview_controller()->InOverviewSession() &&
         !GetTopVisibleWindow();
}

void AppListControllerImpl::OnShelfAlignmentChanged(
    aura::Window* root_window,
    ShelfAlignment old_alignment) {
  if (!IsInTabletMode()) {
    DismissAppList();
  }
}

void AppListControllerImpl::OnShellDestroying() {
  // Stop observing at the beginning of ~Shell to avoid unnecessary work during
  // Shell shutdown.
  Shutdown();
}

void AppListControllerImpl::OnOverviewModeStarting() {
  const OverviewEnterExitType overview_enter_type =
      Shell::Get()
          ->overview_controller()
          ->overview_session()
          ->enter_exit_overview_type();

  const bool animate =
      IsHomeScreenVisible() &&
      overview_enter_type == OverviewEnterExitType::kFadeInEnter;

  UpdateForOverviewModeChange(/*show_home_launcher=*/false, animate);

  if (IsInTabletMode()) {
    const int64_t display_id = last_visible_display_id_;
    OnVisibilityWillChange(false /*shown*/, display_id);
  } else {
    DismissAppList();
  }
}

void AppListControllerImpl::OnOverviewModeStartingAnimationComplete(
    bool canceled) {
  if (!IsInTabletMode()) {
    return;
  }

  // If overview start was canceled, overview end animations are about to start.
  // Preemptively update the target app list visibility.
  if (canceled) {
    OnVisibilityWillChange(!GetTopVisibleWindow(), last_visible_display_id_);
    return;
  }

  OnVisibilityChanged(false /* shown */, last_visible_display_id_);
}

void AppListControllerImpl::OnOverviewModeEnding(OverviewSession* session) {
  // The launcher will be shown after overview mode finishes animating, in
  // OnOverviewModeEndingAnimationComplete(). Overview however is nullptr by
  // the time the animations are finished, so cache the exit type here.
  overview_exit_type_ = std::make_optional(session->enter_exit_overview_type());

  // If the overview is fading out, start the home launcher animation in
  // parallel. Otherwise the transition will be initiated in
  // OnOverviewModeEndingAnimationComplete().
  if (session->enter_exit_overview_type() ==
      OverviewEnterExitType::kFadeOutExit) {
    UpdateForOverviewModeChange(/*show_home_launcher=*/true, /*animate=*/true);

    // Make sure the window visibility is updated, in case it was previously
    // hidden due to overview being shown.
    UpdateHomeScreenVisibility();
  }

  if (!IsInTabletMode()) {
    return;
  }

  // Overview state might end during home launcher transition - if that is the
  // case, respect the final state set by in-progress home launcher transition.
  if (home_launcher_transition_state_ != HomeLauncherTransitionState::kFinished)
    return;

  OnVisibilityWillChange(!GetTopVisibleWindow() /*shown*/,
                         last_visible_display_id_);
}

void AppListControllerImpl::OnOverviewModeEnded() {
  if (!IsInTabletMode()) {
    return;
  }

  // Overview state might end during home launcher transition - if that is the
  // case, respect the final state set by in-progress home launcher transition.
  if (home_launcher_transition_state_ != HomeLauncherTransitionState::kFinished)
    return;
  OnVisibilityChanged(!GetTopVisibleWindow(), last_visible_display_id_);
}

void AppListControllerImpl::OnOverviewModeEndingAnimationComplete(
    bool canceled) {
  DCHECK(overview_exit_type_.has_value());

  // For kFadeOutExit OverviewEnterExitType, the home animation is scheduled in
  // OnOverviewModeEnding(), so there is nothing else to do at this point.
  if (canceled || *overview_exit_type_ == OverviewEnterExitType::kFadeOutExit) {
    overview_exit_type_ = std::nullopt;
    return;
  }

  const bool animate =
      *overview_exit_type_ == OverviewEnterExitType::kFadeOutExit;
  overview_exit_type_ = std::nullopt;

  UpdateForOverviewModeChange(/*show_home_launcher=*/true, animate);

  // Make sure the window visibility is updated, in case it was previously
  // hidden due to overview being shown.
  UpdateHomeScreenVisibility();
}

void AppListControllerImpl::OnSplitViewStateChanged(
    SplitViewController::State previous_state,
    SplitViewController::State state) {
  UpdateHomeScreenVisibility();
}

void AppListControllerImpl::OnChangedToInTabletMode() {
  if (IsKioskSession()) {
    return;
  }

  // Reset the keyboard traversal mode to prevent using the value saved in
  // clamshell mode.
  SetKeyboardTraversalMode(false);

  bubble_presenter_->Dismiss();

  // Show the app list if the tablet mode starts.
  if (Shell::Get()->session_controller()->GetSessionState() ==
      session_manager::SessionState::ACTIVE) {
    ShowHomeScreen(AppListShowSource::kTabletMode);
  }
  UpdateFullscreenLauncherContainer();

  // If the app list is visible before the transition to tablet mode,
  // AppListPresenter relies on the active window change to detect the app list
  // view got hidden behind a window. Though, app list UI moving behind an app
  // window does not always cause an active window change:
  // *   If the app list is still being shown - given that app list takes focus
  //     from the top window only when it's fully shown, the focus will remain
  //     within the app window throughout the tablet mode transition.
  // *   If the assistant UI is visible before the tablet mode transition - the
  //     assistant will keep the focus during transition, even though the app
  //     window will be shown over the app list view.
  // Ensure the app list visibility is properly updated if the app list is
  // hidden behind a window at this point.
  if (last_target_visible_ && !ShouldHomeLauncherBeVisible()) {
    OnVisibilityChanged(false, last_visible_display_id_);
  }
}

void AppListControllerImpl::OnChangedToInClamshellMode() {
  // Reset the keyboard traversal mode to prevent using the value saved last
  // time in tablet mode.
  SetKeyboardTraversalMode(false);

  aura::Window* window = fullscreen_presenter_->GetWindow();
  base::AutoReset<bool> auto_reset(
      &should_dismiss_immediately_,
      window && RootWindowController::ForWindow(window)
                    ->GetShelfLayoutManager()
                    ->HasVisibleWindow());
  UpdateFullscreenLauncherContainer();

  // Dismiss the app list if the tablet mode ends.
  DismissAppList();
}

void AppListControllerImpl::OnDisplayTabletStateChanged(
    display::TabletState state) {
  switch (state) {
    case display::TabletState::kEnteringTabletMode:
    case display::TabletState::kExitingTabletMode:
      // Do nothing when the tablet state is still in the process of transition.
      break;
    case display::TabletState::kInTabletMode:
      OnChangedToInTabletMode();
      break;
    case display::TabletState::kInClamshellMode:
      OnChangedToInClamshellMode();
      break;
  }
}

void AppListControllerImpl::OnWallpaperPreviewStarted() {
  in_wallpaper_preview_ = true;
  UpdateHomeScreenVisibility();
}

void AppListControllerImpl::OnWallpaperPreviewEnded() {
  in_wallpaper_preview_ = false;
  UpdateHomeScreenVisibility();
}

void AppListControllerImpl::OnKeyboardVisibilityChanged(const bool is_visible) {
  onscreen_keyboard_shown_ = is_visible;
  AppListView* app_list_view = fullscreen_presenter_->GetView();
  if (app_list_view)
    app_list_view->OnScreenKeyboardShown(is_visible);
}

void AppListControllerImpl::OnAssistantStatusChanged(
    assistant::AssistantStatus status) {
  UpdateSearchBoxUiVisibilities();
}

void AppListControllerImpl::OnAssistantSettingsEnabled(bool enabled) {
  UpdateSearchBoxUiVisibilities();
}

void AppListControllerImpl::OnAssistantFeatureAllowedChanged(
    assistant::AssistantAllowedState state) {
  UpdateSearchBoxUiVisibilities();
}

void AppListControllerImpl::OnDidApplyDisplayChanges() {
  // Entering tablet mode triggers a display configuration change when we
  // automatically switch to mirror mode. Switching to mirror mode happens
  // asynchronously (see DisplayConfigurationObserver::OnTabletModeStarted()).
  // This may result in the removal of a window tree host, as in the example of
  // switching to tablet mode while Unified Desktop mode is on; the Unified host
  // will be destroyed and the Home Launcher (which was created earlier when we
  // entered tablet mode) will be dismissed.
  // To avoid crashes, we must ensure that the Home Launcher shown status is as
  // expected if it's enabled and we're still in tablet mode.
  // https://crbug.com/900956.
  const bool should_be_shown =
      IsInTabletMode() &&
      Shell::Get()->session_controller()->GetSessionState() ==
          session_manager::SessionState::ACTIVE;

  if (!should_be_shown ||
      should_be_shown == fullscreen_presenter_->GetTargetVisibility()) {
    return;
  }
  ShowHomeScreen(AppListShowSource::kTabletMode);
}

void AppListControllerImpl::OnAssistantReady() {
  UpdateSearchBoxUiVisibilities();
}

void AppListControllerImpl::OnUiVisibilityChanged(
    AssistantVisibility new_visibility,
    AssistantVisibility old_visibility,
    std::optional<AssistantEntryPoint> entry_point,
    std::optional<AssistantExitPoint> exit_point) {
  const bool is_old_visibility_closing =
      (old_visibility == AssistantVisibility::kClosing);

  switch (new_visibility) {
    case AssistantVisibility::kVisible:
      DVLOG(1) << "Assistant becoming visible";
      if (!IsVisible() || is_old_visibility_closing) {
        std::optional<AppListView::ScopedContentsResetDisabler> disabler;
        if (is_old_visibility_closing) {
          // Avoid resetting the contents view when the transition to close the
          // Assistant ui is going to be reversed.
          if (fullscreen_presenter_->GetView())
            disabler.emplace(fullscreen_presenter_->GetView());

          // Reset `close_assistant_ui_runner_` because the Assistant ui is
          // going to show.
          DCHECK(close_assistant_ui_runner_);
          IgnoreResult(close_assistant_ui_runner_.Release());
        }

        Show(GetDisplayIdToShowAppListOn(),
             AppListShowSource::kAssistantEntryPoint, base::TimeTicks(),
             /*should_record_metrics=*/true);
      }
      if (!IsInTabletMode()) {
        bubble_presenter_->ShowEmbeddedAssistantUI();
      } else {
        if (!fullscreen_presenter_->IsShowingEmbeddedAssistantUI() ||
            is_old_visibility_closing) {
          fullscreen_presenter_->ShowEmbeddedAssistantUI(true);
        }

        // Make sure that app list views are visible - they might get hidden
        // during session startup, and the app list visibility might not have
        // yet changed to visible by this point. https://crbug.com/1040751
        fullscreen_presenter_->SetViewVisibility(true);
      }
      break;
    case AssistantVisibility::kClosed:
      if (!IsShowingEmbeddedAssistantUI())
        break;

      // When Launcher is closing, we do not want to call
      // |ShowEmbeddedAssistantUI(false)|, which will show previous state page
      // in Launcher and make the UI flash.
      if (IsInTabletMode()) {
        std::optional<ContentsView::ScopedSetActiveStateAnimationDisabler>
            set_active_state_animation_disabler;
        // When taking a screenshot by Assistant, we do not want to animate to
        // the final state. Otherwise the screenshot may have transient state
        // during the animation. In tablet mode, we want to go back to
        // kStateApps immediately, i.e. skipping the animation in
        // |SetActiveStateInternal|, which are called from
        // |ShowEmbeddedAssistantUI(false)| and
        // |ClearSearchAndDeactivateSearchBox()|.
        if (IsAssistantExitPointScreenshot(exit_point)) {
          set_active_state_animation_disabler.emplace(
              fullscreen_presenter_->GetView()
                  ->app_list_main_view()
                  ->contents_view());
        }

        fullscreen_presenter_->ShowEmbeddedAssistantUI(false);

        if (!IsAssistantExitPointInsideLauncher(exit_point)) {
          fullscreen_presenter_->GetView()
              ->search_box_view()
              ->ClearSearchAndDeactivateSearchBox();
        }
      } else if (!IsAssistantExitPointInsideLauncher(exit_point)) {
        // Similarly, when taking a screenshot by Assistant in clamshell mode,
        // we do not want to dismiss launcher with animation. Otherwise the
        // screenshot may have transient state during the animation.
        base::AutoReset<bool> auto_reset(
            &should_dismiss_immediately_,
            IsAssistantExitPointScreenshot(exit_point));
        DismissAppList();
      }
      break;
    case AssistantVisibility::kClosing:
      break;
  }
}

void AppListControllerImpl::OnHomeLauncherAnimationComplete(
    bool shown,
    int64_t display_id) {
  home_launcher_transition_state_ = HomeLauncherTransitionState::kFinished;

  AssistantUiController::Get()->CloseUi(
      shown ? AssistantExitPoint::kLauncherOpen
            : AssistantExitPoint::kLauncherClose);

  // Animations can be reversed (e.g. in a drag). Let's ensure the target
  // visibility is correct first.
  OnVisibilityChanged(shown, display_id);
}

void AppListControllerImpl::OnHomeLauncherPositionChanged(int percent_shown,
                                                          int64_t display_id) {
  const bool mostly_shown = percent_shown >= 50;
  home_launcher_transition_state_ =
      mostly_shown ? HomeLauncherTransitionState::kMostlyShown
                   : HomeLauncherTransitionState::kMostlyHidden;
  OnVisibilityWillChange(mostly_shown, display_id);
}

aura::Window* AppListControllerImpl::GetHomeScreenWindow() const {
  return fullscreen_presenter_->GetWindow();
}

void AppListControllerImpl::UpdateScaleAndOpacityForHomeLauncher(
    float scale,
    float opacity,
    std::optional<HomeLauncherAnimationInfo> animation_info,
    UpdateAnimationSettingsCallback callback) {
  DCHECK(!animation_info.has_value() || !callback.is_null());

  fullscreen_presenter_->UpdateScaleAndOpacityForHomeLauncher(
      scale, opacity,
      GetTransitionFromMetricsAnimationInfo(std::move(animation_info)),
      std::move(callback));
}

void AppListControllerImpl::Back() {
  fullscreen_presenter_->GetView()->Back();
}

void AppListControllerImpl::SetKeyboardTraversalMode(bool engaged) {
  if (keyboard_traversal_engaged_ == engaged)
    return;

  keyboard_traversal_engaged_ = engaged;
  AssistantUiController::Get()->SetKeyboardTraversalMode(engaged);

  // No need to schedule paint for bubble presenter.
  if (bubble_presenter_->IsShowing())
    return;

  AppListView* app_list_view = fullscreen_presenter_->GetView();
  // May be null in tests of bubble presenter.
  if (!app_list_view)
    return;
  views::View* focused_view =
      app_list_view->GetFocusManager()->GetFocusedView();

  if (!focused_view)
    return;

  // When the search box has focus, it is actually the textfield that has focus.
  // As such, the |SearchBoxView| must be told to repaint directly.
  if (focused_view == app_list_view->search_box_view()->search_box()) {
    app_list_view->search_box_view()->UpdateSearchBoxFocusPaint();
  } else if (AppListToastView::IsToastButton(focused_view)) {
    // Toast button can become focused after app list sorting, so make sure the
    // focus ring appears correctly when updating `keyboard_traversal_engaged_`.
    focused_view->SchedulePaint();
  } else {
    // Ensure that when an app list item's focus ring is triggered by key
    // events, the item is selected.
    // TODO(https://crbug.com/1262236): class name comparision and static cast
    // should be avoided in the production code. Find a better way to guarantee
    // the item's selection status.
    if (focused_view->GetClassName() == AppListItemView::kViewClassName) {
      static_cast<AppListItemView*>(focused_view)->EnsureSelected();
    }

    focused_view->SchedulePaint();
  }
}

bool AppListControllerImpl::IsShowingEmbeddedAssistantUI() const {
  return bubble_presenter_->IsShowingEmbeddedAssistantUI() ||
         fullscreen_presenter_->IsShowingEmbeddedAssistantUI();
}

void AppListControllerImpl::SetStateTransitionAnimationCallbackForTesting(
    StateTransitionAnimationCallback callback) {
  state_transition_animation_callback_ = std::move(callback);
}

void AppListControllerImpl::SetHomeLauncherAnimationCallbackForTesting(
    HomeLauncherAnimationCallback callback) {
  home_launcher_animation_callback_ = std::move(callback);
}

void AppListControllerImpl::RecordShelfAppLaunched() {
  RecordAppListAppLaunched(
      AppListLaunchedFrom::kLaunchedFromShelf,
      recorded_app_list_view_state_.value_or(GetAppListViewState()),
      IsInTabletMode(), recorded_app_list_visibility_.value_or(last_visible_));
  recorded_app_list_view_state_ = std::nullopt;
  recorded_app_list_visibility_ = std::nullopt;
}

////////////////////////////////////////////////////////////////////////////////
// Methods of |client_|:

void AppListControllerImpl::StartAssistant(
    assistant::AssistantEntryPoint entry_point) {
  AssistantUiController::Get()->ShowUi(entry_point);
  UpdateSearchBoxUiVisibilities();
}

void AppListControllerImpl::EndAssistant(
    assistant::AssistantExitPoint exit_point) {
  AssistantUiController::Get()->CloseUi(exit_point);
}

std::vector<AppListSearchControlCategory>
AppListControllerImpl::GetToggleableCategories() const {
  if (client_) {
    return client_->GetToggleableCategories();
  }
  return std::vector<AppListSearchControlCategory>();
}

void AppListControllerImpl::StartSearch(const std::u16string& raw_query) {
  if (client_) {
    std::u16string query;
    base::TrimWhitespace(raw_query, base::TRIM_ALL, &query);
    client_->StartSearch(query);
  }
}

void AppListControllerImpl::StartZeroStateSearch(base::OnceClosure callback,
                                                 base::TimeDelta timeout) {
  if (client_)
    client_->StartZeroStateSearch(std::move(callback), timeout);
}

void AppListControllerImpl::OpenSearchResult(const std::string& result_id,
                                             int event_flags,
                                             AppListLaunchedFrom launched_from,
                                             AppListLaunchType launch_type,
                                             int suggestion_index,
                                             bool launch_as_default) {
  SearchModel* search_model = GetSearchModel();
  SearchResult* result = search_model->FindSearchResult(result_id);
  if (!result)
    return;

  if (launch_type == AppListLaunchType::kAppSearchResult) {
    switch (launched_from) {
      case AppListLaunchedFrom::kLaunchedFromSearchBox:
      case AppListLaunchedFrom::kLaunchedFromRecentApps:
        RecordAppLaunched(launched_from);
        break;
      case AppListLaunchedFrom::kLaunchedFromGrid:
      case AppListLaunchedFrom::kLaunchedFromShelf:
      case AppListLaunchedFrom::kLaunchedFromContinueTask:
      case AppListLaunchedFrom::kLaunchedFromQuickAppAccess:
      case AppListLaunchedFrom::kLaunchedFromAppsCollections:
      case AppListLaunchedFrom::kLaunchedFromDiscoveryChip:
      case AppListLaunchedFrom::kLaunchedFromSearchBoxIcon:
        break;
      case AppListLaunchedFrom::DEPRECATED_kLaunchedFromSuggestionChip:
        NOTREACHED();
    }
  }

  const bool is_tablet_mode = IsInTabletMode();
  switch (launched_from) {
    case AppListLaunchedFrom::kLaunchedFromSearchBox:
      switch (launch_type) {
        case AppListLaunchType::kSearchResult:
          RecordLauncherWorkflowMetrics(AppListUserAction::kOpenSearchResult,
                                        is_tablet_mode, last_show_timestamp_);
          break;
        case AppListLaunchType::kAppSearchResult:
          RecordLauncherWorkflowMetrics(AppListUserAction::kOpenAppSearchResult,
                                        is_tablet_mode, last_show_timestamp_);
          break;
        case AppListLaunchType::kApp:
          NOTREACHED();
      }
      break;
    case AppListLaunchedFrom::kLaunchedFromContinueTask:
      RecordLauncherWorkflowMetrics(AppListUserAction::kOpenContinueSectionTask,
                                    is_tablet_mode, last_show_timestamp_);
      break;
    case AppListLaunchedFrom::kLaunchedFromGrid:
    case AppListLaunchedFrom::kLaunchedFromRecentApps:
    case AppListLaunchedFrom::kLaunchedFromShelf:
    case AppListLaunchedFrom::DEPRECATED_kLaunchedFromSuggestionChip:
    case AppListLaunchedFrom::kLaunchedFromQuickAppAccess:
    case AppListLaunchedFrom::kLaunchedFromAppsCollections:
    case AppListLaunchedFrom::kLaunchedFromDiscoveryChip:
    case AppListLaunchedFrom::kLaunchedFromSearchBoxIcon:
      NOTREACHED();
  }

  base::RecordAction(base::UserMetricsAction("AppList_OpenSearchResult"));

  if (client_) {
    client_->OpenSearchResult(profile_id_, result_id, event_flags,
                              launched_from, launch_type, suggestion_index,
                              launch_as_default);
  }

  ResetHomeLauncherIfShown();
}

void AppListControllerImpl::InvokeSearchResultAction(
    const std::string& result_id,
    SearchResultActionType action) {
  if (client_)
    client_->InvokeSearchResultAction(result_id, action);
}

void AppListControllerImpl::ViewShown(int64_t display_id) {
  UpdateSearchBoxUiVisibilities();

  // Note that IsHomeScreenVisible() might still return false at this point, as
  // the home screen visibility takes into account whether the app list view is
  // obscured by an app window, or overview UI. This method gets called when the
  // app list view widget visibility changes (regardless of whether anything is
  // stacked above the home screen).
  aura::Window* window = GetHomeScreenWindow();
  split_view_observation_.Observe(SplitViewController::Get(window));
  UpdateHomeScreenVisibility();

  // Ensure search box starts fresh with no ring each time it opens.
  keyboard_traversal_engaged_ = false;
}

bool AppListControllerImpl::AppListTargetVisibility() const {
  return last_target_visible_;
}

void AppListControllerImpl::ViewClosing() {
  split_view_observation_.Reset();
}

void AppListControllerImpl::ActivateItem(const std::string& id,
                                         int event_flags,
                                         AppListLaunchedFrom launched_from,
                                         bool is_app_above_the_fold) {
  RecordAppLaunched(launched_from);

  const bool is_tablet_mode = IsInTabletMode();
  switch (launched_from) {
    case AppListLaunchedFrom::kLaunchedFromGrid:
      RecordLauncherWorkflowMetrics(AppListUserAction::kAppLaunchFromAppsGrid,
                                    is_tablet_mode, last_show_timestamp_);
      break;
    case AppListLaunchedFrom::kLaunchedFromRecentApps:
      RecordLauncherWorkflowMetrics(AppListUserAction::kAppLaunchFromRecentApps,
                                    is_tablet_mode, last_show_timestamp_);
      break;
    case AppListLaunchedFrom::kLaunchedFromQuickAppAccess:
    // Metrics for quick app launch already recorded at RecordApplaunched().
    case AppListLaunchedFrom::kLaunchedFromAppsCollections:
    // Metrics for apps collections launch recorded by the
    // AppListViewDelegate.
    case AppListLaunchedFrom::kLaunchedFromDiscoveryChip:
      // Metrics for discovery chip already recorded at RecordApplaunched().
      break;
    case AppListLaunchedFrom::kLaunchedFromSearchBoxIcon:
      // Metrics for launching an app from an icon in search box is recorded via
      // `Apps.AppList.GeminiSearchBoxIcon`. This is currently used only for a
      // Gemini icon.
      break;
    case AppListLaunchedFrom::kLaunchedFromSearchBox:
    case AppListLaunchedFrom::kLaunchedFromContinueTask:
    case AppListLaunchedFrom::kLaunchedFromShelf:
    case AppListLaunchedFrom::DEPRECATED_kLaunchedFromSuggestionChip:
      NOTREACHED();
  }

  if (client_)
    client_->ActivateItem(profile_id_, id, event_flags, launched_from,
                          is_app_above_the_fold);

  ResetHomeLauncherIfShown();
}

void AppListControllerImpl::GetContextMenuModel(
    const std::string& id,
    AppListItemContext item_context,
    GetContextMenuModelCallback callback) {
  if (client_)
    client_->GetContextMenuModel(profile_id_, id, item_context,
                                 std::move(callback));
}

void AppListControllerImpl::ShowWallpaperContextMenu(
    const gfx::Point& onscreen_location,
    ui::mojom::MenuSourceType source_type) {
  Shell::Get()->ShowContextMenu(onscreen_location, source_type);
}

bool AppListControllerImpl::KeyboardTraversalEngaged() {
  return keyboard_traversal_engaged_;
}

bool AppListControllerImpl::CanProcessEventsOnApplistViews() {
  // Do not allow processing events during overview or while overview is
  // finished but still animating out.
  OverviewController* overview_controller = Shell::Get()->overview_controller();
  if (overview_controller->InOverviewSession() ||
      overview_controller->IsCompletingShutdownAnimations()) {
    return false;
  }

  return true;
}

bool AppListControllerImpl::ShouldDismissImmediately() {
  return should_dismiss_immediately_;
}

AssistantViewDelegate* AppListControllerImpl::GetAssistantViewDelegate() {
  return Shell::Get()->assistant_controller()->view_delegate();
}

void AppListControllerImpl::OnSearchResultVisibilityChanged(
    const std::string& id,
    bool visibility) {
  if (client_)
    client_->OnSearchResultVisibilityChanged(id, visibility);
}

bool AppListControllerImpl::IsAssistantAllowedAndEnabled() const {
  if (!Shell::Get()->assistant_controller()->IsAssistantReady())
    return false;

  auto* state = AssistantState::Get();
  return state->settings_enabled().value_or(false) &&
         state->allowed_state() == assistant::AssistantAllowedState::ALLOWED &&
         state->assistant_status() != assistant::AssistantStatus::NOT_READY;
}

void AppListControllerImpl::OnStateTransitionAnimationCompleted(
    AppListViewState state,
    bool was_animation_interrupted) {
  if (!was_animation_interrupted &&
      !state_transition_animation_callback_.is_null()) {
    state_transition_animation_callback_.Run(state);
  }

  MaybeCloseAssistant();
}

void AppListControllerImpl::MaybeCloseAssistant() {
  if (close_assistant_ui_runner_)
    close_assistant_ui_runner_.RunAndReset();
}

AppListViewState AppListControllerImpl::GetAppListViewState() const {
  return app_list_view_state_;
}

void AppListControllerImpl::OnViewStateChanged(AppListViewState state) {
  DVLOG(1) << __PRETTY_FUNCTION__ << " " << state;
  app_list_view_state_ = state;

  for (auto& observer : observers_)
    observer.OnViewStateChanged(state);

  if (state == AppListViewState::kClosed)
    ScheduleCloseAssistant();
}

void AppListControllerImpl::ScheduleCloseAssistant() {
  DVLOG(1) << __PRETTY_FUNCTION__;
  // Close the Assistant in asynchronous way if the app list is going to be
  // closed while the Assistant is visible. If the app list close animation is
  // not reversed, `close_assistant_ui_runner_` runs at the end of the animation
  // to actually close the Assistant.
  const bool is_assistant_ui_visible =
      (AssistantUiController::Get()->GetModel()->visibility() ==
       AssistantVisibility::kVisible);
  if (is_assistant_ui_visible) {
    std::optional<base::ScopedClosureRunner> runner =
        AssistantUiController::Get()->CloseUi(
            AssistantExitPoint::kLauncherClose);
    DCHECK(runner);
    DCHECK(!close_assistant_ui_runner_);
    close_assistant_ui_runner_.ReplaceClosure(runner->Release());
  }
}

void AppListControllerImpl::LoadIcon(const std::string& app_id) {
  if (client_)
    client_->LoadIcon(profile_id_, app_id);
}

bool AppListControllerImpl::HasValidProfile() const {
  return profile_id_ != kAppListInvalidProfileID;
}

bool AppListControllerImpl::ShouldHideContinueSection() const {
  PrefService* prefs = GetLastActiveUserPrefService();
  return prefs->GetBoolean(prefs::kLauncherContinueSectionHidden);
}

void AppListControllerImpl::SetHideContinueSection(bool hide) {
  PrefService* prefs = GetLastActiveUserPrefService();
  bool is_hidden = prefs->GetBoolean(prefs::kLauncherContinueSectionHidden);
  if (hide == is_hidden)
    return;
  prefs->SetBoolean(prefs::kLauncherContinueSectionHidden, hide);
  fullscreen_presenter_->UpdateContinueSectionVisibility();
  bubble_presenter_->UpdateContinueSectionVisibility();
}

bool AppListControllerImpl::IsCategoryEnabled(
    AppListSearchControlCategory category) {
  PrefService* prefs =
      Shell::Get()->session_controller()->GetLastActiveUserPrefService();
  return prefs->GetDict(prefs::kLauncherSearchCategoryControlStatus)
      .FindBool(GetAppListControlCategoryName(category))
      .value_or(true);
}

void AppListControllerImpl::SetCategoryEnabled(
    AppListSearchControlCategory category,
    bool enabled) {
  PrefService* prefs =
      Shell::Get()->session_controller()->GetLastActiveUserPrefService();
  ScopedDictPrefUpdate pref_update(prefs,
                                   prefs::kLauncherSearchCategoryControlStatus);
  pref_update->Set(GetAppListControlCategoryName(category), enabled);
}

void AppListControllerImpl::RecordAppsDefaultVisibility(
    const std::vector<std::string>& apps_above_the_fold,
    const std::vector<std::string>& apps_below_the_fold,
    bool is_apps_collections_page) {
  if (client_) {
    client_->RecordAppsDefaultVisibility(
        apps_above_the_fold, apps_below_the_fold, is_apps_collections_page);
  }
}

void AppListControllerImpl::GetAppLaunchedMetricParams(
    AppLaunchedMetricParams* metric_params) {
  metric_params->app_list_view_state = GetAppListViewState();
  metric_params->is_tablet_mode = IsInTabletMode();
  metric_params->app_list_shown = last_visible_;
  metric_params->launcher_show_timestamp = last_show_timestamp_;
}

gfx::Rect AppListControllerImpl::SnapBoundsToDisplayEdge(
    const gfx::Rect& bounds) {
  AppListView* app_list_view = fullscreen_presenter_->GetView();
  DCHECK(app_list_view && app_list_view->GetWidget());
  aura::Window* window = app_list_view->GetWidget()->GetNativeView();
  return screen_util::SnapBoundsToDisplayEdge(bounds, window);
}

AppListState AppListControllerImpl::GetCurrentAppListPage() const {
  return app_list_page_;
}

void AppListControllerImpl::OnAppListPageChanged(AppListState page) {
  const AppListState old_page = app_list_page_;
  if (old_page == page)
    return;

  app_list_page_ = page;

  if (!fullscreen_presenter_)
    return;

  UpdateFullscreenLauncherContainer();

  if (page == AppListState::kStateEmbeddedAssistant) {
    // ShowUi() will be no-op if the Assistant UI is already visible.
    AssistantUiController::Get()->ShowUi(AssistantEntryPoint::kUnspecified);
    return;
  }

  if (old_page == AppListState::kStateEmbeddedAssistant) {
    // CloseUi() will be no-op if the Assistant UI is already closed.
    AssistantUiController::Get()->CloseUi(AssistantExitPoint::kBackInLauncher);
  }
}

int AppListControllerImpl::GetShelfSize() {
  return ShelfConfig::Get()->GetSystemShelfSizeInTabletMode();
}

int AppListControllerImpl::GetSystemShelfInsetsInTabletMode() {
  return ShelfConfig::Get()->GetTabletModeShelfInsetsAndRecordUMA();
}

bool AppListControllerImpl::IsInTabletMode() const {
  return display::Screen::GetScreen()->InTabletMode();
}

void AppListControllerImpl::RecordAppLaunched(
    AppListLaunchedFrom launched_from) {
  RecordAppListAppLaunched(launched_from, GetAppListViewState(),
                           IsInTabletMode(), last_visible_);
}

void AppListControllerImpl::AddObserver(AppListControllerObserver* observer) {
  observers_.AddObserver(observer);
}

void AppListControllerImpl::RemoveObserver(
    AppListControllerObserver* observer) {
  observers_.RemoveObserver(observer);
}

void AppListControllerImpl::OnVisibilityChanged(bool visible,
                                                int64_t display_id) {
  // In the Kiosk session we should never show the app list.
  CHECK(!visible || !IsKioskSession());

  if (client_) {
    client_->RecalculateWouldTriggerLauncherSearchIph();
  }

  DVLOG(1) << __PRETTY_FUNCTION__ << " visible " << visible << " display_id "
           << display_id;
  // Focus and app visibility changes while finishing home launcher state
  // animation may cause OnVisibilityChanged() to be called before the home
  // launcher state transition finished - delay the visibility change until
  // the home launcher stops animating, so observers do not miss the animation
  // state update.
  if (home_launcher_transition_state_ !=
      HomeLauncherTransitionState::kFinished) {
    OnVisibilityWillChange(visible, display_id);
    return;
  }

  bool real_visibility = visible;
  // HomeLauncher is only visible when no other app windows are visible,
  // unless we are in the process of animating to (or dragging) the home
  // launcher.
  if (IsInTabletMode()) {
    UpdateTrackedAppWindow();

    if (tracked_app_window_)
      real_visibility = false;

    // When transitioning to/from overview, ensure the AppList window is not in
    // the process of being hidden.
    aura::Window* app_list_window = GetWindow();
    real_visibility &= app_list_window && app_list_window->TargetVisibility();
  }

  OnVisibilityWillChange(real_visibility, display_id);

  // Skip adjacent same changes.
  if (last_visible_ == real_visibility &&
      last_visible_display_id_ == display_id) {
    return;
  }

  last_visible_display_id_ = display_id;

  if (visible)
    last_show_timestamp_ = base::TimeTicks::Now();

  AppListView* const app_list_view = fullscreen_presenter_->GetView();
  if (app_list_view) {
    app_list_view->UpdatePageResetTimer(real_visibility);

    if (!real_visibility) {
      app_list_view->search_box_view()->ClearSearchAndDeactivateSearchBox();
      // Reset the app list contents state, so the app list is in initial state
      // when the app list visibility changes again.
      app_list_view->app_list_main_view()->contents_view()->ResetForShow();
    }
  }

  // Notify chrome of visibility changes.
  if (last_visible_ != real_visibility) {
    // When showing the launcher with the virtual keyboard enabled, one
    // feature called "transient blur" (which means that if focus was lost but
    // regained a few seconds later, we would show the virtual keyboard again)
    // may show the virtual keyboard, which is not what we want. So hide the
    // virtual keyboard explicitly when the launcher shows.
    if (real_visibility)
      keyboard::KeyboardUIController::Get()->HideKeyboardExplicitlyBySystem();

    if (client_)
      client_->OnAppListVisibilityChanged(real_visibility);

    last_visible_ = real_visibility;

    // Updates AppsContainerView in `fullscreen_presenter_`.
    if (app_list_view) {
      app_list_view->OnAppListVisibilityChanged(real_visibility);

      // Only handle the tablet mode visibility changes, and let clamshell mode
      // handle the nudge and button visibility metrics separately.
      if (real_visibility && IsInTabletMode()) {
        views::ImageButton* sunfish_button =
            app_list_view->search_box_view()->sunfish_button();
        // `sunfish_button` is always initialised in `SearchBoxView`'s
        // constructor.
        CHECK(sunfish_button);
        MaybeShowSunfishLauncherNudge(sunfish_button);
      }
    }

    for (auto& observer : observers_)
      observer.OnAppListVisibilityChanged(real_visibility, display_id);

    if (real_visibility) {
      // Record whether the continue section is hidden by the user.
      RecordHideContinueSectionMetric();

      SearchBoxModel::SunfishButtonVisibility visibility =
          GetSearchModel()->search_box()->sunfish_button_visibility();
      RecordSunfishSessionButtonVisibilityOnLauncherShown(
          /*is_visible=*/visibility !=
          SearchBoxModel::SunfishButtonVisibility::kHidden);
    }

    if (!home_launcher_animation_callback_.is_null())
      home_launcher_animation_callback_.Run(real_visibility);
  }
}

void AppListControllerImpl::OnWindowVisibilityChanging(aura::Window* window,
                                                       bool visible) {
  if (visible || window != tracked_app_window_)
    return;

  UpdateTrackedAppWindow();

  if (!tracked_app_window_ && ShouldHomeLauncherBeVisible())
    OnVisibilityChanged(true, last_visible_display_id_);
}

void AppListControllerImpl::OnWindowDestroyed(aura::Window* window) {
  if (window != tracked_app_window_)
    return;

  tracked_app_window_ = nullptr;
}

void AppListControllerImpl::OnVisibilityWillChange(bool visible,
                                                   int64_t display_id) {
  // In the Kiosk session we should never show the app list.
  CHECK(!visible || !IsKioskSession());

  bool real_target_visibility = visible;
  // HomeLauncher is only visible when no other app windows are visible,
  // unless we are in the process of animating to (or dragging) the home
  // launcher.
  if (IsInTabletMode() && home_launcher_transition_state_ ==
                              HomeLauncherTransitionState::kFinished) {
    real_target_visibility &= !GetTopVisibleWindow();
  }

  // Skip adjacent same changes.
  if (last_target_visible_ == real_target_visibility &&
      last_target_visible_display_id_ == display_id) {
    return;
  }

  // Notify chrome of target visibility changes.
  if (last_target_visible_ != real_target_visibility) {
    last_target_visible_ = real_target_visibility;
    last_target_visible_display_id_ = display_id;

    if (real_target_visibility && fullscreen_presenter_->GetView())
      fullscreen_presenter_->SetViewVisibility(true);

    if (client_)
      client_->OnAppListVisibilityWillChange(real_target_visibility);

    for (auto& observer : observers_) {
      observer.OnAppListVisibilityWillChange(real_target_visibility,
                                             display_id);
    }

    if (real_target_visibility) {
      // The virtual keyboard should be hidden before the bubble launcher
      // calculating the work area.
      keyboard::KeyboardUIController::Get()->HideKeyboardExplicitlyBySystem();

      // Recalculate the Sunfish-session button visibility every time the
      // launcher will be shown, as there are too many variables that can
      // control it and not all of them can be observed for changes.
      sunfish_scanner_feature_observation_.GetSource()->UpdateFeatureStates();
    }
  }
}

////////////////////////////////////////////////////////////////////////////////
// Private used only:

AppListModel* AppListControllerImpl::GetModel() {
  return model_provider_->model();
}

SearchModel* AppListControllerImpl::GetSearchModel() {
  return model_provider_->search_model();
}

void AppListControllerImpl::UpdateSearchBoxUiVisibilities() {
  OnSunfishScannerFeatureStatesChanged(
      *sunfish_scanner_feature_observation_.GetSource());

  // Hide Gemini button first until we are sure that Gemini app list item
  // exists.
  HideGeminiButton();

  if (!client_) {
    return;
  }

  client_->RecalculateWouldTriggerLauncherSearchIph();

  // Gemini app icon is loaded via `client_` for a dependency reason. This must
  // be after `client_` non-nullptr check.
  gemini_app_waiter_.emplace(
      Shell::Get()->session_controller()->GetActiveAccountId(),
      base::BindOnce(&AppListControllerImpl::ShowGeminiButton,
                     base::Unretained(this)),
      kGeminiAppId);
}

int64_t AppListControllerImpl::GetDisplayIdToShowAppListOn() {
  if (IsInTabletMode() && !Shell::Get()->display_manager()->IsInUnifiedMode()) {
    return display::HasInternalDisplay()
               ? display::Display::InternalDisplayId()
               : display::Screen::GetScreen()->GetPrimaryDisplay().id();
  }

  return display::Screen::GetScreen()
      ->GetDisplayNearestWindow(Shell::GetRootWindowForNewWindows())
      .id();
}

void AppListControllerImpl::ResetHomeLauncherIfShown() {
  if (!IsInTabletMode() || !fullscreen_presenter_->IsVisibleDeprecated()) {
    return;
  }

  auto* const keyboard_controller = keyboard::KeyboardUIController::Get();
  if (keyboard_controller->IsKeyboardVisible())
    keyboard_controller->HideKeyboardByUser();
  fullscreen_presenter_->GetView()->CloseOpenedPage();

  // Refresh the suggestion chips with empty query.
  // TODO(crbug.com/40204937): Switch to client_->StartZeroStateSearch()?
  StartSearch(std::u16string());
}

void AppListControllerImpl::ShowHomeScreen(AppListShowSource show_source) {
  DCHECK(IsInTabletMode());

  if (!Shell::Get()->session_controller()->IsActiveUserSessionStarted() ||
      IsKioskSession())
    return;

  // App list is only considered shown for metrics if there are currently no
  // other visible windows shown over the app list after the tablet
  // transition.
  bool should_record_metrics = !GetTopVisibleWindow();

  Show(GetDisplayIdToShowAppListOn(), show_source, base::TimeTicks(),
       should_record_metrics);
  UpdateHomeScreenVisibility();

  aura::Window* window = GetHomeScreenWindow();
  if (window)
    Shelf::ForWindow(window)->MaybeUpdateShelfBackground();
  last_open_source_ = show_source;
}

void AppListControllerImpl::UpdateHomeScreenVisibility() {
  if (!IsInTabletMode()) {
    return;
  }

  aura::Window* window = GetHomeScreenWindow();
  if (!window)
    return;

  if (ShouldShowHomeScreen())
    window->Show();
  else
    window->Hide();
}

bool AppListControllerImpl::ShouldShowHomeScreen() const {
  if (IsKioskSession() || in_window_dragging_ || in_wallpaper_preview_)
    return false;

  aura::Window* window = GetHomeScreenWindow();
  if (!window)
    return false;

  if (!IsInTabletMode()) {
    return false;
  }
  if (Shell::Get()->overview_controller()->InOverviewSession()) {
    return false;
  }

  return !SplitViewController::Get(window)->InSplitViewMode();
}

void AppListControllerImpl::UpdateForOverviewModeChange(bool show_home_launcher,
                                                        bool animate) {
  // Force the home view into the expected initial state without animation,
  // except when transitioning out from home launcher. Gesture handling for
  // the gesture to move to overview can update the scale before triggering
  // transition to overview - undoing these changes here would make the UI
  // jump during the transition.
  if (animate && show_home_launcher) {
    UpdateScaleAndOpacityForHomeLauncher(kOverviewFadeAnimationScale,
                                         /*opacity=*/0.0f,
                                         /*animation_info=*/std::nullopt,
                                         /*callback=*/base::NullCallback());
  }

  // Hide all transient child windows in the app list (e.g. uninstall dialog)
  // before starting the overview mode transition, and restore them when
  // reshowing the app list.
  aura::Window* app_list_window =
      Shell::Get()->app_list_controller()->GetHomeScreenWindow();
  if (app_list_window) {
    for (aura::Window* child : wm::GetTransientChildren(app_list_window)) {
      if (show_home_launcher)
        child->Show();
      else
        child->Hide();
    }
  }

  std::optional<HomeLauncherAnimationInfo> animation_info =
      animate ? std::make_optional<HomeLauncherAnimationInfo>(
                    HomeLauncherAnimationTrigger::kOverviewModeFade,
                    show_home_launcher)
              : std::nullopt;
  UpdateAnimationSettingsCallback animation_settings_updater =
      animate ? base::BindRepeating(&UpdateOverviewSettings,
                                    kOverviewFadeAnimationDuration)
              : base::NullCallback();
  const float target_scale =
      show_home_launcher ? 1.0f : kOverviewFadeAnimationScale;
  const float target_opacity = show_home_launcher ? 1.0f : 0.0f;
  UpdateScaleAndOpacityForHomeLauncher(target_scale, target_opacity,
                                       std::move(animation_info),
                                       animation_settings_updater);
}

void AppListControllerImpl::UpdateFullscreenLauncherContainer(
    std::optional<int64_t> display_id) {
  aura::Window* window = fullscreen_presenter_->GetWindow();
  if (!window)
    return;

  aura::Window* parent_window =
      GetFullscreenLauncherContainerForDisplayId(display_id);
  if (parent_window && !parent_window->Contains(window)) {
    parent_window->AddChild(window);
    // Release focus if the launcher is moving behind apps, and there is app
    // window showing. Note that the app list can be shown behind apps in
    // tablet mode only.
    if (IsInTabletMode() && !ShouldHomeLauncherBeVisible()) {
      WindowState* const window_state = WindowState::Get(window);
      if (window_state->IsActive())
        window_state->Deactivate();
    }
  }
}

aura::Window* AppListControllerImpl::GetFullscreenLauncherContainerForDisplayId(
    std::optional<int64_t> display_id) {
  aura::Window* root_window = nullptr;
  if (display_id.has_value()) {
    root_window = Shell::GetRootWindowForDisplayId(display_id.value());
  } else if (fullscreen_presenter_->GetWindow()) {
    root_window = fullscreen_presenter_->GetWindow()->GetRootWindow();
  }

  return root_window
             ? root_window->GetChildById(GetFullscreenLauncherContainerId())
             : nullptr;
}

void AppListControllerImpl::Shutdown() {
  DCHECK(!is_shutdown_);
  is_shutdown_ = true;

  // Cancel any pending assistant UI close requests to avoid attempts to update
  // assistant UI state mid shutdown (possibly after assistant has started
  // shutting down).
  IgnoreResult(close_assistant_ui_runner_.Release());

  // Always shutdown the bubble presenter.
  bubble_presenter_->Shutdown();

  Shell* shell = Shell::Get();
  AssistantController::Get()->RemoveObserver(this);
  AssistantUiController::Get()->GetModel()->RemoveObserver(this);
  shell->display_manager()->RemoveDisplayManagerObserver(this);
  AssistantState::Get()->RemoveObserver(this);
  keyboard::KeyboardUIController::Get()->RemoveObserver(this);
  display::Screen::GetScreen()->RemoveObserver(this);
  shell->overview_controller()->RemoveObserver(this);
  shell->RemoveShellObserver(this);
  WallpaperController::Get()->RemoveObserver(this);
  shell->session_controller()->RemoveObserver(this);
  FeatureDiscoveryDurationReporter::GetInstance()->RemoveObserver(this);

  badge_controller_->Shutdown();
}

bool AppListControllerImpl::IsHomeScreenVisible() {
  return IsInTabletMode() && IsVisible();
}

void AppListControllerImpl::OnWindowDragStarted() {
  in_window_dragging_ = true;
  UpdateHomeScreenVisibility();

  // Dismiss Assistant if it's running when a window drag starts.
  if (fullscreen_presenter_->IsShowingEmbeddedAssistantUI())
    fullscreen_presenter_->ShowEmbeddedAssistantUI(false);
}

void AppListControllerImpl::OnWindowDragEnded(bool animate) {
  in_window_dragging_ = false;
  UpdateHomeScreenVisibility();
  if (ShouldShowHomeScreen())
    UpdateForOverviewModeChange(/*show_home_launcher=*/true, animate);
}

void AppListControllerImpl::UpdateTrackedAppWindow() {
  // Do not want to observe new windows or further update
  // |tracked_app_window_| once Shutdown() has been called.
  aura::Window* top_window = !is_shutdown_ ? GetTopVisibleWindow() : nullptr;
  if (tracked_app_window_ == top_window)
    return;

  if (tracked_app_window_)
    tracked_app_window_->RemoveObserver(this);
  tracked_app_window_ = top_window;
  if (tracked_app_window_)
    tracked_app_window_->AddObserver(this);
}

void AppListControllerImpl::RecordAppListState() {
  recorded_app_list_view_state_ = GetAppListViewState();
  recorded_app_list_visibility_ = last_visible_;
}

void AppListControllerImpl::StartTrackingAnimationSmoothness(
    int64_t display_id) {
  auto* root_window = Shell::GetRootWindowForDisplayId(display_id);
  auto* compositor = root_window->layer()->GetCompositor();
  smoothness_tracker_ = compositor->RequestNewCompositorMetricsTracker();
  smoothness_tracker_->Start(
      metrics_util::ForSmoothnessV3(base::BindRepeating([](int smoothness) {
        UMA_HISTOGRAM_PERCENTAGE(kHomescreenAnimationHistogram, smoothness);
      })));
}

void AppListControllerImpl::RecordAnimationSmoothness() {
  if (!smoothness_tracker_)
    return;
  smoothness_tracker_->Stop();
  smoothness_tracker_.reset();
}

void AppListControllerImpl::OnGoHomeWindowAnimationsEnded(int64_t display_id) {
  RecordAnimationSmoothness();
  OnHomeLauncherAnimationComplete(/*shown=*/true, display_id);
}

void AppListControllerImpl::OnReporterActivated() {
  FeatureDiscoveryDurationReporter::GetInstance()->MaybeActivateObservation(
      feature_discovery::TrackableFeature::
          kAppListReorderAfterSessionActivation);
}

int AppListControllerImpl::GetFullscreenLauncherContainerId() const {
  const bool should_show_behind_apps =
      app_list_page_ != AppListState::kStateEmbeddedAssistant;
  return should_show_behind_apps ? kShellWindowId_HomeScreenContainer
                                 : kShellWindowId_AppListContainer;
}

void AppListControllerImpl::ShowGeminiButton(std::string app_name) {
  CHECK(client_);

  GetSearchModel()->search_box()->SetGeminiButtonVisibility(
      SearchBoxModel::SearchBoxIconButton({
          .display_name = app_name,
          .icon = client_->GetGeminiIcon(),
      }));
}

void AppListControllerImpl::HideGeminiButton() {
  gemini_app_waiter_.reset();
  GetSearchModel()->search_box()->SetGeminiButtonVisibility(std::nullopt);
}

int AppListControllerImpl::GetPreferredBubbleWidth(
    aura::Window* root_window) const {
  DCHECK(bubble_presenter_);

  return bubble_presenter_->GetPreferredBubbleWidth(root_window);
}

bool AppListControllerImpl::SetHomeButtonQuickApp(const std::string& app_id) {
  if (!features::IsHomeButtonQuickAppAccessEnabled()) {
    return false;
  }
  return model_provider_->quick_app_access_model()->SetQuickApp(app_id);
}

// static
void AppListControllerImpl::SetSunfishNudgeDisabledForTest(bool is_disabled) {
  g_sunfish_nudge_disabled_for_test = is_disabled;
}

void AppListControllerImpl::MaybeShowSunfishLauncherNudge(
    views::View* launcher_button) {
  if (g_sunfish_nudge_disabled_for_test) {
    return;
  }

  if (base::CommandLine::ForCurrentProcess()->HasSwitch(
          switches::kAshNoNudges)) {
    return;
  }

  if (!CanShowSunfishOrScannerUi()) {
    return;
  }

  // We don't want to show the nudge if the user is not signed in yet.
  auto* session_controller = Shell::Get()->session_controller();
  if (!session_controller || session_controller->IsUserSessionBlocked()) {
    return;
  }

  auto* pref_service = session_controller->GetActivePrefService();
  CHECK(pref_service);
  CHECK(launcher_button);

  const int shown_count =
      pref_service->GetInteger(prefs::kSunfishLauncherNudgeShownCount);
  const base::Time last_shown_time =
      pref_service->GetTime(prefs::kSunfishLauncherNudgeLastShown);

  // Do not show the nudge more than three times, or if it has already been
  // shown in the past 24 hours.
  const base::Time now = base::Time::Now();
  if ((shown_count >= capture_mode::kSunfishNudgeMaxShownCount) ||
      ((now - last_shown_time) < capture_mode::kSunfishNudgeTimeBetweenShown)) {
    return;
  }

  // Update the preferences.
  pref_service->SetInteger(prefs::kSunfishLauncherNudgeShownCount,
                           shown_count + 1);
  pref_service->SetTime(prefs::kSunfishLauncherNudgeLastShown, now);

  // TODO(hewer): Upload string for translation.
  AnchoredNudgeData nudge_data = AnchoredNudgeData(
      capture_mode::kSunfishLauncherNudgeId,
      NudgeCatalogName::kSunfishLauncherNudge,
      u"Select anything on your screen and let your Chromebook suggest best "
      u"actions from there",
      launcher_button);

  AnchoredNudgeManager::Get()->Show(nudge_data);
}

}  // namespace ash