settings/display/
display_controller.rs

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
// Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

use anyhow::Error;
use serde::{Deserialize, Serialize};

use crate::base::{Merge, SettingInfo, SettingType};
use crate::call;
use crate::config::default_settings::DefaultSetting;
use crate::display::display_configuration::{
    ConfigurationThemeMode, ConfigurationThemeType, DisplayConfiguration,
};
use crate::display::types::{DisplayInfo, LowLightMode, Theme, ThemeBuilder, ThemeMode, ThemeType};
use crate::handler::base::Request;
use crate::handler::setting_handler::persist::{controller as data_controller, ClientProxy};
use crate::handler::setting_handler::{
    controller, ControllerError, IntoHandlerResult, SettingHandlerResult,
};
use crate::service_context::ExternalServiceProxy;
use async_trait::async_trait;
use fidl_fuchsia_ui_brightness::{
    ControlMarker as BrightnessControlMarker, ControlProxy as BrightnessControlProxy,
};
use fuchsia_trace as ftrace;
use settings_storage::device_storage::{DeviceStorage, DeviceStorageCompatible};
use settings_storage::storage_factory::{DefaultLoader, NoneT, StorageAccess};
use settings_storage::UpdateState;
use std::sync::Mutex;

pub(super) const DEFAULT_MANUAL_BRIGHTNESS_VALUE: f32 = 0.5;
pub(super) const DEFAULT_AUTO_BRIGHTNESS_VALUE: f32 = 0.5;

/// Default display used if no configuration is available.
pub(crate) const DEFAULT_DISPLAY_INFO: DisplayInfo = DisplayInfo::new(
    false,                           /*auto_brightness_enabled*/
    DEFAULT_MANUAL_BRIGHTNESS_VALUE, /*manual_brightness_value*/
    DEFAULT_AUTO_BRIGHTNESS_VALUE,   /*auto_brightness_value*/
    true,                            /*screen_enabled*/
    LowLightMode::Disable,           /*low_light_mode*/
    None,                            /*theme*/
);

/// Returns a default display [`DisplayInfo`] that is derived from
/// [`DEFAULT_DISPLAY_INFO`] with any fields specified in the
/// display configuration set.
pub struct DisplayInfoLoader {
    display_configuration: Mutex<DefaultSetting<DisplayConfiguration, &'static str>>,
}

impl DisplayInfoLoader {
    pub(crate) fn new(default_setting: DefaultSetting<DisplayConfiguration, &'static str>) -> Self {
        Self { display_configuration: Mutex::new(default_setting) }
    }
}

impl DefaultLoader for DisplayInfoLoader {
    type Result = DisplayInfo;

    fn default_value(&self) -> Self::Result {
        let mut default_display_info = DEFAULT_DISPLAY_INFO;

        if let Ok(Some(display_configuration)) =
            self.display_configuration.lock().unwrap().get_cached_value()
        {
            default_display_info.theme = Some(Theme {
                theme_type: Some(match display_configuration.theme.theme_type {
                    ConfigurationThemeType::Light => ThemeType::Light,
                }),
                theme_mode: if display_configuration
                    .theme
                    .theme_mode
                    .contains(&ConfigurationThemeMode::Auto)
                {
                    ThemeMode::AUTO
                } else {
                    ThemeMode::empty()
                },
            });
        }

        default_display_info
    }
}

impl DeviceStorageCompatible for DisplayInfo {
    type Loader = DisplayInfoLoader;
    const KEY: &'static str = "display_info";

    fn try_deserialize_from(value: &str) -> Result<Self, Error> {
        Self::extract(value).or_else(|_| DisplayInfoV5::try_deserialize_from(value).map(Self::from))
    }
}

impl From<DisplayInfo> for SettingInfo {
    fn from(info: DisplayInfo) -> SettingInfo {
        SettingInfo::Brightness(info)
    }
}

impl From<DisplayInfoV5> for DisplayInfo {
    fn from(v5: DisplayInfoV5) -> Self {
        DisplayInfo {
            auto_brightness: v5.auto_brightness,
            auto_brightness_value: DEFAULT_AUTO_BRIGHTNESS_VALUE,
            manual_brightness_value: v5.manual_brightness_value,
            screen_enabled: v5.screen_enabled,
            low_light_mode: v5.low_light_mode,
            theme: v5.theme,
        }
    }
}

#[async_trait(?Send)]
pub(crate) trait BrightnessManager: Sized {
    async fn from_client(client: &ClientProxy) -> Result<Self, ControllerError>;
    async fn update_brightness(
        &self,
        info: DisplayInfo,
        client: &ClientProxy,
        // Allows overriding of the check for whether info has changed. This is necessary for
        // the initial restore call.
        always_send: bool,
    ) -> SettingHandlerResult;
}

#[async_trait(?Send)]
impl BrightnessManager for () {
    async fn from_client(_: &ClientProxy) -> Result<Self, ControllerError> {
        Ok(())
    }

    // This does not send the brightness value on anywhere, it simply stores it.
    // External services will pick up the value and set it on the brightness manager.
    async fn update_brightness(
        &self,
        info: DisplayInfo,
        client: &ClientProxy,
        _: bool,
    ) -> SettingHandlerResult {
        let id = ftrace::Id::new();
        if !info.is_finite() {
            return Err(ControllerError::InvalidArgument(
                SettingType::Display,
                "display_info".into(),
                format!("{info:?}").into(),
            ));
        }
        client.write_setting(info.into(), id).await.into_handler_result()
    }
}

pub(crate) struct ExternalBrightnessControl {
    brightness_service: ExternalServiceProxy<BrightnessControlProxy>,
}

#[async_trait(?Send)]
impl BrightnessManager for ExternalBrightnessControl {
    async fn from_client(client: &ClientProxy) -> Result<Self, ControllerError> {
        client
            .get_service_context()
            .connect::<BrightnessControlMarker>()
            .await
            .map(|brightness_service| Self { brightness_service })
            .map_err(|_| {
                ControllerError::InitFailure("could not connect to brightness service".into())
            })
    }

    async fn update_brightness(
        &self,
        info: DisplayInfo,
        client: &ClientProxy,
        always_send: bool,
    ) -> SettingHandlerResult {
        let id = ftrace::Id::new();
        if !info.is_finite() {
            return Err(ControllerError::InvalidArgument(
                SettingType::Display,
                "display_info".into(),
                format!("{info:?}").into(),
            ));
        }
        let update_state = client.write_setting(info.into(), id).await?;
        if update_state == UpdateState::Unchanged && !always_send {
            return Ok(None);
        }

        if info.auto_brightness {
            call!(self.brightness_service => set_auto_brightness())
        } else {
            call!(self.brightness_service => set_manual_brightness(info.manual_brightness_value))
        }
        .map(|_| None)
        .map_err(|e| {
            ControllerError::ExternalFailure(
                SettingType::Display,
                "brightness_service".into(),
                "set_brightness".into(),
                format!("{e:?}").into(),
            )
        })
    }
}

pub(crate) struct DisplayController<T = ()>
where
    T: BrightnessManager,
{
    client: ClientProxy,
    brightness_manager: T,
}

impl<T> StorageAccess for DisplayController<T>
where
    T: BrightnessManager,
{
    type Storage = DeviceStorage;
    type Data = DisplayInfo;
    const STORAGE_KEY: &'static str = DisplayInfo::KEY;
}

#[async_trait(?Send)]
impl<T> data_controller::Create for DisplayController<T>
where
    T: BrightnessManager,
{
    async fn create(client: ClientProxy) -> Result<Self, ControllerError> {
        let brightness_manager = <T as BrightnessManager>::from_client(&client).await?;
        Ok(Self { client, brightness_manager })
    }
}

#[async_trait(?Send)]
impl<T> controller::Handle for DisplayController<T>
where
    T: BrightnessManager,
{
    async fn handle(&self, request: Request) -> Option<SettingHandlerResult> {
        match request {
            Request::Restore => {
                let display_info = self.client.read_setting::<DisplayInfo>(ftrace::Id::new()).await;
                assert!(display_info.is_finite());

                // Load and set value.
                Some(
                    self.brightness_manager
                        .update_brightness(display_info, &self.client, true)
                        .await,
                )
            }
            Request::SetDisplayInfo(mut set_display_info) => {
                let display_info = self.client.read_setting::<DisplayInfo>(ftrace::Id::new()).await;
                assert!(display_info.is_finite());

                if let Some(theme) = set_display_info.theme {
                    set_display_info.theme = self.build_theme(theme, &display_info);
                }

                Some(
                    self.brightness_manager
                        .update_brightness(
                            display_info.merge(set_display_info),
                            &self.client,
                            false,
                        )
                        .await,
                )
            }
            Request::Get => Some(
                self.client
                    .read_setting_info::<DisplayInfo>(ftrace::Id::new())
                    .await
                    .into_handler_result(),
            ),
            _ => None,
        }
    }
}

impl<T> DisplayController<T>
where
    T: BrightnessManager,
{
    fn build_theme(&self, incoming_theme: Theme, display_info: &DisplayInfo) -> Option<Theme> {
        let existing_theme_type = display_info.theme.and_then(|theme| theme.theme_type);
        let new_theme_type = incoming_theme.theme_type.or(existing_theme_type);

        ThemeBuilder::new()
            .set_theme_type(new_theme_type)
            .set_theme_mode(incoming_theme.theme_mode)
            .build()
    }
}

/// The following struct should never be modified. It represents an old
/// version of the display settings.
#[derive(PartialEq, Debug, Clone, Copy, Serialize, Deserialize)]
pub struct DisplayInfoV1 {
    /// The last brightness value that was manually set.
    pub manual_brightness_value: f32,
    pub auto_brightness: bool,
    pub low_light_mode: LowLightMode,
}

impl DisplayInfoV1 {
    const fn new(
        auto_brightness: bool,
        manual_brightness_value: f32,
        low_light_mode: LowLightMode,
    ) -> DisplayInfoV1 {
        DisplayInfoV1 { manual_brightness_value, auto_brightness, low_light_mode }
    }
}

impl DeviceStorageCompatible for DisplayInfoV1 {
    type Loader = NoneT;
    const KEY: &'static str = "display_infoV1";
}

impl Default for DisplayInfoV1 {
    fn default() -> Self {
        DisplayInfoV1::new(
            false,                           /*auto_brightness_enabled*/
            DEFAULT_MANUAL_BRIGHTNESS_VALUE, /*brightness_value*/
            LowLightMode::Disable,           /*low_light_mode*/
        )
    }
}

/// The following struct should never be modified.  It represents an old
/// version of the display settings.
#[derive(PartialEq, Debug, Clone, Copy, Serialize, Deserialize)]
pub struct DisplayInfoV2 {
    pub manual_brightness_value: f32,
    pub auto_brightness: bool,
    pub low_light_mode: LowLightMode,
    pub theme_mode: ThemeModeV1,
}

impl DisplayInfoV2 {
    const fn new(
        auto_brightness: bool,
        manual_brightness_value: f32,
        low_light_mode: LowLightMode,
        theme_mode: ThemeModeV1,
    ) -> DisplayInfoV2 {
        DisplayInfoV2 { manual_brightness_value, auto_brightness, low_light_mode, theme_mode }
    }
}

impl DeviceStorageCompatible for DisplayInfoV2 {
    type Loader = NoneT;
    const KEY: &'static str = "display_infoV2";

    fn try_deserialize_from(value: &str) -> Result<Self, Error> {
        Self::extract(value).or_else(|_| DisplayInfoV1::try_deserialize_from(value).map(Self::from))
    }
}

impl Default for DisplayInfoV2 {
    fn default() -> Self {
        DisplayInfoV2::new(
            false,                           /*auto_brightness_enabled*/
            DEFAULT_MANUAL_BRIGHTNESS_VALUE, /*brightness_value*/
            LowLightMode::Disable,           /*low_light_mode*/
            ThemeModeV1::Unknown,            /*theme_mode*/
        )
    }
}

impl From<DisplayInfoV1> for DisplayInfoV2 {
    fn from(v1: DisplayInfoV1) -> Self {
        DisplayInfoV2 {
            auto_brightness: v1.auto_brightness,
            manual_brightness_value: v1.manual_brightness_value,
            low_light_mode: v1.low_light_mode,
            theme_mode: ThemeModeV1::Unknown,
        }
    }
}

#[derive(PartialEq, Debug, Clone, Copy, Serialize, Deserialize)]
pub enum ThemeModeV1 {
    Unknown,
    Default,
    Light,
    Dark,
    /// Product can choose a theme based on ambient cues.
    Auto,
}

impl From<ThemeModeV1> for ThemeType {
    fn from(theme_mode_v1: ThemeModeV1) -> Self {
        match theme_mode_v1 {
            ThemeModeV1::Default => ThemeType::Default,
            ThemeModeV1::Light => ThemeType::Light,
            ThemeModeV1::Dark => ThemeType::Dark,
            // ThemeType has removed Auto field, see https://fxbug.dev/42143417
            ThemeModeV1::Unknown | ThemeModeV1::Auto => ThemeType::Unknown,
        }
    }
}

#[derive(PartialEq, Debug, Clone, Copy, Serialize, Deserialize)]
pub struct DisplayInfoV3 {
    /// The last brightness value that was manually set.
    pub manual_brightness_value: f32,
    pub auto_brightness: bool,
    pub screen_enabled: bool,
    pub low_light_mode: LowLightMode,
    pub theme_mode: ThemeModeV1,
}

impl DisplayInfoV3 {
    const fn new(
        auto_brightness: bool,
        manual_brightness_value: f32,
        screen_enabled: bool,
        low_light_mode: LowLightMode,
        theme_mode: ThemeModeV1,
    ) -> DisplayInfoV3 {
        DisplayInfoV3 {
            manual_brightness_value,
            auto_brightness,
            screen_enabled,
            low_light_mode,
            theme_mode,
        }
    }
}

impl DeviceStorageCompatible for DisplayInfoV3 {
    type Loader = NoneT;
    const KEY: &'static str = "display_info";

    fn try_deserialize_from(value: &str) -> Result<Self, Error> {
        Self::extract(value).or_else(|_| DisplayInfoV2::try_deserialize_from(value).map(Self::from))
    }
}

impl Default for DisplayInfoV3 {
    fn default() -> Self {
        DisplayInfoV3::new(
            false,                           /*auto_brightness_enabled*/
            DEFAULT_MANUAL_BRIGHTNESS_VALUE, /*brightness_value*/
            true,                            /*screen_enabled*/
            LowLightMode::Disable,           /*low_light_mode*/
            ThemeModeV1::Unknown,            /*theme_mode*/
        )
    }
}

impl From<DisplayInfoV2> for DisplayInfoV3 {
    fn from(v2: DisplayInfoV2) -> Self {
        DisplayInfoV3 {
            auto_brightness: v2.auto_brightness,
            manual_brightness_value: v2.manual_brightness_value,
            screen_enabled: true,
            low_light_mode: v2.low_light_mode,
            theme_mode: v2.theme_mode,
        }
    }
}

#[derive(PartialEq, Debug, Clone, Copy, Serialize, Deserialize)]
pub struct DisplayInfoV4 {
    /// The last brightness value that was manually set.
    pub manual_brightness_value: f32,
    pub auto_brightness: bool,
    pub screen_enabled: bool,
    pub low_light_mode: LowLightMode,
    pub theme_type: ThemeType,
}

impl DisplayInfoV4 {
    const fn new(
        auto_brightness: bool,
        manual_brightness_value: f32,
        screen_enabled: bool,
        low_light_mode: LowLightMode,
        theme_type: ThemeType,
    ) -> DisplayInfoV4 {
        DisplayInfoV4 {
            manual_brightness_value,
            auto_brightness,
            screen_enabled,
            low_light_mode,
            theme_type,
        }
    }
}

impl From<DisplayInfoV3> for DisplayInfoV4 {
    fn from(v3: DisplayInfoV3) -> Self {
        DisplayInfoV4 {
            auto_brightness: v3.auto_brightness,
            manual_brightness_value: v3.manual_brightness_value,
            screen_enabled: v3.screen_enabled,
            low_light_mode: v3.low_light_mode,
            // In v4, the field formerly known as theme_mode was renamed to
            // theme_type.
            theme_type: ThemeType::from(v3.theme_mode),
        }
    }
}

impl DeviceStorageCompatible for DisplayInfoV4 {
    type Loader = NoneT;
    const KEY: &'static str = "display_info";

    fn try_deserialize_from(value: &str) -> Result<Self, Error> {
        Self::extract(value).or_else(|_| DisplayInfoV3::try_deserialize_from(value).map(Self::from))
    }
}

impl Default for DisplayInfoV4 {
    fn default() -> Self {
        DisplayInfoV4::new(
            false,                           /*auto_brightness_enabled*/
            DEFAULT_MANUAL_BRIGHTNESS_VALUE, /*brightness_value*/
            true,                            /*screen_enabled*/
            LowLightMode::Disable,           /*low_light_mode*/
            ThemeType::Unknown,              /*theme_type*/
        )
    }
}

#[derive(PartialEq, Debug, Clone, Copy, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct DisplayInfoV5 {
    /// The last brightness value that was manually set.
    pub manual_brightness_value: f32,
    pub auto_brightness: bool,
    pub screen_enabled: bool,
    pub low_light_mode: LowLightMode,
    pub theme: Option<Theme>,
}

impl DisplayInfoV5 {
    const fn new(
        auto_brightness: bool,
        manual_brightness_value: f32,
        screen_enabled: bool,
        low_light_mode: LowLightMode,
        theme: Option<Theme>,
    ) -> DisplayInfoV5 {
        DisplayInfoV5 {
            manual_brightness_value,
            auto_brightness,
            screen_enabled,
            low_light_mode,
            theme,
        }
    }
}

impl From<DisplayInfoV4> for DisplayInfoV5 {
    fn from(v4: DisplayInfoV4) -> Self {
        DisplayInfoV5 {
            auto_brightness: v4.auto_brightness,
            manual_brightness_value: v4.manual_brightness_value,
            screen_enabled: v4.screen_enabled,
            low_light_mode: v4.low_light_mode,
            // Clients has migrated off auto theme_type, we should not get theme_type as Auto
            theme: Some(Theme::new(Some(v4.theme_type), ThemeMode::empty())),
        }
    }
}

impl DeviceStorageCompatible for DisplayInfoV5 {
    type Loader = NoneT;
    const KEY: &'static str = "display_info";

    fn try_deserialize_from(value: &str) -> Result<Self, Error> {
        Self::extract(value).or_else(|_| DisplayInfoV4::try_deserialize_from(value).map(Self::from))
    }
}

impl Default for DisplayInfoV5 {
    fn default() -> Self {
        DisplayInfoV5::new(
            false,                                                          /*auto_brightness_enabled*/
            DEFAULT_MANUAL_BRIGHTNESS_VALUE,                                /*brightness_value*/
            true,                                                           /*screen_enabled*/
            LowLightMode::Disable,                                          /*low_light_mode*/
            Some(Theme::new(Some(ThemeType::Unknown), ThemeMode::empty())), /*theme_type*/
        )
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[fuchsia::test]
    fn test_display_migration_v1_to_v2() {
        let v1 = DisplayInfoV1 {
            manual_brightness_value: 0.6,
            auto_brightness: true,
            low_light_mode: LowLightMode::Enable,
        };

        let serialized_v1 = v1.serialize_to();
        let v2 = DisplayInfoV2::try_deserialize_from(&serialized_v1)
            .expect("deserialization should succeed");

        assert_eq!(
            v2,
            DisplayInfoV2 {
                manual_brightness_value: v1.manual_brightness_value,
                auto_brightness: v1.auto_brightness,
                low_light_mode: v1.low_light_mode,
                theme_mode: DisplayInfoV2::default().theme_mode,
            }
        );
    }

    #[fuchsia::test]
    fn test_display_migration_v2_to_v3() {
        let v2 = DisplayInfoV2 {
            manual_brightness_value: 0.7,
            auto_brightness: true,
            low_light_mode: LowLightMode::Enable,
            theme_mode: ThemeModeV1::Default,
        };

        let serialized_v2 = v2.serialize_to();
        let v3 = DisplayInfoV3::try_deserialize_from(&serialized_v2)
            .expect("deserialization should succeed");

        assert_eq!(
            v3,
            DisplayInfoV3 {
                manual_brightness_value: v2.manual_brightness_value,
                auto_brightness: v2.auto_brightness,
                screen_enabled: DisplayInfoV3::default().screen_enabled,
                low_light_mode: v2.low_light_mode,
                theme_mode: v2.theme_mode,
            }
        );
    }

    #[fuchsia::test]
    fn test_display_migration_v3_to_v4() {
        let v3 = DisplayInfoV3 {
            manual_brightness_value: 0.7,
            auto_brightness: true,
            low_light_mode: LowLightMode::Enable,
            theme_mode: ThemeModeV1::Light,
            screen_enabled: false,
        };

        let serialized_v3 = v3.serialize_to();
        let v4 = DisplayInfoV4::try_deserialize_from(&serialized_v3)
            .expect("deserialization should succeed");

        // In v4, the field formally known as theme_mode is theme_type.
        assert_eq!(
            v4,
            DisplayInfoV4 {
                manual_brightness_value: v3.manual_brightness_value,
                auto_brightness: v3.auto_brightness,
                low_light_mode: v3.low_light_mode,
                theme_type: ThemeType::Light,
                screen_enabled: v3.screen_enabled,
            }
        );
    }

    #[fuchsia::test]
    fn test_display_migration_v4_to_v5() {
        let v4 = DisplayInfoV4 {
            manual_brightness_value: 0.7,
            auto_brightness: true,
            low_light_mode: LowLightMode::Enable,
            theme_type: ThemeType::Dark,
            screen_enabled: false,
        };

        let serialized_v4 = v4.serialize_to();
        let v5 = DisplayInfoV5::try_deserialize_from(&serialized_v4)
            .expect("deserialization should succeed");

        assert_eq!(
            v5,
            DisplayInfoV5 {
                manual_brightness_value: v4.manual_brightness_value,
                auto_brightness: v4.auto_brightness,
                low_light_mode: v4.low_light_mode,
                theme: Some(Theme::new(Some(v4.theme_type), ThemeMode::empty())),
                screen_enabled: v4.screen_enabled,
            }
        );
    }

    #[fuchsia::test]
    fn test_display_migration_v1_to_current() {
        let v1 = DisplayInfoV1 {
            manual_brightness_value: 0.6,
            auto_brightness: true,
            low_light_mode: LowLightMode::Enable,
        };

        let serialized_v1 = v1.serialize_to();
        let current = DisplayInfo::try_deserialize_from(&serialized_v1)
            .expect("deserialization should succeed");

        assert_eq!(
            current,
            DisplayInfo {
                manual_brightness_value: v1.manual_brightness_value,
                auto_brightness: v1.auto_brightness,
                low_light_mode: v1.low_light_mode,
                theme: Some(Theme::new(Some(ThemeType::Unknown), ThemeMode::empty())),
                // screen_enabled was added in v3.
                screen_enabled: DisplayInfoV3::default().screen_enabled,
                auto_brightness_value: DEFAULT_DISPLAY_INFO.auto_brightness_value,
            }
        );
    }

    #[fuchsia::test]
    fn test_display_migration_v2_to_current() {
        let v2 = DisplayInfoV2 {
            manual_brightness_value: 0.6,
            auto_brightness: true,
            low_light_mode: LowLightMode::Enable,
            theme_mode: ThemeModeV1::Light,
        };

        let serialized_v2 = v2.serialize_to();
        let current = DisplayInfo::try_deserialize_from(&serialized_v2)
            .expect("deserialization should succeed");

        assert_eq!(
            current,
            DisplayInfo {
                manual_brightness_value: v2.manual_brightness_value,
                auto_brightness: v2.auto_brightness,
                low_light_mode: v2.low_light_mode,
                theme: Some(Theme::new(Some(ThemeType::Light), ThemeMode::empty())),
                // screen_enabled was added in v3.
                screen_enabled: DisplayInfoV3::default().screen_enabled,
                auto_brightness_value: DEFAULT_DISPLAY_INFO.auto_brightness_value,
            }
        );
    }

    #[fuchsia::test]
    fn test_display_migration_v3_to_current() {
        let v3 = DisplayInfoV3 {
            manual_brightness_value: 0.6,
            auto_brightness: true,
            low_light_mode: LowLightMode::Enable,
            theme_mode: ThemeModeV1::Light,
            screen_enabled: false,
        };

        let serialized_v3 = v3.serialize_to();
        let current = DisplayInfo::try_deserialize_from(&serialized_v3)
            .expect("deserialization should succeed");

        assert_eq!(
            current,
            DisplayInfo {
                manual_brightness_value: v3.manual_brightness_value,
                auto_brightness: v3.auto_brightness,
                low_light_mode: v3.low_light_mode,
                theme: Some(Theme::new(Some(ThemeType::Light), ThemeMode::empty())),
                // screen_enabled was added in v3.
                screen_enabled: v3.screen_enabled,
                auto_brightness_value: DEFAULT_DISPLAY_INFO.auto_brightness_value,
            }
        );
    }

    #[fuchsia::test]
    fn test_display_migration_v4_to_current() {
        let v4 = DisplayInfoV4 {
            manual_brightness_value: 0.6,
            auto_brightness: true,
            low_light_mode: LowLightMode::Enable,
            theme_type: ThemeType::Light,
            screen_enabled: false,
        };

        let serialized_v4 = v4.serialize_to();
        let current = DisplayInfo::try_deserialize_from(&serialized_v4)
            .expect("deserialization should succeed");

        assert_eq!(
            current,
            DisplayInfo {
                manual_brightness_value: v4.manual_brightness_value,
                auto_brightness: v4.auto_brightness,
                low_light_mode: v4.low_light_mode,
                theme: Some(Theme::new(Some(ThemeType::Light), ThemeMode::empty())),
                screen_enabled: v4.screen_enabled,
                auto_brightness_value: DEFAULT_DISPLAY_INFO.auto_brightness_value,
            }
        );
    }

    #[fuchsia::test]
    fn test_display_migration_v5_to_current() {
        let v5 = DisplayInfoV5 {
            manual_brightness_value: 0.6,
            auto_brightness: true,
            low_light_mode: LowLightMode::Enable,
            theme: Some(Theme::new(Some(ThemeType::Light), ThemeMode::AUTO)),
            screen_enabled: false,
        };

        let serialized_v5 = v5.serialize_to();
        let current = DisplayInfo::try_deserialize_from(&serialized_v5)
            .expect("deserialization should succeed");

        assert_eq!(
            current,
            DisplayInfo {
                manual_brightness_value: v5.manual_brightness_value,
                auto_brightness: v5.auto_brightness,
                low_light_mode: v5.low_light_mode,
                theme: Some(Theme::new(Some(ThemeType::Light), ThemeMode::AUTO)),
                screen_enabled: v5.screen_enabled,
                auto_brightness_value: DEFAULT_DISPLAY_INFO.auto_brightness_value,
            }
        );
    }
}