File: brightness_controller_chromeos_unittest.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 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 (1850 lines) | stat: -rw-r--r-- 76,048 bytes parent folder | download | duplicates (5)
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
// Copyright 2024 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/system/brightness/brightness_controller_chromeos.h"

#include <memory>

#include "ash/constants/ash_features.h"
#include "ash/constants/ash_pref_names.h"
#include "ash/login/login_screen_controller.h"
#include "ash/login/ui/login_data_dispatcher.h"
#include "ash/session/session_controller_impl.h"
#include "ash/shell.h"
#include "ash/system/brightness_control_delegate.h"
#include "ash/system/power/power_status.h"
#include "ash/test/ash_test_base.h"
#include "base/test/bind.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/scoped_feature_list.h"
#include "base/test/task_environment.h"
#include "base/time/time.h"
#include "chromeos/dbus/power/fake_power_manager_client.h"
#include "chromeos/dbus/power_manager/backlight.pb.h"
#include "components/account_id/account_id.h"
#include "components/session_manager/session_manager_types.h"
#include "components/user_manager/known_user.h"
#include "components/user_manager/user_type.h"

namespace ash {

namespace {

power_manager::PowerSupplyProperties BuildFakePowerSupplyProperties(
    power_manager::PowerSupplyProperties::ExternalPower charger_state) {
  power_manager::PowerSupplyProperties fake_power;
  fake_power.set_external_power(charger_state);
  fake_power.set_battery_percent(50);
  return fake_power;
}

void SetBatteryPower() {
  DCHECK(PowerStatus::IsInitialized());
  PowerStatus::Get()->SetProtoForTesting(BuildFakePowerSupplyProperties(
      power_manager::PowerSupplyProperties::DISCONNECTED));
}

void SetChargerPower() {
  DCHECK(PowerStatus::IsInitialized());
  PowerStatus::Get()->SetProtoForTesting(
      BuildFakePowerSupplyProperties(power_manager::PowerSupplyProperties::AC));
}

bool HasBrightnessPrefValue(const user_manager::KnownUser& known_user,
                            const AccountId& account_id) {
  const base::Value* pref_value = known_user.FindPath(
      account_id, prefs::kInternalDisplayScreenBrightnessPercent);
  if (!pref_value) {
    return false;
  }

  return pref_value->is_double();
}

// Gets the KnownUser internal display brightness pref value. Only call this
// function if HasBrightnessPrefValue is true.
double GetBrightnessPrefValue(const user_manager::KnownUser& known_user,
                              const AccountId& account_id) {
  return known_user
      .FindPath(account_id, prefs::kInternalDisplayScreenBrightnessPercent)
      ->GetDouble();
}

// Return true if there is a KnownUser pref for the ambient light sensor
// disabled reason.
bool HasAmbientLightSensorDisabledReasonPrefValue(
    const user_manager::KnownUser& known_user,
    const AccountId& account_id) {
  const base::Value* pref_value =
      known_user.FindPath(account_id, prefs::kAmbientLightSensorDisabledReason);
  if (!pref_value) {
    return false;
  }

  return pref_value->is_int();
}

// Gets the KnownUser ambient light sensor disabled reason pref value. Only call
// this function if HasAmbientLightSensorDisabledReasonPrefValue is true.
int GetAmbientLightSensorDisabledReasonPrefValue(
    const user_manager::KnownUser& known_user,
    const AccountId& account_id) {
  return known_user
      .FindPath(account_id, prefs::kAmbientLightSensorDisabledReason)
      ->GetInt();
}

// Return true if there is a KnownUser pref for the ambient light sensor
// enabled status.
bool HasDisplayAmbientLightSensorEnabledPrefValue(
    const user_manager::KnownUser& known_user,
    const AccountId& account_id) {
  const base::Value* pref_value =
      known_user.FindPath(account_id, prefs::kDisplayAmbientLightSensorEnabled);
  if (!pref_value) {
    return false;
  }

  return pref_value->is_bool();
}

// Gets the KnownUser ambient light sensor enabled pref value. Only call
// this function if HasDisplayAmbientLightSensorEnabledPrefValue is true.
bool GetDisplayAmbientLightSensorEnabledPrefValue(
    const user_manager::KnownUser& known_user,
    const AccountId& account_id) {
  return known_user
      .FindPath(account_id, prefs::kDisplayAmbientLightSensorEnabled)
      ->GetBool();
}

constexpr char kUserEmail[] = "user@example.com";
constexpr char kUserEmailSecondary[] = "user2@example.com";
constexpr char kUserEmailTertiary[] = "user3@example.com";
constexpr double kInitialBrightness = 51.0;

}  // namespace

class BrightnessControllerChromeosTest : public AshTestBase {
 public:
  BrightnessControllerChromeosTest()
      : AshTestBase(base::test::TaskEnvironment::TimeSource::MOCK_TIME) {}

  void SetUp() override {
    AshTestBase::SetUp();
    histogram_tester_ = std::make_unique<base::HistogramTester>();
  }

  void TearDown() override { AshTestBase::TearDown(); }

  BrightnessControlDelegate* brightness_control_delegate() {
    return Shell::Get()->brightness_control_delegate();
  }

  LoginDataDispatcher* login_data_dispatcher() {
    return Shell::Get()->login_screen_controller()->data_dispatcher();
  }

 protected:
  std::unique_ptr<base::HistogramTester> histogram_tester_;
  base::RunLoop run_loop_;
  base::test::ScopedFeatureList scoped_feature_list_;

  void AdvanceClock(base::TimeDelta time) {
    task_environment()->AdvanceClock(time);
  }

  void SetAmbientLightSensorEnabled(
      bool enabled,
      power_manager::AmbientLightSensorChange_Cause cause) {
    brightness_control_delegate()->SetAmbientLightSensorEnabled(
        enabled, BrightnessControlDelegate::
                     AmbientLightSensorEnabledChangeSource::kSettingsApp);
    power_manager::AmbientLightSensorChange sensor_change;
    sensor_change.set_sensor_enabled(enabled);
    sensor_change.set_cause(cause);
    power_manager_client()->SendAmbientLightSensorEnabledChanged(sensor_change);
  }

  void SetBrightness(double brightness_percent,
                     power_manager::BacklightBrightnessChange_Cause cause) {
    brightness_control_delegate()->HandleBrightnessDown();
    power_manager::BacklightBrightnessChange brightness_change;
    brightness_change.set_percent(brightness_percent);
    brightness_change.set_cause(cause);
    power_manager_client()->set_screen_brightness_percent(brightness_percent);
    power_manager_client()->SendScreenBrightnessChanged(brightness_change);
  }

  void ExpectAmbientLightSensorEnabled(bool expected_value,
                                       const std::string error_message) {
    brightness_control_delegate()->GetAmbientLightSensorEnabled(
        base::BindLambdaForTesting([expected_value, error_message](
                                       std::optional<bool> sensor_enabled) {
          EXPECT_EQ(sensor_enabled.value(), expected_value) << error_message;
        }));
  }

  void ExpectBrightnessPercent(double expected_value,
                               const std::string error_message) {
    brightness_control_delegate()->GetBrightnessPercent(
        base::BindLambdaForTesting(
            [expected_value,
             error_message](std::optional<double> brightness_percent) {
              EXPECT_EQ(brightness_percent.value(), expected_value)
                  << error_message;
            }));
  }

  // On the login screen, focus the given account.
  void LoginScreenFocusAccount(const AccountId account_id) {
    login_data_dispatcher()->NotifyFocusPod(account_id);
    run_loop_.RunUntilIdle();
  }
};

TEST_F(BrightnessControllerChromeosTest, Prefs_OnLoginScreen_MultipleUsers) {
  // Set initial brightness.
  power_manager_client()->set_screen_brightness_percent(kInitialBrightness);

  // Clear user sessions and reset to the primary login screen.
  ClearLogin();

  // On the login screen, focus a user.
  AccountId account_id = AccountId::FromUserEmail(kUserEmail);
  login_data_dispatcher()->NotifyFocusPod(account_id);

  // Create a KnownUser for this Local State.
  user_manager::KnownUser known_user(local_state());

  // Simulate the brightness changing automatically due to inactivity.
  // This should not be saved into Local State.
  SetBrightness(0.0,
                power_manager::BacklightBrightnessChange_Cause_USER_INACTIVITY);
  EXPECT_FALSE(HasBrightnessPrefValue(known_user, account_id));

  // Simulate the brightness changing automatically due to activity.
  // This should not be saved into Local State.
  SetBrightness(60.0,
                power_manager::BacklightBrightnessChange_Cause_USER_ACTIVITY);
  EXPECT_FALSE(HasBrightnessPrefValue(known_user, account_id));

  // The brightness Local State pref should not be set yet, because the
  // brightness has not yet been adjusted by the user.
  EXPECT_FALSE(HasBrightnessPrefValue(known_user, account_id));

  // The secondary account should not have a pref saved yet either.
  AccountId secondary_account_id =
      AccountId::FromUserEmail(kUserEmailSecondary);
  EXPECT_FALSE(HasBrightnessPrefValue(known_user, secondary_account_id));

  // Set the brightness to a new value via user action.
  double first_brightness_change_percent = 12.0;
  SetBrightness(first_brightness_change_percent,
                power_manager::BacklightBrightnessChange_Cause_USER_REQUEST);

  // The brightness Local State pref should now be set, with the value of the
  // current brightness.
  EXPECT_EQ(GetBrightnessPrefValue(known_user, account_id),
            first_brightness_change_percent);

  // The second user should still not have a pref set.
  EXPECT_FALSE(HasBrightnessPrefValue(known_user, secondary_account_id));

  // On the login screen, focus the second user.
  login_data_dispatcher()->NotifyFocusPod(secondary_account_id);

  // Switching focused users should not change the saved prefs.
  EXPECT_EQ(GetBrightnessPrefValue(known_user, account_id),
            first_brightness_change_percent);

  // The second user should still not have a pref set.
  EXPECT_FALSE(HasBrightnessPrefValue(known_user, secondary_account_id));

  // Set the brightness to a new value via user action.
  double second_brightness_change_percent = 99.9;
  SetBrightness(second_brightness_change_percent,
                power_manager::BacklightBrightnessChange_Cause_USER_REQUEST);

  // The first user should still have its old value set.
  EXPECT_EQ(GetBrightnessPrefValue(known_user, account_id),
            first_brightness_change_percent);

  // The second user should have the new value set.
  EXPECT_EQ(GetBrightnessPrefValue(known_user, secondary_account_id),
            second_brightness_change_percent);
}

TEST_F(BrightnessControllerChromeosTest,
       Prefs_OnLoginScreen_BrightnessNotChanged) {
  // Set initial brightness.
  power_manager_client()->set_screen_brightness_percent(kInitialBrightness);

  // Clear user sessions and reset to the primary login screen.
  ClearLogin();

  // On the login screen, focus a user.
  AccountId account_id = AccountId::FromUserEmail(kUserEmail);
  login_data_dispatcher()->NotifyFocusPod(account_id);

  // The brightness Local State pref should not be set yet, because the
  // brightness has not yet been adjusted.
  user_manager::KnownUser known_user(local_state());
  EXPECT_FALSE(HasBrightnessPrefValue(known_user, account_id));

  SimulateUserLogin({kUserEmail});

  // Wait for callback in
  // BrightnessControllerChromeos::OnActiveUserSessionChanged to finish.
  run_loop_.RunUntilIdle();

  // After login, the brightness pref should have a value equal to the initial
  // brightness level.
  EXPECT_EQ(GetBrightnessPrefValue(known_user, account_id), kInitialBrightness);
}

TEST_F(BrightnessControllerChromeosTest,
       Prefs_AfterLogin_BrightnessChange_SaveToLocalStatePref) {
  // Set initial brightness.
  power_manager_client()->set_screen_brightness_percent(kInitialBrightness);

  // Clear user sessions and reset to the primary login screen.
  ClearLogin();

  // On the login screen, focus a user.
  AccountId account_id = AccountId::FromUserEmail(kUserEmail);
  login_data_dispatcher()->NotifyFocusPod(account_id);

  // Simulate the brightness changing automatically due to inactivity.
  // This should not be saved into Local State.
  SetBrightness(0.0,
                power_manager::BacklightBrightnessChange_Cause_USER_INACTIVITY);

  // Simulate the brightness changing automatically due to activity.
  // This should not be saved into Local State.
  SetBrightness(62.0,
                power_manager::BacklightBrightnessChange_Cause_USER_ACTIVITY);

  // Set the brightness to a new value via user action.
  double brightness_change_percent = 12.0;
  SetBrightness(brightness_change_percent,
                power_manager::BacklightBrightnessChange_Cause_USER_REQUEST);

  // The brightness Local State pref should now be set, with the value of the
  // current brightness.
  user_manager::KnownUser known_user(local_state());
  EXPECT_EQ(GetBrightnessPrefValue(known_user, account_id),
            brightness_change_percent);

  SimulateUserLogin({kUserEmail});

  // Wait for callback in
  // BrightnessControllerChromeos::OnActiveUserSessionChanged to finish.
  run_loop_.RunUntilIdle();

  // Simulate the brightness changing automatically due to inactivity.
  // This should not be saved into Local State.
  SetBrightness(0.0,
                power_manager::BacklightBrightnessChange_Cause_USER_INACTIVITY);

  // Confirm that after login, the brightness Local State pref has the same
  // value.
  EXPECT_EQ(GetBrightnessPrefValue(known_user, account_id),
            brightness_change_percent);

  // Change the brightness via user request (this time, after login).
  double new_brightness_change_percent = 96.0;
  SetBrightness(new_brightness_change_percent,
                power_manager::BacklightBrightnessChange_Cause_USER_REQUEST);

  // The Local State brightness pref should have the new brightness value
  // stored.
  EXPECT_EQ(GetBrightnessPrefValue(known_user, account_id),
            new_brightness_change_percent);

  // Change the brightness via user request, from the Settings app.
  double settings_brightness_change_percent = 22.2;
  SetBrightness(
      settings_brightness_change_percent,
      power_manager::
          BacklightBrightnessChange_Cause_USER_REQUEST_FROM_SETTINGS_APP);

  // The Local State brightness pref should have the new brightness value
  // stored.
  EXPECT_EQ(GetBrightnessPrefValue(known_user, account_id),
            settings_brightness_change_percent);
}

TEST_F(BrightnessControllerChromeosTest,
       HistogramTest_DecreaseBrightnessOnLoginScreen) {
  // Metric count should start at 0.
  histogram_tester_->ExpectTotalCount(
      "ChromeOS.Display.TimeUntilFirstBrightnessChange.OnLoginScreen."
      "DecreaseBrightness.BatteryPower",
      0);

  // Start on the login screen
  GetSessionControllerClient()->SetSessionState(
      session_manager::SessionState::LOGIN_PRIMARY);

  // "Unplug" the device from charger
  SetBatteryPower();

  // Wait for a period of time, then send a brightness event
  int seconds_to_wait = 11;
  AdvanceClock(base::Seconds(seconds_to_wait));
  brightness_control_delegate()->HandleBrightnessDown();

  histogram_tester_->ExpectTotalCount(
      "ChromeOS.Display.TimeUntilFirstBrightnessChange.OnLoginScreen."
      "DecreaseBrightness.BatteryPower",
      1);
  histogram_tester_->ExpectTimeBucketCount(
      "ChromeOS.Display.TimeUntilFirstBrightnessChange.OnLoginScreen."
      "DecreaseBrightness.BatteryPower",
      base::Seconds(seconds_to_wait), 1);

  // Login
  GetSessionControllerClient()->SetSessionState(
      session_manager::SessionState::ACTIVE);

  // Wait for a period of time, then send another brightness event
  AdvanceClock(base::Seconds(5));
  brightness_control_delegate()->HandleBrightnessDown();

  // The number of events should not have changed, since we already recorded a
  // metric on the login screen.
  histogram_tester_->ExpectTotalCount(
      "ChromeOS.Display.TimeUntilFirstBrightnessChange.OnLoginScreen."
      "DecreaseBrightness.BatteryPower",
      1);
}

TEST_F(BrightnessControllerChromeosTest,
       Prefs_OnLogin_DoNotSaveBrightnessWhenLidClosed) {
  // Set initial brightness.
  power_manager_client()->set_screen_brightness_percent(kInitialBrightness);

  // Clear user sessions and reset to the primary login screen.
  ClearLogin();

  // On the login screen, focus a user
  AccountId account_id = AccountId::FromUserEmail(kUserEmail);
  login_data_dispatcher()->NotifyFocusPod(account_id);

  // Create a KnownUser for this Local State
  user_manager::KnownUser known_user(local_state());

  // Verify no brightness preference exists yet
  EXPECT_FALSE(HasBrightnessPrefValue(known_user, account_id));

  system::BrightnessControllerChromeos* brightness_controller =
      static_cast<system::BrightnessControllerChromeos*>(
          brightness_control_delegate());
  {
    // Simulate lid closed and verify that brightness pref is not saved.
    power_manager_client()->set_screen_brightness_percent(0.0);
    brightness_controller->LidEventReceived(
        chromeos::PowerManagerClient::LidState::CLOSED, base::TimeTicks::Now());
    brightness_controller->OnActiveUserSessionChanged(account_id);
    run_loop_.RunUntilIdle();
    EXPECT_FALSE(HasBrightnessPrefValue(known_user, account_id))
        << "Brightness should not be saved to preferences when lid is closed";
  }
  {
    // Simulate lid open and verify that brightness pref is saved.
    power_manager_client()->set_screen_brightness_percent(kInitialBrightness);
    brightness_controller->LidEventReceived(
        chromeos::PowerManagerClient::LidState::OPEN, base::TimeTicks::Now());
    brightness_controller->OnActiveUserSessionChanged(account_id);
    run_loop_.RunUntilIdle();
    EXPECT_TRUE(HasBrightnessPrefValue(known_user, account_id))
        << "Brightness should be saved to preferences when lid is open";
  }
}

TEST_F(BrightnessControllerChromeosTest, HistogramTest_LoginSecondary) {
  // Metric count should start at 0.
  histogram_tester_->ExpectTotalCount(
      "ChromeOS.Display.TimeUntilFirstBrightnessChange.OnLoginScreen."
      "DecreaseBrightness.BatteryPower",
      0);

  // Start on the "secondary" login screen (i.e. another user is already
  // logged-in, and another user is now logging in).
  GetSessionControllerClient()->SetSessionState(
      session_manager::SessionState::LOGIN_SECONDARY);

  // "Unplug" the device from charger
  SetBatteryPower();

  // Wait for a period of time, then send a brightness event
  int seconds_to_wait = 22;
  AdvanceClock(base::Seconds(seconds_to_wait));
  brightness_control_delegate()->HandleBrightnessDown();

  histogram_tester_->ExpectTotalCount(
      "ChromeOS.Display.TimeUntilFirstBrightnessChange.OnLoginScreen."
      "DecreaseBrightness.BatteryPower",
      1);
  histogram_tester_->ExpectTimeBucketCount(
      "ChromeOS.Display.TimeUntilFirstBrightnessChange.OnLoginScreen."
      "DecreaseBrightness.BatteryPower",
      base::Seconds(seconds_to_wait), 1);

  // Login
  GetSessionControllerClient()->SetSessionState(
      session_manager::SessionState::ACTIVE);

  // Wait for a period of time, then send another brightness event
  AdvanceClock(base::Seconds(5));
  brightness_control_delegate()->HandleBrightnessDown();

  // The number of events should not have changed, since we already recorded a
  // metric on the login screen.
  histogram_tester_->ExpectTotalCount(
      "ChromeOS.Display.TimeUntilFirstBrightnessChange.OnLoginScreen."
      "DecreaseBrightness.BatteryPower",
      1);
}

TEST_F(BrightnessControllerChromeosTest, HistogramTest_PowerSourceCharger) {
  // Metric count should start at 0.
  histogram_tester_->ExpectTotalCount(
      "ChromeOS.Display.TimeUntilFirstBrightnessChange.OnLoginScreen."
      "IncreaseBrightness.ChargerPower",
      0);

  // Start on the login screen
  GetSessionControllerClient()->SetSessionState(
      session_manager::SessionState::LOGIN_PRIMARY);

  // "Plug in" the charger
  SetChargerPower();

  // Wait for a period of time, then send a brightness event
  int seconds_to_wait = 8;
  AdvanceClock(base::Seconds(seconds_to_wait));
  brightness_control_delegate()->HandleBrightnessUp();

  histogram_tester_->ExpectTotalCount(
      "ChromeOS.Display.TimeUntilFirstBrightnessChange.OnLoginScreen."
      "IncreaseBrightness.ChargerPower",
      1);
  histogram_tester_->ExpectTimeBucketCount(
      "ChromeOS.Display.TimeUntilFirstBrightnessChange.OnLoginScreen."
      "IncreaseBrightness.ChargerPower",
      base::Seconds(seconds_to_wait), 1);
}

TEST_F(BrightnessControllerChromeosTest,
       HistogramTest_BrightnessChangeAfterLogin) {
  // Metric count should start at 0.
  histogram_tester_->ExpectTotalCount(
      "ChromeOS.Display.TimeUntilFirstBrightnessChange.AfterLogin."
      "SetBrightness.ChargerPower",
      0);

  // Start on the login screen
  GetSessionControllerClient()->SetSessionState(
      session_manager::SessionState::LOGIN_PRIMARY);

  // "Plug in" the charger
  SetChargerPower();

  // Wait for a period of time, but don't change brightness.
  AdvanceClock(base::Seconds(9));

  // Login
  GetSessionControllerClient()->SetSessionState(
      session_manager::SessionState::ACTIVE);

  // Wait for a period of time, then send another brightness event
  int seconds_to_wait = 5;
  AdvanceClock(base::Seconds(seconds_to_wait));
  brightness_control_delegate()->SetBrightnessPercent(
      50, /*gradual=*/true, /*source=*/
      BrightnessControlDelegate::BrightnessChangeSource::kQuickSettings);

  // Brightness changes from Quick Settings should have cause "USER_REQUEST".
  EXPECT_EQ(power_manager_client()->requested_screen_brightness_cause(),
            power_manager::SetBacklightBrightnessRequest_Cause_USER_REQUEST);

  // Expect a record with the number of seconds since login, not since the
  // beginning of the login screen.
  histogram_tester_->ExpectTimeBucketCount(
      "ChromeOS.Display.TimeUntilFirstBrightnessChange.AfterLogin."
      "SetBrightness.ChargerPower",
      base::Seconds(seconds_to_wait), 1);
}

TEST_F(BrightnessControllerChromeosTest,
       HistogramTest_BrightnessChangeAfterLogin_LongDuration) {
  // Metric count should start at 0.
  histogram_tester_->ExpectTotalCount(
      "ChromeOS.Display.TimeUntilFirstBrightnessChange.AfterLogin."
      "IncreaseBrightness.BatteryPower",
      0);

  // Start on the login screen
  GetSessionControllerClient()->SetSessionState(
      session_manager::SessionState::LOGIN_PRIMARY);

  // "Unplug" the charger
  SetBatteryPower();

  // Wait for a period of time, but don't change brightness.
  AdvanceClock(base::Seconds(20));

  // Login
  GetSessionControllerClient()->SetSessionState(
      session_manager::SessionState::ACTIVE);

  // Wait for a period of time, then send another brightness event
  int minutes_to_wait = 35;
  AdvanceClock(base::Minutes(minutes_to_wait));
  brightness_control_delegate()->HandleBrightnessUp();

  // Expect a record with the number of minutes since login, not since the
  // beginning of the login screen.
  histogram_tester_->ExpectTotalCount(
      "ChromeOS.Display.TimeUntilFirstBrightnessChange.AfterLogin."
      "IncreaseBrightness.BatteryPower",
      1);
  histogram_tester_->ExpectTimeBucketCount(
      "ChromeOS.Display.TimeUntilFirstBrightnessChange.AfterLogin."
      "IncreaseBrightness.BatteryPower",
      base::Minutes(minutes_to_wait), 1);
}

TEST_F(BrightnessControllerChromeosTest,
       HistogramTest_BrightnessChangeAfterLogin_DurationGreaterThanOneHour) {
  // Start on the login screen
  GetSessionControllerClient()->SetSessionState(
      session_manager::SessionState::LOGIN_PRIMARY);

  // "Unplug" the charger
  SetBatteryPower();

  // Wait for a period of time, but don't change brightness.
  AdvanceClock(base::Seconds(1));

  // Login
  GetSessionControllerClient()->SetSessionState(
      session_manager::SessionState::ACTIVE);

  // Wait for > 1 hour, then send a brightness event.
  AdvanceClock(base::Hours(1) + base::Minutes(5));
  brightness_control_delegate()->HandleBrightnessUp();

  // Since the brightness event occurred >1 hour after login, don't record it.
  histogram_tester_->ExpectTotalCount(
      "ChromeOS.Display.TimeUntilFirstBrightnessChange.AfterLogin."
      "IncreaseBrightness.BatteryPower",
      0);
}

TEST_F(BrightnessControllerChromeosTest, SetAmbientLightSensorEnabled) {
  GetSessionControllerClient()->SetSessionState(
      session_manager::SessionState::ACTIVE);
  SetBatteryPower();

  // Ambient light sensor is enabled by default.
  EXPECT_TRUE(power_manager_client()->is_ambient_light_sensor_enabled());

  // Disable the ambient light sensor via the BrightnessControlDelegate.
  brightness_control_delegate()->SetAmbientLightSensorEnabled(
      false, BrightnessControlDelegate::AmbientLightSensorEnabledChangeSource::
                 kSettingsApp);
  // PowerManagerClient should have been invoked, disabling the ambient light
  // sensor.
  EXPECT_FALSE(power_manager_client()->is_ambient_light_sensor_enabled());

  // Re-enabled the ambient light sensor via the BrightnessControlDelegate.
  brightness_control_delegate()->SetAmbientLightSensorEnabled(
      true, BrightnessControlDelegate::AmbientLightSensorEnabledChangeSource::
                kSettingsApp);
  // PowerManagerClient should have been invoked, re-enabling the ambient light
  // sensor.
  EXPECT_TRUE(power_manager_client()->is_ambient_light_sensor_enabled());
}

TEST_F(BrightnessControllerChromeosTest, GetAmbientLightSensorEnabled) {
  GetSessionControllerClient()->SetSessionState(
      session_manager::SessionState::ACTIVE);
  SetBatteryPower();

  // Disable the ambient light sensor via the BrightnessControlDelegate.
  brightness_control_delegate()->SetAmbientLightSensorEnabled(
      false, BrightnessControlDelegate::AmbientLightSensorEnabledChangeSource::
                 kSettingsApp);

  // GetAmbientLightSensorEnabled should return that the the light sensor is
  // currently not enabled.
  brightness_control_delegate()->GetAmbientLightSensorEnabled(
      base::BindOnce([](std::optional<bool> is_ambient_light_sensor_enabled) {
        EXPECT_FALSE(is_ambient_light_sensor_enabled.value());
      }));

  // Re-enable the ambient light sensor via the BrightnessControlDelegate.
  brightness_control_delegate()->SetAmbientLightSensorEnabled(
      true, BrightnessControlDelegate::AmbientLightSensorEnabledChangeSource::
                kSettingsApp);

  // GetAmbientLightSensorEnabled should return that the the light sensor is
  // currently enabled.
  brightness_control_delegate()->GetAmbientLightSensorEnabled(
      base::BindOnce([](std::optional<bool> is_ambient_light_sensor_enabled) {
        EXPECT_TRUE(is_ambient_light_sensor_enabled.value());
      }));
}

TEST_F(BrightnessControllerChromeosTest, HasAmbientLightSensor) {
  GetSessionControllerClient()->SetSessionState(
      session_manager::SessionState::ACTIVE);
  SetBatteryPower();

  power_manager_client()->set_has_ambient_light_sensor(true);

  brightness_control_delegate()->HasAmbientLightSensor(
      base::BindOnce([](std::optional<bool> has_ambient_light_sensor) {
        EXPECT_TRUE(has_ambient_light_sensor.value());
      }));

  power_manager_client()->set_has_ambient_light_sensor(false);

  brightness_control_delegate()->HasAmbientLightSensor(
      base::BindOnce([](std::optional<bool> has_ambient_light_sensor) {
        EXPECT_FALSE(has_ambient_light_sensor.value());
      }));
}

TEST_F(BrightnessControllerChromeosTest, AmbientLightSensorDisabledReasonPref) {
  GetSessionControllerClient()->SetSessionState(
      session_manager::SessionState::ACTIVE);
  SetBatteryPower();

  // Set the ambient light sensor to be enabled initially.
  power_manager::SetAmbientLightSensorEnabledRequest request;
  request.set_sensor_enabled(true);
  power_manager_client()->SetAmbientLightSensorEnabled(request);
  // Wait for AmbientLightSensorEnabledChange observer to be notified.
  run_loop_.RunUntilIdle();

  // On the login screen, focus a user.
  AccountId account_id = AccountId::FromUserEmail(kUserEmail);
  login_data_dispatcher()->NotifyFocusPod(account_id);

  user_manager::KnownUser known_user(local_state());

  // Confirm that no "disabled reason" pref exists for the given KnownUser.
  EXPECT_FALSE(
      HasAmbientLightSensorDisabledReasonPrefValue(known_user, account_id));

  // Disable the ambient light sensor.
  request.set_sensor_enabled(false);
  power_manager_client()->SetAmbientLightSensorEnabled(request);
  // Wait for AmbientLightSensorEnabledChange observer to be notified.
  run_loop_.RunUntilIdle();

  // There should now be a "disabled reason" pref stored in KnownUser.
  EXPECT_TRUE(
      HasAmbientLightSensorDisabledReasonPrefValue(known_user, account_id));
  // In this case, the cause is USER_REQUEST_SETTINGS_APP because the change was
  // made from the PowerManagerClient SetAmbientLightSensorEnabled function.
  EXPECT_EQ(
      power_manager::AmbientLightSensorChange_Cause_USER_REQUEST_SETTINGS_APP,
      GetAmbientLightSensorDisabledReasonPrefValue(known_user, account_id));

  // Re-enable the ambient light sensor.
  request.set_sensor_enabled(true);
  power_manager_client()->SetAmbientLightSensorEnabled(request);
  // Wait for AmbientLightSensorEnabledChange observer to be notified.
  run_loop_.RunUntilIdle();

  // After the ambient light sensor is re-enabled, the "disabled reason" pref
  // should be deleted.
  EXPECT_FALSE(
      HasAmbientLightSensorDisabledReasonPrefValue(known_user, account_id));

  // Get a reference to the actual BrightnessControllerChromeos so that we can
  // trigger its observer callback manually.
  system::BrightnessControllerChromeos* brightness_controller =
      static_cast<system::BrightnessControllerChromeos*>(
          brightness_control_delegate());

  // Disable the ambient light sensor, triggering the observer callback manually
  // so we can manually set a cause.
  {
    power_manager::AmbientLightSensorChange change;
    change.set_sensor_enabled(false);
    power_manager::AmbientLightSensorChange_Cause expected_cause =
        power_manager::AmbientLightSensorChange_Cause_BRIGHTNESS_USER_REQUEST;
    change.set_cause(expected_cause);
    brightness_controller->AmbientLightSensorEnabledChanged(change);
    EXPECT_EQ(expected_cause, GetAmbientLightSensorDisabledReasonPrefValue(
                                  known_user, account_id));
  }

  {
    // Disable the ambient light sensor (again triggering the observer callback
    // manually), choosing a different cause this time. Note that the pref will
    // be set even if the ambient light sensor was previously disabled.
    power_manager::AmbientLightSensorChange change;
    change.set_sensor_enabled(false);
    power_manager::AmbientLightSensorChange_Cause expected_cause =
        power_manager::AmbientLightSensorChange_Cause_NO_READINGS_FROM_ALS;
    change.set_cause(expected_cause);
    brightness_controller->AmbientLightSensorEnabledChanged(change);
    EXPECT_EQ(expected_cause, GetAmbientLightSensorDisabledReasonPrefValue(
                                  known_user, account_id));
  }
}

TEST_F(BrightnessControllerChromeosTest, AmbientLightSensorEnabledPref) {
  // Activate user session.
  GetSessionControllerClient()->SetSessionState(
      session_manager::SessionState::ACTIVE);

  // Set the ambient light sensor to be enabled initially.
  power_manager::SetAmbientLightSensorEnabledRequest request;
  request.set_sensor_enabled(true);
  power_manager_client()->SetAmbientLightSensorEnabled(request);
  // Wait for AmbientLightSensorEnabledChange observer to be notified.
  run_loop_.RunUntilIdle();

  // User pref is default to true.
  EXPECT_TRUE(
      Shell::Get()->session_controller()->GetActivePrefService()->GetBoolean(
          prefs::kDisplayAmbientLightSensorLastEnabled));

  // Disable the sensor via brightness change (not from settings app), pref
  // should remain true.
  SetAmbientLightSensorEnabled(
      false, power_manager::AmbientLightSensorChange_Cause::
                 AmbientLightSensorChange_Cause_BRIGHTNESS_USER_REQUEST);
  EXPECT_TRUE(
      Shell::Get()->session_controller()->GetActivePrefService()->GetBoolean(
          prefs::kDisplayAmbientLightSensorLastEnabled));

  // Re-enable the sensor from settings app, pref should be true.
  SetAmbientLightSensorEnabled(
      true, power_manager::AmbientLightSensorChange_Cause::
                AmbientLightSensorChange_Cause_USER_REQUEST_SETTINGS_APP);
  EXPECT_TRUE(
      Shell::Get()->session_controller()->GetActivePrefService()->GetBoolean(
          prefs::kDisplayAmbientLightSensorLastEnabled));

  // Disable the sensor again, this time, the request is from settings app, the
  // pref should be updated to false.
  SetAmbientLightSensorEnabled(
      false, power_manager::AmbientLightSensorChange_Cause::
                 AmbientLightSensorChange_Cause_USER_REQUEST_SETTINGS_APP);
  EXPECT_FALSE(
      Shell::Get()->session_controller()->GetActivePrefService()->GetBoolean(
          prefs::kDisplayAmbientLightSensorLastEnabled));

  // Re-enable the sensor via user settings and verify the preference updates.
  SetAmbientLightSensorEnabled(
      true, power_manager::AmbientLightSensorChange_Cause::
                AmbientLightSensorChange_Cause_USER_REQUEST_SETTINGS_APP);
  EXPECT_TRUE(
      Shell::Get()->session_controller()->GetActivePrefService()->GetBoolean(
          prefs::kDisplayAmbientLightSensorLastEnabled));
}

class BrightnessControllerChromeosTest_NonApplicableSessionStates
    : public BrightnessControllerChromeosTest,
      public testing::WithParamInterface<session_manager::SessionState> {};

INSTANTIATE_TEST_SUITE_P(
    /* no prefix */,
    BrightnessControllerChromeosTest_NonApplicableSessionStates,
    testing::ValuesIn<session_manager::SessionState>({
        session_manager::SessionState::LOCKED,
        session_manager::SessionState::LOGGED_IN_NOT_ACTIVE,
        session_manager::SessionState::OOBE,
        session_manager::SessionState::RMA,
        session_manager::SessionState::UNKNOWN,
    }));

TEST_P(BrightnessControllerChromeosTest_NonApplicableSessionStates,
       HistogramTest_NonApplicableSessionStates) {
  GetSessionControllerClient()->SetSessionState(GetParam());

  // "Plug in" the charger
  SetChargerPower();

  // Wait for a period of time, then send a brightness event
  AdvanceClock(base::Seconds(8));
  brightness_control_delegate()->HandleBrightnessUp();

  // Expect no events, since the event did not happen on the login screen or
  // after login.
  histogram_tester_->ExpectTotalCount(
      "ChromeOS.Display.TimeUntilFirstBrightnessChange.OnLoginScreen."
      "IncreaseBrightness.ChargerPower",
      0);
  histogram_tester_->ExpectTotalCount(
      "ChromeOS.Display.TimeUntilFirstBrightnessChange.AfterLogin."
      "IncreaseBrightness.ChargerPower",
      0);
}

TEST_F(BrightnessControllerChromeosTest,
       HistogramTest_SetBrightnessAfterSystemRestoration) {
  scoped_feature_list_.InitAndEnableFeature(
      features::kEnableBrightnessControlInSettings);

  // Start on the login screen.
  GetSessionControllerClient()->SetSessionState(
      session_manager::SessionState::LOGIN_PRIMARY);
  SetBatteryPower();

  // Metrics count should start at 0, both OnLogin and AfterLogin.
  histogram_tester_->ExpectTotalCount(
      "ChromeOS.Display.TimeUntilFirstBrightnessChange.OnLoginScreen."
      "SetBrightness.BatteryPower",
      0);
  histogram_tester_->ExpectTotalCount(
      "ChromeOS.Display.TimeUntilFirstBrightnessChange.AfterLogin."
      "SetBrightness.BatteryPower",
      0);

  // Log in.
  ClearLogin();
  AccountId account_id = AccountId::FromUserEmail(kUserEmail);
  user_manager::KnownUser known_user(local_state());
  SimulateUserLogin({kUserEmail});

  // Set display brightness.
  known_user.SetPath(account_id, prefs::kInternalDisplayScreenBrightnessPercent,
                     std::make_optional<base::Value>(30.0));

  // Simulate reboot, brightness should be restored.
  login_data_dispatcher()->NotifyFocusPod(account_id);

  // Verify that system restoring brightness is not recorded.
  histogram_tester_->ExpectTotalCount(
      "ChromeOS.Display.TimeUntilFirstBrightnessChange.OnLoginScreen."
      "SetBrightness.BatteryPower",
      0);
  histogram_tester_->ExpectTotalCount(
      "ChromeOS.Display.TimeUntilFirstBrightnessChange.AfterLogin."
      "SetBrightness.BatteryPower",
      0);

  // Wait and then simulate a user-initiated brightness change.
  int seconds_to_wait = 5;
  AdvanceClock(base::Seconds(seconds_to_wait));
  brightness_control_delegate()->SetBrightnessPercent(
      50, /*gradual=*/true, /*source=*/
      BrightnessControlDelegate::BrightnessChangeSource::kQuickSettings);

  // Verify that the user-initiated brightness change is recorded.
  histogram_tester_->ExpectTimeBucketCount(
      "ChromeOS.Display.TimeUntilFirstBrightnessChange.AfterLogin."
      "SetBrightness.BatteryPower",
      base::Seconds(seconds_to_wait), 1);
}

TEST_F(BrightnessControllerChromeosTest, SetBrightnessPercent_Cause) {
  GetSessionControllerClient()->SetSessionState(
      session_manager::SessionState::ACTIVE);
  SetChargerPower();

  brightness_control_delegate()->SetBrightnessPercent(
      50, /*gradual=*/true, /*source=*/
      BrightnessControlDelegate::BrightnessChangeSource::kQuickSettings);

  // Brightness changes from Quick Settings should have cause "USER_REQUEST".
  EXPECT_EQ(power_manager_client()->requested_screen_brightness_cause(),
            power_manager::SetBacklightBrightnessRequest_Cause_USER_REQUEST);

  brightness_control_delegate()->SetBrightnessPercent(
      50, /*gradual=*/true, /*source=*/
      BrightnessControlDelegate::BrightnessChangeSource::kSettingsApp);

  // Brightness changes from the Settings app should have cause
  // "USER_REQUEST_FROM_SETTINGS_APP".
  EXPECT_EQ(
      power_manager_client()->requested_screen_brightness_cause(),
      power_manager::
          SetBacklightBrightnessRequest_Cause_USER_REQUEST_FROM_SETTINGS_APP);
}

TEST_F(BrightnessControllerChromeosTest, SetAmbientLightSensorEnabled_Cause) {
  GetSessionControllerClient()->SetSessionState(
      session_manager::SessionState::ACTIVE);
  SetChargerPower();

  brightness_control_delegate()->SetAmbientLightSensorEnabled(
      true, BrightnessControlDelegate::AmbientLightSensorEnabledChangeSource::
                kSettingsApp);

  // Brightness changes from Setting app should have cause
  // "USER_REQUEST_FROM_SETTINGS_APP".
  EXPECT_EQ(
      power_manager_client()->requested_ambient_light_sensor_enabled_cause(),
      power_manager::
          SetAmbientLightSensorEnabledRequest_Cause_USER_REQUEST_FROM_SETTINGS_APP);

  brightness_control_delegate()->SetAmbientLightSensorEnabled(
      false, BrightnessControlDelegate::AmbientLightSensorEnabledChangeSource::
                 kRestoredFromUserPref);

  // Brightness changes from the Settings app should have cause
  // "USER_REQUEST_FROM_SETTINGS_APP".
  EXPECT_EQ(
      power_manager_client()->requested_ambient_light_sensor_enabled_cause(),
      power_manager::
          SetAmbientLightSensorEnabledRequest_Cause_RESTORED_FROM_USER_PREFERENCE);
}

TEST_F(BrightnessControllerChromeosTest,
       RestoreBrightnessSettingsFromPref_FlagEnabled) {
  scoped_feature_list_.InitAndEnableFeature(
      features::kEnableBrightnessControlInSettings);

  // Set initial ALS status and brightness level.
  power_manager::SetAmbientLightSensorEnabledRequest request;
  request.set_sensor_enabled(true);
  power_manager_client()->SetAmbientLightSensorEnabled(request);
  power_manager_client()->set_screen_brightness_percent(kInitialBrightness);
  run_loop_.RunUntilIdle();

  // Clear user sessions and reset to the primary login screen.
  ClearLogin();

  // On the login screen, focus the first user.
  AccountId first_account = AccountId::FromUserEmail(kUserEmail);
  LoginScreenFocusAccount(first_account);
  ExpectAmbientLightSensorEnabled(
      true, "ALS should be enabled for first user by default.");
  ExpectBrightnessPercent(
      kInitialBrightness,
      "Brightness should be unchanged for first user after initial focus.");

  // Then, focus the second user.
  AccountId second_account = AccountId::FromUserEmail(kUserEmailSecondary);
  LoginScreenFocusAccount(second_account);
  ExpectAmbientLightSensorEnabled(
      true, "ALS should be enabled for second user by default.");
  ExpectBrightnessPercent(
      kInitialBrightness,
      "Brightness should be unchanged for second user after initial focus.");

  // Switch back to the first user, then disable ALS by changing the brightness.
  LoginScreenFocusAccount(first_account);
  const double first_brightness_change_percent = 12.0;
  brightness_control_delegate()->SetBrightnessPercent(
      first_brightness_change_percent, /*gradual=*/false,
      BrightnessControlDelegate::BrightnessChangeSource::kQuickSettings);
  // Wait for callbacks to finish executing.
  run_loop_.RunUntilIdle();
  ExpectAmbientLightSensorEnabled(
      false, "ALS should be disabled for first user after brightness change.");
  ExpectBrightnessPercent(first_brightness_change_percent,
                          "Brightness should be equal to the previously-set "
                          "value for the first user.");

  LoginScreenFocusAccount(second_account);
  ExpectAmbientLightSensorEnabled(true,
                                  "ALS should be enabled for second user "
                                  "despite being disabled for first user.");
  ExpectBrightnessPercent(
      first_brightness_change_percent,
      "Brightness should remain the same after switching to the second user.");

  // Switch to a third user.
  AccountId third_account = AccountId::FromUserEmail(kUserEmailTertiary);
  LoginScreenFocusAccount(third_account);
  ExpectAmbientLightSensorEnabled(true,
                                  "ALS should be enabled for third user "
                                  "despite being disabled for first user.");
  ExpectBrightnessPercent(
      first_brightness_change_percent,
      "Brightness should remain the same after switching to the second user.");

  // Set the brightness for the third user.
  const double second_brightness_change_percent = 77.0;
  brightness_control_delegate()->SetBrightnessPercent(
      second_brightness_change_percent, /*gradual=*/false,
      BrightnessControlDelegate::BrightnessChangeSource::kQuickSettings);
  // Wait for callbacks to finish executing.
  run_loop_.RunUntilIdle();

  ExpectAmbientLightSensorEnabled(
      false, "ALS should be disabled for third user after brightness change.");
  ExpectBrightnessPercent(
      second_brightness_change_percent,
      "Brightness for the third user should be equal to the last-set value.");

  LoginScreenFocusAccount(first_account);
  ExpectAmbientLightSensorEnabled(false,
                                  "ALS should be disabled for first user after "
                                  "switching back from second user.");
  ExpectBrightnessPercent(
      first_brightness_change_percent,
      "Brightness should be equal to the previously-set value for the first "
      "user, even after focusing the second user.");

  LoginScreenFocusAccount(third_account);
  ExpectAmbientLightSensorEnabled(false,
                                  "ALS should be disabled for third user after "
                                  "switching back from first user.");
  ExpectBrightnessPercent(
      second_brightness_change_percent,
      "Brightness should be restored to the previously-set value for the third "
      "user, even after focusing the first user (which has its own set "
      "brightness value).");

  // Simulate a reboot, which resets the value of the ambient light sensor and
  // the screen brightness.
  ClearLogin();
  request.set_sensor_enabled(true);
  power_manager_client()->SetAmbientLightSensorEnabled(request);
  power_manager_client()->set_screen_brightness_percent(kInitialBrightness);

  LoginScreenFocusAccount(second_account);
  ExpectAmbientLightSensorEnabled(
      true, "After reboot, ALS should be still be enabled for second user.");
  ExpectBrightnessPercent(kInitialBrightness,
                          "After reboot, brightness should be equal to the "
                          "initial value for the second user.");

  LoginScreenFocusAccount(first_account);
  ExpectAmbientLightSensorEnabled(
      false, "After reboot, ALS should be still be disabled for first user.");
  ExpectBrightnessPercent(first_brightness_change_percent,
                          "After reboot, brightness should be equal to the "
                          "previously-set value for the first user.");

  LoginScreenFocusAccount(second_account);
  ExpectAmbientLightSensorEnabled(
      true, "After reboot, ALS should be still be enabled for second user.");
  ExpectBrightnessPercent(first_brightness_change_percent,
                          "After switching to the second user (after reboot), "
                          "brightness should be equal to the "
                          "last value set (since auto-brightness is enabled).");

  LoginScreenFocusAccount(first_account);
  ExpectAmbientLightSensorEnabled(
      false,
      "After reboot and after switching back from second user, ALS should be "
      "still be disabled for first user.");
  ExpectBrightnessPercent(
      first_brightness_change_percent,
      "After reboot, brightness should be equal to the previously-set value "
      "for the first user, even after focusing the second user.");

  LoginScreenFocusAccount(third_account);
  ExpectAmbientLightSensorEnabled(
      false, "After reboot, ALS should be still be disabled for third user.");
  ExpectBrightnessPercent(second_brightness_change_percent,
                          "After reboot, brightness should be equal to the "
                          "previously-set value for the third user, even after "
                          "focusing the first user.");
}

TEST_F(BrightnessControllerChromeosTest,
       RestoreBrightnessSettingsFromPref_FlagDisabled) {
  scoped_feature_list_.InitAndDisableFeature(
      features::kEnableBrightnessControlInSettings);

  // Set initial ALS status and brightness level.
  power_manager::SetAmbientLightSensorEnabledRequest request;
  request.set_sensor_enabled(true);
  power_manager_client()->SetAmbientLightSensorEnabled(request);
  power_manager_client()->set_screen_brightness_percent(kInitialBrightness);
  run_loop_.RunUntilIdle();

  // Clear user sessions and reset to the primary login screen.
  ClearLogin();

  // On the login screen, focus the first user.
  AccountId first_account = AccountId::FromUserEmail(kUserEmail);
  LoginScreenFocusAccount(first_account);
  ExpectAmbientLightSensorEnabled(
      true, "ALS should be enabled for first user by default.");
  ExpectBrightnessPercent(
      kInitialBrightness,
      "Brightness should be unchanged for first user after initial focus.");

  // Then, focus the second user.
  AccountId second_account = AccountId::FromUserEmail(kUserEmailSecondary);
  LoginScreenFocusAccount(second_account);
  ExpectAmbientLightSensorEnabled(
      true, "ALS should be enabled for second user by default.");
  ExpectBrightnessPercent(
      kInitialBrightness,
      "Brightness should be unchanged for second user after initial focus.");

  // Switch back to the first user, then disable ALS by changing the brightness.
  LoginScreenFocusAccount(first_account);
  const double brightness_change_percent = 12.0;
  brightness_control_delegate()->SetBrightnessPercent(
      brightness_change_percent, /*gradual=*/false,
      BrightnessControlDelegate::BrightnessChangeSource::kQuickSettings);
  // Wait for callbacks to finish executing.
  run_loop_.RunUntilIdle();
  ExpectAmbientLightSensorEnabled(
      false, "ALS should be disabled for first user after brightness change.");
  ExpectBrightnessPercent(brightness_change_percent,
                          "Brightness should be equal to the previously-set "
                          "value for the first user.");

  LoginScreenFocusAccount(second_account);
  ExpectAmbientLightSensorEnabled(
      false,
      "ALS should be disabled for second user because the ALS value is not "
      "being restored from prefs.");
  ExpectBrightnessPercent(brightness_change_percent,
                          "After switching to the second user, the previous "
                          "brightness should not be restored.");

  LoginScreenFocusAccount(first_account);
  ExpectAmbientLightSensorEnabled(false,
                                  "ALS should be disabled for first user after "
                                  "switching back from second user.");
  ExpectBrightnessPercent(brightness_change_percent,
                          "After switching back to the first user, the "
                          "previous brightness should not be restored.");

  // Simulate a reboot, which resets the value of the ambient light sensor and
  // the screen brightness.
  ClearLogin();
  request.set_sensor_enabled(true);
  power_manager_client()->SetAmbientLightSensorEnabled(request);
  power_manager_client()->set_screen_brightness_percent(kInitialBrightness);

  LoginScreenFocusAccount(first_account);
  ExpectAmbientLightSensorEnabled(
      true, "After reboot, ALS should be enabled for first user by default.");
  ExpectBrightnessPercent(kInitialBrightness,
                          "After reboot, the brightness level should be equal "
                          "to the initial brightness for the first user.");

  LoginScreenFocusAccount(second_account);
  ExpectAmbientLightSensorEnabled(
      true, "After reboot, ALS should be enabled for second user by default.");
  ExpectBrightnessPercent(kInitialBrightness,
                          "After reboot, the brightness level should be equal "
                          "to the initial brightness for the second user.");

  LoginScreenFocusAccount(first_account);
  ExpectAmbientLightSensorEnabled(
      true, "After reboot, ALS should be enabled for first user by default.");
  ExpectBrightnessPercent(kInitialBrightness,
                          "After reboot, the brightness level should be equal "
                          "to the initial brightness for the first user (after "
                          "switching from the second user).");
}

TEST_F(BrightnessControllerChromeosTest,
       ReenableAmbientLightSensor_Reboot_DisabledFromSettingsApp) {
  scoped_feature_list_.InitAndEnableFeature(
      features::kEnableBrightnessControlInSettings);

  // Set initial ALS status and brightness level.
  power_manager::SetAmbientLightSensorEnabledRequest request;
  request.set_sensor_enabled(true);
  power_manager_client()->SetAmbientLightSensorEnabled(request);
  power_manager_client()->set_screen_brightness_percent(kInitialBrightness);
  run_loop_.RunUntilIdle();

  // Log in
  ClearLogin();
  AccountId account_id = AccountId::FromUserEmail(kUserEmail);
  user_manager::KnownUser known_user(local_state());
  SimulateUserLogin({kUserEmail});

  // Set ALS to false, and set the disabled reason to be
  // USER_REQUEST_SETTINGS_APP.
  SetAmbientLightSensorEnabled(
      false,
      power_manager::AmbientLightSensorChange_Cause_USER_REQUEST_SETTINGS_APP);
  known_user.SetPath(
      account_id, prefs::kAmbientLightSensorDisabledReason,
      std::make_optional<base::Value>(
          power_manager::
              AmbientLightSensorChange_Cause_USER_REQUEST_SETTINGS_APP));

  // ALS is disabled.
  ExpectAmbientLightSensorEnabled(
      false,
      "Ambient light sensor is disabled, the request is from settings app.");
  EXPECT_EQ(false, GetDisplayAmbientLightSensorEnabledPrefValue(known_user,
                                                                account_id));

  // "disabled reason" pref stored in KnownUser should be
  // USER_REQUEST_SETTINGS_APP.
  EXPECT_TRUE(
      HasAmbientLightSensorDisabledReasonPrefValue(known_user, account_id));
  EXPECT_EQ(
      power_manager::AmbientLightSensorChange_Cause_USER_REQUEST_SETTINGS_APP,
      GetAmbientLightSensorDisabledReasonPrefValue(known_user, account_id));

  // Simulate reboot, and log in again.
  GetSessionControllerClient()->SetSessionState(
      session_manager::SessionState::LOGIN_PRIMARY);
  known_user.SetPath(account_id, prefs::kInternalDisplayScreenBrightnessPercent,
                     std::make_optional<base::Value>(30.0));
  login_data_dispatcher()->NotifyFocusPod(account_id);

  // Expect ambient light sensor remain disabled, and brightness should be
  // restored.
  ExpectAmbientLightSensorEnabled(false, "ALS remain disabled");
  ExpectBrightnessPercent(30.0, "Brightness percent should be restored.");

  // Simulate reboot, and log in the third time.
  GetSessionControllerClient()->SetSessionState(
      session_manager::SessionState::LOGIN_PRIMARY);
  login_data_dispatcher()->NotifyFocusPod(account_id);

  // ALS and brightness should remain the same as last reboot.
  ExpectAmbientLightSensorEnabled(false, "ALS should remain disabled.");
  ExpectBrightnessPercent(30.0, "Brightness percent should be restored.");
}
TEST_F(BrightnessControllerChromeosTest,
       ReenableAmbientLightSensor_Reboot_DisabledFromBrightnessKey) {
  scoped_feature_list_.InitAndEnableFeature(
      features::kEnableBrightnessControlInSettings);

  // Set initial ALS status and brightness level.
  power_manager::SetAmbientLightSensorEnabledRequest request;
  request.set_sensor_enabled(true);
  power_manager_client()->SetAmbientLightSensorEnabled(request);
  power_manager_client()->set_screen_brightness_percent(kInitialBrightness);
  run_loop_.RunUntilIdle();

  // Log in
  ClearLogin();
  AccountId account_id = AccountId::FromUserEmail(kUserEmail);
  user_manager::KnownUser known_user(local_state());
  SimulateUserLogin({kUserEmail});

  // Set ALS to false, and set the disabled reason to be
  // BRIGHTNESS_USER_REQUEST.
  SetAmbientLightSensorEnabled(
      false,
      power_manager::AmbientLightSensorChange_Cause_BRIGHTNESS_USER_REQUEST);
  known_user.SetPath(
      account_id, prefs::kAmbientLightSensorDisabledReason,
      std::make_optional<base::Value>(
          power_manager::
              AmbientLightSensorChange_Cause_BRIGHTNESS_USER_REQUEST));

  // ALS is disabled.
  ExpectAmbientLightSensorEnabled(
      false,
      "Ambient light sensor is disabled, the request is from settings app.");
  EXPECT_EQ(false, GetDisplayAmbientLightSensorEnabledPrefValue(known_user,
                                                                account_id));

  // "disabled reason" pref stored in KnownUser should be
  // BRIGHTNESS_USER_REQUEST.
  EXPECT_TRUE(
      HasAmbientLightSensorDisabledReasonPrefValue(known_user, account_id));
  EXPECT_EQ(
      power_manager::AmbientLightSensorChange_Cause_BRIGHTNESS_USER_REQUEST,
      GetAmbientLightSensorDisabledReasonPrefValue(known_user, account_id));

  // Simulate reboot, and log in again.
  GetSessionControllerClient()->SetSessionState(
      session_manager::SessionState::LOGIN_PRIMARY);
  known_user.SetPath(account_id, prefs::kInternalDisplayScreenBrightnessPercent,
                     std::make_optional<base::Value>(30.0));
  login_data_dispatcher()->NotifyFocusPod(account_id);

  // Expect ambient light sensor is re-enabled.
  ExpectAmbientLightSensorEnabled(true, "ALS is re-enabled.");

  // Simulate reboot, and log in the third time.
  GetSessionControllerClient()->SetSessionState(
      session_manager::SessionState::LOGIN_PRIMARY);
  login_data_dispatcher()->NotifyFocusPod(account_id);

  // ALS should remain enabled.
  ExpectAmbientLightSensorEnabled(
      true, "ALS should remain enabled after re-enabled in last reboot.");
}

TEST_F(BrightnessControllerChromeosTest,
       BrightnessSettingsUnchanged_DeviceLocked) {
  scoped_feature_list_.InitAndEnableFeature(
      features::kEnableBrightnessControlInSettings);

  // Set initial ALS status and brightness level.
  power_manager::SetAmbientLightSensorEnabledRequest request;
  request.set_sensor_enabled(true);
  power_manager_client()->SetAmbientLightSensorEnabled(request);
  power_manager_client()->set_screen_brightness_percent(kInitialBrightness);
  run_loop_.RunUntilIdle();

  // Log in
  ClearLogin();
  AccountId account_id = AccountId::FromUserEmail(kUserEmail);
  user_manager::KnownUser known_user(local_state());
  SimulateUserLogin({kUserEmail});

  // Disable ALS using the brightness key.
  SetAmbientLightSensorEnabled(
      false,
      power_manager::AmbientLightSensorChange_Cause_BRIGHTNESS_USER_REQUEST);

  // Current status: Als is turned off, and current brightness is
  // kInitialBrightness.
  ExpectAmbientLightSensorEnabled(
      false,
      "Ambient light sensor is disabled, the request is from brightness key.");
  ExpectBrightnessPercent(kInitialBrightness,
                          "Current brightness should be kInitialBrightness.");

  // Simulate device lock and re-login.
  GetSessionControllerClient()->SetSessionState(
      session_manager::SessionState::ACTIVE);
  login_data_dispatcher()->NotifyFocusPod(account_id);

  // Als should not be re-enabled, although it was not previously disabled from
  // settings app. The brightness percent should still be kInitialBrightness.
  ExpectAmbientLightSensorEnabled(false, "ALS remain disabled.");
  ExpectBrightnessPercent(kInitialBrightness,
                          "Brightness should remain unchanged.");
}

TEST_F(BrightnessControllerChromeosTest,
       RestoreAutoBrightnessForNewUser_FlagEnabled) {
  scoped_feature_list_.InitAndEnableFeature(
      features::kEnableBrightnessControlInSettings);

  // Set initial ALS status and brightness level.
  power_manager::SetAmbientLightSensorEnabledRequest request;
  request.set_sensor_enabled(true);
  power_manager_client()->SetAmbientLightSensorEnabled(request);
  power_manager_client()->set_screen_brightness_percent(kInitialBrightness);
  run_loop_.RunUntilIdle();

  // Clear user sessions and reset to the primary login screen.
  ClearLogin();

  // On the login screen, select and login with an existing user.
  AccountId account_id = AccountId::FromUserEmail(kUserEmail);
  login_data_dispatcher()->NotifyFocusPod(account_id);
  LoginScreenFocusAccount(account_id);
  SimulateUserLogin({kUserEmail});

  // The ambient light sensor should be enabled by default.
  ExpectAmbientLightSensorEnabled(
      true, "Ambient light sensor should be enabled by default.");

  // Verify that the synced ambient light sensor profile pref value has a
  // default value of true.
  EXPECT_TRUE(
      Shell::Get()->session_controller()->GetActivePrefService()->GetBoolean(
          prefs::kDisplayAmbientLightSensorLastEnabled));
  // There should not be a KnownUser pref set initially because there hasn't
  // been a change to the ambient light sensor status yet.
  user_manager::KnownUser known_user(local_state());
  EXPECT_FALSE(
      HasDisplayAmbientLightSensorEnabledPrefValue(known_user, account_id));

  // Disable the ambient light sensor by manually changing the brightness.
  brightness_control_delegate()->HandleBrightnessDown();
  // Wait for AmbientLightSensorEnabledChange observer to be notified.
  run_loop_.RunUntilIdle();

  ExpectAmbientLightSensorEnabled(
      false,
      "Ambient light sensor should be disabled for first user after manually "
      "changing the brightness.");

  // After the ambient light sensor status is disabled, the KnownUser pref
  // should be stored with the correct value (false).
  EXPECT_TRUE(
      HasDisplayAmbientLightSensorEnabledPrefValue(known_user, account_id));
  EXPECT_FALSE(
      GetDisplayAmbientLightSensorEnabledPrefValue(known_user, account_id));
  // The synced profile pref should also have the correct value (false).
  EXPECT_FALSE(
      Shell::Get()->session_controller()->GetActivePrefService()->GetBoolean(
          prefs::kDisplayAmbientLightSensorLastEnabled));

  // Simulate a reboot, which resets the value of the ambient light sensor and
  // the screen brightness.
  ClearLogin();
  request.set_sensor_enabled(true);
  power_manager_client()->SetAmbientLightSensorEnabled(request);
  power_manager_client()->set_screen_brightness_percent(kInitialBrightness);

  // Simulate a login with a second user, as if it's that user's first time
  // logging in on this device.
  SimulateNewUserFirstLogin(kUserEmailSecondary);

  // The value of the synced profile pref for the ambient light sensor should be
  // true by default, and the ambient light sensor should be enabled.
  EXPECT_TRUE(
      Shell::Get()->session_controller()->GetActivePrefService()->GetBoolean(
          prefs::kDisplayAmbientLightSensorLastEnabled));
  ExpectAmbientLightSensorEnabled(
      true, "Ambient light sensor should be enabled for new users.");

  // Before logging in the first user, manually set the synced pref to false to
  // simulate the pref finishing syncing to the new device.
  PrefService* pref_service =
      Shell::Get()->session_controller()->GetActivePrefService();
  pref_service->SetBoolean(prefs::kDisplayAmbientLightSensorLastEnabled, false);

  // Now, login the first user again, as if it's that user's first time
  // logging in on this device.
  SimulateNewUserFirstLogin(kUserEmail);

  // The value of the synced profile pref for the ambient light sensor should be
  // false, because on the "other device" that value was set to false.
  EXPECT_FALSE(
      Shell::Get()->session_controller()->GetActivePrefService()->GetBoolean(
          prefs::kDisplayAmbientLightSensorLastEnabled));
  // As a result, the local state pref for ambient light sensor status should be
  // disabled, and the ambient light sensor should be disabled.
  EXPECT_TRUE(
      HasDisplayAmbientLightSensorEnabledPrefValue(known_user, account_id));
  EXPECT_FALSE(
      GetDisplayAmbientLightSensorEnabledPrefValue(known_user, account_id));
  ExpectAmbientLightSensorEnabled(
      false,
      "Ambient light sensor should be disabled for first user after logging in "
      "from a new device.");
}

TEST_F(BrightnessControllerChromeosTest,
       RestoreAutoBrightnessForNewUser_FlagDisabled) {
  scoped_feature_list_.InitAndDisableFeature(
      features::kEnableBrightnessControlInSettings);

  // Set initial ALS status and brightness level.
  power_manager::SetAmbientLightSensorEnabledRequest request;
  request.set_sensor_enabled(true);
  power_manager_client()->SetAmbientLightSensorEnabled(request);
  power_manager_client()->set_screen_brightness_percent(kInitialBrightness);
  run_loop_.RunUntilIdle();

  // Clear user sessions and reset to the primary login screen.
  ClearLogin();

  // On the login screen, select and login with an existing user.
  AccountId account_id = AccountId::FromUserEmail(kUserEmail);
  login_data_dispatcher()->NotifyFocusPod(account_id);
  LoginScreenFocusAccount(account_id);
  SimulateUserLogin({kUserEmail});

  // The ambient light sensor should be enabled by default.
  ExpectAmbientLightSensorEnabled(
      true, "Ambient light sensor should be enabled by default.");

  // Verify that the synced ambient light sensor profile pref value has a
  // default value of true.
  EXPECT_TRUE(
      Shell::Get()->session_controller()->GetActivePrefService()->GetBoolean(
          prefs::kDisplayAmbientLightSensorLastEnabled));
  // There should not be a KnownUser pref set initially because there hasn't
  // been a change to the ambient light sensor status yet.
  user_manager::KnownUser known_user(local_state());
  EXPECT_FALSE(
      HasDisplayAmbientLightSensorEnabledPrefValue(known_user, account_id));

  // Disable the ambient light sensor by manually changing the brightness.
  brightness_control_delegate()->HandleBrightnessDown();
  // Wait for AmbientLightSensorEnabledChange observer to be notified.
  run_loop_.RunUntilIdle();

  ExpectAmbientLightSensorEnabled(
      false,
      "Ambient light sensor should be disabled for first user after manually "
      "changing the brightness.");

  // After the ambient light sensor status is disabled, the KnownUser pref
  // should be stored with the correct value (false).
  EXPECT_TRUE(
      HasDisplayAmbientLightSensorEnabledPrefValue(known_user, account_id));
  EXPECT_FALSE(
      GetDisplayAmbientLightSensorEnabledPrefValue(known_user, account_id));
  // The synced profile pref should also have the correct value (false).
  EXPECT_FALSE(
      Shell::Get()->session_controller()->GetActivePrefService()->GetBoolean(
          prefs::kDisplayAmbientLightSensorLastEnabled));

  // Simulate a reboot, which resets the value of the ambient light sensor and
  // the screen brightness.
  ClearLogin();
  request.set_sensor_enabled(true);
  power_manager_client()->SetAmbientLightSensorEnabled(request);
  power_manager_client()->set_screen_brightness_percent(kInitialBrightness);

  // Simulate a login with a second user, as if it's that user's first time
  // logging in on this device.
  SimulateNewUserFirstLogin(kUserEmailSecondary);

  // The value of the synced profile pref for the ambient light sensor should be
  // true by default, and the ambient light sensor should be enabled.
  EXPECT_TRUE(
      Shell::Get()->session_controller()->GetActivePrefService()->GetBoolean(
          prefs::kDisplayAmbientLightSensorLastEnabled));
  ExpectAmbientLightSensorEnabled(
      true, "Ambient light sensor should be enabled for new users.");

  // Before logging in the first user, manually set the synced pref to false to
  // simulate the pref finishing syncing to the new device.
  PrefService* pref_service =
      Shell::Get()->session_controller()->GetActivePrefService();
  pref_service->SetBoolean(prefs::kDisplayAmbientLightSensorLastEnabled, false);

  // Now, login the first user again, as if it's that user's first time
  // logging in on this device.
  SimulateNewUserFirstLogin(kUserEmail);

  // The value of the synced profile pref for the ambient light sensor should be
  // false, because on the "other device" that value was set to false.
  EXPECT_FALSE(
      Shell::Get()->session_controller()->GetActivePrefService()->GetBoolean(
          prefs::kDisplayAmbientLightSensorLastEnabled));
  // However, because the brightness-control flag is disabled, the ambient light
  // sensor preference will not be restored, and thus the ambient light sensor
  // should be disabled.
  ExpectAmbientLightSensorEnabled(
      true,
      "Ambient light sensor should be enabled for first user after logging in "
      "from a new device.");
}

TEST_F(BrightnessControllerChromeosTest,
       RestoreBrightnessSettings_ScreenBrightnessPercentPolicySet) {
  scoped_feature_list_.InitAndEnableFeature(
      features::kEnableBrightnessControlInSettings);

  // Set initial ALS status and brightness level.
  power_manager::SetAmbientLightSensorEnabledRequest request;
  request.set_sensor_enabled(true);
  power_manager_client()->SetAmbientLightSensorEnabled(request);
  power_manager_client()->set_screen_brightness_percent(kInitialBrightness);
  run_loop_.RunUntilIdle();

  // Log in
  ClearLogin();
  AccountId account_id = AccountId::FromUserEmail(kUserEmail);
  user_manager::KnownUser known_user(local_state());
  SimulateUserLogin({kUserEmail});

  // Set brightness to 100%.
  SetAmbientLightSensorEnabled(
      false,
      power_manager::AmbientLightSensorChange_Cause_USER_REQUEST_SETTINGS_APP);
  SetBrightness(100.0,
                power_manager::BacklightBrightnessChange_Cause_USER_REQUEST);
  ExpectBrightnessPercent(100.0, "Brightness should be set to 100.");

  // Manually set known_user's saved brightness to 10%.
  known_user.SetPath(account_id, prefs::kInternalDisplayScreenBrightnessPercent,
                     std::make_optional<base::Value>(10.0));
  EXPECT_EQ(GetBrightnessPrefValue(known_user, account_id), 10.0);

  // Simulate reboot.
  GetSessionControllerClient()->SetSessionState(
      session_manager::SessionState::LOGIN_PRIMARY);
  LoginScreenFocusAccount(account_id);

  // Expect the brightness is restored to 10%.
  ExpectBrightnessPercent(10, "Brightness should be set to 10.");
}

TEST_F(BrightnessControllerChromeosTest,
       RestoreBrightnessSettings_ScreenBrightnessPercentPolicyUnset) {
  scoped_feature_list_.InitAndEnableFeature(
      features::kEnableBrightnessControlInSettings);

  // Set initial ALS status and brightness level.
  power_manager::SetAmbientLightSensorEnabledRequest request;
  request.set_sensor_enabled(true);
  power_manager_client()->SetAmbientLightSensorEnabled(request);
  power_manager_client()->set_screen_brightness_percent(kInitialBrightness);
  run_loop_.RunUntilIdle();

  // Log in
  ClearLogin();
  AccountId account_id = AccountId::FromUserEmail(kUserEmail);
  user_manager::KnownUser known_user(local_state());
  SimulateUserLogin({kUserEmail});

  // Set brightness to 100%.
  SetAmbientLightSensorEnabled(
      false,
      power_manager::AmbientLightSensorChange_Cause_USER_REQUEST_SETTINGS_APP);
  SetBrightness(100.0,
                power_manager::BacklightBrightnessChange_Cause_USER_REQUEST);
  ExpectBrightnessPercent(100.0, "Brightness should be set to 100.");

  // Manually set known_user's saved brightness to 10%.
  known_user.SetPath(account_id, prefs::kInternalDisplayScreenBrightnessPercent,
                     std::make_optional<base::Value>(10.0));
  EXPECT_EQ(GetBrightnessPrefValue(known_user, account_id), 10.0);

  // This time, set the brightness managed by policy to be true.
  PrefService* prefs =
      Shell::Get()->session_controller()->GetLastActiveUserPrefService();
  static_cast<TestingPrefServiceSimple*>(prefs)->SetManagedPref(
      prefs::kPowerBatteryScreenBrightnessPercent,
      std::make_unique<base::Value>(true));
  EXPECT_TRUE(
      prefs->IsManagedPreference(prefs::kPowerBatteryScreenBrightnessPercent));

  // "Unplug" the device from charger
  SetBatteryPower();

  // Simulate reboot, and log in.
  GetSessionControllerClient()->SetSessionState(
      session_manager::SessionState::LOGIN_PRIMARY);
  SimulateUserLogin({kUserEmail});

  // Expect the brightness is not restored to 10%.
  brightness_control_delegate()->GetBrightnessPercent(
      base::BindLambdaForTesting([](std::optional<double> brightness_percent) {
        EXPECT_NE(brightness_percent.value(), 10.0);
      }));
}

TEST_F(BrightnessControllerChromeosTest,
       RecordStartupAmbientLightSensorStatus) {
  scoped_feature_list_.InitAndEnableFeature(
      features::kEnableBrightnessControlInSettings);
  histogram_tester_->ExpectTotalCount(
      "ChromeOS.Display.Startup.AmbientLightSensorEnabled", 0);

  // Set ALS and sensor status.
  power_manager::SetAmbientLightSensorEnabledRequest request;
  request.set_sensor_enabled(true);
  power_manager_client()->SetAmbientLightSensorEnabled(request);
  power_manager_client()->set_has_ambient_light_sensor(true);
  run_loop_.RunUntilIdle();

  // Log in.
  ClearLogin();
  AccountId first_account = AccountId::FromUserEmail(kUserEmail);
  LoginScreenFocusAccount(first_account);
  histogram_tester_->ExpectBucketCount(
      "ChromeOS.Display.Startup.AmbientLightSensorEnabled", true, 1);

  // Log in again, expect no extra metric is emitted.
  ClearLogin();
  LoginScreenFocusAccount(first_account);
  histogram_tester_->ExpectTotalCount(
      "ChromeOS.Display.Startup.AmbientLightSensorEnabled", 1);
}

TEST_F(BrightnessControllerChromeosTest, RestoreBrightnessSettings_NoSensor) {
  // Test case: Disable ALS via brightness key and restore brightness settings.
  // When the device has no sensor. ALS should not be re-enabled after login.
  scoped_feature_list_.InitAndEnableFeature(
      features::kEnableBrightnessControlInSettings);

  // Set initial ALS status and brightness level.
  power_manager::SetAmbientLightSensorEnabledRequest request;
  request.set_sensor_enabled(true);
  power_manager_client()->SetAmbientLightSensorEnabled(request);
  power_manager_client()->set_screen_brightness_percent(kInitialBrightness);

  // Log in
  ClearLogin();
  AccountId account_id = AccountId::FromUserEmail(kUserEmail);
  user_manager::KnownUser known_user(local_state());
  SimulateUserLogin({kUserEmail});

  // Disable ALS
  SetAmbientLightSensorEnabled(
      false,
      power_manager::AmbientLightSensorChange_Cause_BRIGHTNESS_USER_REQUEST);
  ExpectAmbientLightSensorEnabled(false, "ALS is disabled.");

  // Set the device to have no ambient light sensor.
  power_manager_client()->set_has_ambient_light_sensor(false);

  // Reinitialize controller to apply updates.
  auto controller = std::make_unique<system::BrightnessControllerChromeos>(
      local_state(), Shell::Get()->session_controller());
  run_loop_.RunUntilIdle();

  // Before reboot, set saved prefs: ALS disabled
  // reason (BRIGHTNESS_USER_REQUEST) and brightness percent (30.0).
  known_user.SetPath(
      account_id, prefs::kAmbientLightSensorDisabledReason,
      std::make_optional<base::Value>(
          power_manager::
              AmbientLightSensorChange_Cause_BRIGHTNESS_USER_REQUEST));
  known_user.SetPath(account_id, prefs::kInternalDisplayScreenBrightnessPercent,
                     std::make_optional<base::Value>(30.0));

  // Simulate reboot, and log in again.
  GetSessionControllerClient()->SetSessionState(
      session_manager::SessionState::LOGIN_PRIMARY);
  login_data_dispatcher()->NotifyFocusPod(account_id);

  // Verify ALS is not re-enabled, brightness percent is restored to 30.0.
  ExpectAmbientLightSensorEnabled(false, "ALS is not re-enabled.");
  ExpectBrightnessPercent(30.0, "brighntess is restored");
}

TEST_F(BrightnessControllerChromeosTest, RestoreBrightnessSettings_HasSensor) {
  // Test case: Disable ALS via brightness key and restore brightness settings.
  // When the device has a sensor. ALS should be re-enabled after login.
  scoped_feature_list_.InitAndEnableFeature(
      features::kEnableBrightnessControlInSettings);

  // Set initial ALS status and brightness level.
  power_manager::SetAmbientLightSensorEnabledRequest request;
  request.set_sensor_enabled(true);
  power_manager_client()->SetAmbientLightSensorEnabled(request);
  power_manager_client()->set_screen_brightness_percent(kInitialBrightness);

  // Log in
  ClearLogin();
  AccountId account_id = AccountId::FromUserEmail(kUserEmail);
  user_manager::KnownUser known_user(local_state());
  SimulateUserLogin({kUserEmail});

  // Disable ALS
  SetAmbientLightSensorEnabled(
      false,
      power_manager::AmbientLightSensorChange_Cause_BRIGHTNESS_USER_REQUEST);
  ExpectAmbientLightSensorEnabled(false, "ALS is disabled");

  // Set the device to have ambient light sensor.
  power_manager_client()->set_has_ambient_light_sensor(true);

  // Reinitialize controller to apply updates.
  auto controller = std::make_unique<system::BrightnessControllerChromeos>(
      local_state(), Shell::Get()->session_controller());
  run_loop_.RunUntilIdle();

  // Before reboot, set saved prefs: ALS disabled
  // reason (BRIGHTNESS_USER_REQUEST) and brightness percent (30.0).
  known_user.SetPath(
      account_id, prefs::kAmbientLightSensorDisabledReason,
      std::make_optional<base::Value>(
          power_manager::
              AmbientLightSensorChange_Cause_BRIGHTNESS_USER_REQUEST));
  known_user.SetPath(account_id, prefs::kAmbientLightSensorDisabledReason,
                     std::make_optional<base::Value>(30.0));

  // Simulate reboot, and log in again.
  GetSessionControllerClient()->SetSessionState(
      session_manager::SessionState::LOGIN_PRIMARY);
  login_data_dispatcher()->NotifyFocusPod(account_id);

  // Verify ambient light sensor is re-enabled, because als was disabled by
  // brightness key, and the brightness percent should be
  // kInitialKeyboardBrightness instead of 30.0.
  ExpectAmbientLightSensorEnabled(true, "ALS is re-enabled.");
  ExpectBrightnessPercent(kInitialBrightness,
                          "Brightness percent should not be restored.");
}

}  // namespace ash