settings/input/
types.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
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
// Copyright 2020 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 crate::base::SettingInfo;
use crate::handler::setting_handler::ControllerError;
use crate::input::input_device_configuration::InputConfiguration;
use settings_storage::device_storage::DeviceStorageConvertible;

use anyhow::Error;
use bitflags::bitflags;
use fidl_fuchsia_settings::{
    DeviceState as FidlDeviceState, DeviceStateSource as FidlDeviceStateSource,
    DeviceType as FidlDeviceType, InputDevice as FidlInputDevice,
    InputSettings as FidlInputSettings, SourceState as FidlSourceState,
    ToggleStateFlags as FidlToggleFlags,
};
use serde::{Deserialize, Serialize};
use std::borrow::Cow;
use std::collections::{HashMap, HashSet};
use std::fmt;

impl From<SettingInfo> for FidlInputSettings {
    fn from(response: SettingInfo) -> Self {
        if let SettingInfo::Input(info) = response {
            let mut input_settings = FidlInputSettings::default();
            let mut input_devices: Vec<FidlInputDevice> = Vec::new();

            info.input_device_state.input_categories.iter().for_each(|(_, category)| {
                category.devices.iter().for_each(|(_, device)| {
                    input_devices.push(device.clone().into());
                })
            });

            input_settings.devices = Some(input_devices);
            input_settings
        } else {
            panic!("Incorrect value sent to input");
        }
    }
}

#[derive(PartialEq, Debug, Clone)]
pub struct InputInfo {
    pub input_device_state: InputState,
}

impl DeviceStorageConvertible for InputInfo {
    type Storable = InputInfoSources;

    fn get_storable(&self) -> Cow<'_, Self::Storable> {
        Cow::Owned(InputInfoSources { input_device_state: self.input_device_state.clone() })
    }
}

#[derive(PartialEq, Default, Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct InputInfoSources {
    pub input_device_state: InputState,
}

#[derive(PartialEq, Default, Debug, Clone, Copy, Serialize, Deserialize)]
// DO NOT USE - this type is deprecated and will be replaced by
// the use of InputDevice.
pub struct Microphone {
    pub muted: bool,
}

#[derive(PartialEq, Debug, Default, Clone, Serialize, Deserialize)]
/// The top-level struct for the input state. It categorizes the input devices
/// by their device type.
pub struct InputState {
    /// The input devices categorized by device type.
    pub input_categories: HashMap<InputDeviceType, InputCategory>,
}

impl InputState {
    pub(crate) fn new() -> Self {
        Self::default()
    }

    /// Insert an InputDevice's state into the internal InputState hierarchy, updating the
    /// state if it already exists or adding the state if it does not.
    pub(crate) fn insert_device(&mut self, input_device: InputDevice, source: DeviceStateSource) {
        self.set_source_state(
            input_device.device_type,
            input_device.name,
            source,
            input_device.state,
        );
    }

    /// Set the `state` for a given device and `source`.
    /// The combination of `device_type` and `device_name`
    /// uniquely identifies the device.
    pub(crate) fn set_source_state(
        &mut self,
        device_type: InputDeviceType,
        device_name: String,
        source: DeviceStateSource,
        state: DeviceState,
    ) {
        // Ensure the category has an entry in the categories map.
        let category = self.input_categories.entry(device_type).or_default();

        // Ensure the device has an entry in the devices map.
        let input_device = category
            .devices
            .entry(device_name.clone())
            .or_insert_with(|| InputDevice::new(device_name, device_type));

        // Replace or add the source state in the map. Ignore the old value.
        let _ = input_device.source_states.insert(source, state);
        input_device.compute_input_state();
    }

    /// Retrieve the state of a given device for one of its `source`s.
    /// The combination of `device_type` and `device_name`
    /// uniquely identifies the device. Returns None if it fails to find
    /// the corresponding state for the given arguments.
    pub(crate) fn get_source_state(
        &self,
        device_type: InputDeviceType,
        device_name: String,
        source: DeviceStateSource,
    ) -> Result<DeviceState, Error> {
        Ok(*self
            .input_categories
            .get(&device_type)
            .ok_or_else(|| {
                ControllerError::UnexpectedError(
                    "Failed to get input category by input type".into(),
                )
            })?
            .devices
            .get(&device_name)
            .ok_or_else(|| {
                ControllerError::UnexpectedError("Failed to get input device by device name".into())
            })?
            .source_states
            .get(&source)
            .ok_or_else(|| {
                ControllerError::UnexpectedError("Failed to get state from source states".into())
            })?)
    }

    /// Retrieve the overall state of a given device.
    /// The combination of `device_type` and `device_name`
    /// uniquely identifies the device. Returns None if it fails to find
    /// the corresponding state for the given arguments.
    #[cfg(test)]
    pub(crate) fn get_state(
        &self,
        device_type: InputDeviceType,
        device_name: String,
    ) -> Result<DeviceState, Error> {
        Ok(self
            .input_categories
            .get(&device_type)
            .ok_or_else(|| {
                ControllerError::UnexpectedError(
                    "Failed to get input category by input type".into(),
                )
            })?
            .devices
            .get(&device_name)
            .ok_or_else(|| {
                ControllerError::UnexpectedError("Failed to get input device by device name".into())
            })?
            .state)
    }

    /// Returns true if the state map is empty.
    pub(crate) fn is_empty(&self) -> bool {
        self.input_categories.is_empty()
    }

    /// Returns a set of the `InputDeviceType`s contained in the
    /// state map.
    pub(crate) fn device_types(&self) -> HashSet<InputDeviceType> {
        self.input_categories.keys().cloned().collect()
    }
}

impl From<InputConfiguration> for InputState {
    fn from(config: InputConfiguration) -> Self {
        let mut categories = HashMap::<InputDeviceType, InputCategory>::new();
        let devices = config.devices;

        devices.iter().for_each(|device_config| {
            // Ensure the category has an entry in the categories map.
            let input_device_type = device_config.device_type;
            let category = categories.entry(input_device_type).or_default();

            // Ensure the device has an entry in the devices map.
            let device_name = device_config.device_name.clone();
            let device = category
                .devices
                .entry(device_name.clone())
                .or_insert_with(|| InputDevice::new(device_name, input_device_type));

            // Set the entry on the source states map.
            device_config.source_states.iter().for_each(|source_state| {
                let value = DeviceState::from_bits(source_state.state).unwrap_or_default();
                // Ignore the old value.
                let _ = device.source_states.insert(source_state.source, value);
            });

            // Recompute the overall state.
            device.compute_input_state();
        });
        InputState { input_categories: categories }
    }
}

#[derive(PartialEq, Debug, Default, Clone, Serialize, Deserialize)]
pub struct InputCategory {
    // Map of input devices in this category, identified by names.
    // It is recommended that the name be the lower-case string
    // representation of the device type if there is only one input
    // device in this category.
    pub devices: HashMap<String, InputDevice>,
}

#[derive(PartialEq, Debug, Clone, Serialize, Deserialize)]
pub struct InputDevice {
    /// The unique name within the device type.
    pub name: String,

    /// The type of input device.
    pub device_type: InputDeviceType,

    /// The states for each source.
    pub source_states: HashMap<DeviceStateSource, DeviceState>,

    /// The overall state of the device considering the `source_state`s.
    pub state: DeviceState,
}

impl InputDevice {
    fn new(name: String, device_type: InputDeviceType) -> Self {
        Self {
            name,
            device_type,
            source_states: HashMap::<DeviceStateSource, DeviceState>::new(),
            state: DeviceState::new(),
        }
    }

    fn compute_input_state(&mut self) {
        let mut computed_state = DeviceState::from_bits(0).unwrap();

        for state in self.source_states.values() {
            if state.has_error() {
                computed_state |= DeviceState::ERROR;
            }
            if state.has_state(DeviceState::DISABLED) {
                computed_state |= DeviceState::DISABLED | DeviceState::MUTED;
            }
            if state.has_state(DeviceState::MUTED) {
                computed_state |= DeviceState::MUTED;
            }
            if state.has_state(DeviceState::ACTIVE) {
                computed_state |= DeviceState::ACTIVE | DeviceState::AVAILABLE;
            }
        }

        // If any source has ERROR, DISABLED, MUTED, or ACTIVE, the overall
        // state is that state, in order of precedence. Otherwise, the overall state
        // is AVAILABLE.
        if computed_state.has_error() {
            self.state = DeviceState::ERROR;
        } else if computed_state.has_state(DeviceState::DISABLED) {
            self.state = DeviceState::DISABLED | DeviceState::MUTED;
        } else if computed_state.has_state(DeviceState::MUTED) {
            self.state = DeviceState::MUTED;
        } else if computed_state.has_state(DeviceState::ACTIVE) {
            self.state = DeviceState::ACTIVE | DeviceState::AVAILABLE;
        } else {
            self.state = DeviceState::AVAILABLE;
        }
    }
}

impl From<InputDevice> for FidlInputDevice {
    fn from(device: InputDevice) -> Self {
        let mut result = FidlInputDevice::default();

        // Convert source states.
        let source_states = Some(
            device
                .source_states
                .keys()
                .map(|source| FidlSourceState {
                    source: Some((*source).into()),
                    state: Some(
                        (*device.source_states.get(source).expect("Source state map key missing"))
                            .into(),
                    ),
                    ..Default::default()
                })
                .collect(),
        );

        let mutable_toggle_state: FidlDeviceState =
            DeviceState::default_mutable_toggle_state().into();
        result.device_name = Some(device.name.clone());
        result.device_type = Some(device.device_type.into());
        result.source_states = source_states;
        result.mutable_toggle_state = mutable_toggle_state.toggle_flags;
        result.state = Some(device.state.into());
        result
    }
}

#[derive(PartialEq, Eq, Debug, Copy, Clone, Hash, Serialize, Deserialize)]
#[allow(clippy::upper_case_acronyms)]
pub enum InputDeviceType {
    CAMERA,
    MICROPHONE,
}

/// Instead of defining our own fmt function, an easier way
/// is to derive the 'Display' trait for enums using `enum-display-derive` crate
///
/// <https://docs.rs/enum-display-derive/0.1.0/enum_display_derive/>
///
/// Since addition of this in third_party/rust_crates needs OSRB approval, we
/// define our own function here.
impl fmt::Display for InputDeviceType {
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            InputDeviceType::CAMERA => fmt.write_str("camera"),
            InputDeviceType::MICROPHONE => fmt.write_str("microphone"),
        }
    }
}

impl From<FidlDeviceType> for InputDeviceType {
    fn from(device_type: FidlDeviceType) -> Self {
        match device_type {
            FidlDeviceType::Camera => InputDeviceType::CAMERA,
            FidlDeviceType::Microphone => InputDeviceType::MICROPHONE,
        }
    }
}

impl From<InputDeviceType> for FidlDeviceType {
    fn from(device_type: InputDeviceType) -> Self {
        match device_type {
            InputDeviceType::CAMERA => FidlDeviceType::Camera,
            InputDeviceType::MICROPHONE => FidlDeviceType::Microphone,
        }
    }
}

#[derive(PartialEq, Eq, Debug, Copy, Clone, Hash, Serialize, Deserialize)]
#[allow(clippy::upper_case_acronyms)]
pub enum DeviceStateSource {
    HARDWARE,
    SOFTWARE,
}

impl From<FidlDeviceStateSource> for DeviceStateSource {
    fn from(device_state_source: FidlDeviceStateSource) -> Self {
        match device_state_source {
            FidlDeviceStateSource::Hardware => DeviceStateSource::HARDWARE,
            FidlDeviceStateSource::Software => DeviceStateSource::SOFTWARE,
        }
    }
}

impl From<DeviceStateSource> for FidlDeviceStateSource {
    fn from(device_state_source: DeviceStateSource) -> Self {
        match device_state_source {
            DeviceStateSource::HARDWARE => FidlDeviceStateSource::Hardware,
            DeviceStateSource::SOFTWARE => FidlDeviceStateSource::Software,
        }
    }
}

bitflags! {
    #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
    pub struct DeviceState : u64 {
        const AVAILABLE = 0b00000001;
        const ACTIVE = 0b00000010;
        const MUTED = 0b00000100;
        const DISABLED = 0b00001000;
        const ERROR = 0b00010000;
    }
}

impl Default for DeviceState {
    fn default() -> Self {
        Self::new()
    }
}

impl DeviceState {
    pub(crate) fn new() -> Self {
        // Represents AVAILABLE as the default.
        Self::AVAILABLE
    }

    /// The flags that clients can manipulate by default.
    fn default_mutable_toggle_state() -> Self {
        DeviceState::MUTED | DeviceState::DISABLED
    }

    /// Returns true if the current state contains the given state.
    /// e.g. All the 1 bits in the given `state` are also 1s in the
    /// current state.
    pub(crate) fn has_state(&self, state: DeviceState) -> bool {
        *self & state == state
    }

    /// Returns true if the device's state has an error.
    fn has_error(&self) -> bool {
        let is_err = *self & DeviceState::ERROR == DeviceState::ERROR;
        let incompatible_state = self.has_state(DeviceState::ACTIVE | DeviceState::DISABLED)
            || self.has_state(DeviceState::ACTIVE | DeviceState::MUTED)
            || self.has_state(DeviceState::AVAILABLE | DeviceState::DISABLED)
            || self.has_state(DeviceState::AVAILABLE | DeviceState::MUTED);
        is_err || incompatible_state
    }
}

impl From<FidlDeviceState> for DeviceState {
    fn from(device_state: FidlDeviceState) -> Self {
        if let Some(toggle_flags) = device_state.toggle_flags {
            if let Some(res) = Self::from_bits(toggle_flags.bits()) {
                return res;
            }
        }
        Self::default_mutable_toggle_state()
    }
}

impl From<DeviceState> for FidlDeviceState {
    fn from(device_state: DeviceState) -> Self {
        FidlDeviceState {
            toggle_flags: FidlToggleFlags::from_bits(device_state.bits()),
            ..Default::default()
        }
    }
}

bitflags_serde_legacy::impl_traits!(DeviceState);

#[cfg(test)]
mod tests {
    use super::*;
    use crate::input::input_device_configuration::{InputDeviceConfiguration, SourceState};

    const DEFAULT_MIC_NAME: &str = "microphone";
    const DEFAULT_CAMERA_NAME: &str = "camera";
    const AVAILABLE_BITS: u64 = 1;
    const MUTED_BITS: u64 = 4;
    const MUTED_DISABLED_BITS: u64 = 12;

    /// Helper to create a `FidlInputDevice`.
    fn create_fidl_input_device(
        device_name: &str,
        device_type: FidlDeviceType,
        sw_bits: u64,
        hw_bits: u64,
        overall_bits: u64,
    ) -> FidlInputDevice {
        FidlInputDevice {
            device_name: Some(device_name.to_string()),
            device_type: Some(device_type),
            source_states: Some(vec![
                FidlSourceState {
                    source: Some(FidlDeviceStateSource::Hardware),
                    state: Some(FidlDeviceState {
                        toggle_flags: FidlToggleFlags::from_bits(hw_bits),
                        ..Default::default()
                    }),
                    ..Default::default()
                },
                FidlSourceState {
                    source: Some(FidlDeviceStateSource::Software),
                    state: Some(FidlDeviceState {
                        toggle_flags: FidlToggleFlags::from_bits(sw_bits),
                        ..Default::default()
                    }),
                    ..Default::default()
                },
            ]),
            mutable_toggle_state: FidlToggleFlags::from_bits(MUTED_DISABLED_BITS),
            state: Some(FidlDeviceState {
                toggle_flags: FidlToggleFlags::from_bits(overall_bits),
                ..Default::default()
            }),
            ..Default::default()
        }
    }

    /// Helper to create an [`InputDevice`].
    fn create_input_device(
        device_name: &str,
        device_type: InputDeviceType,
        sw_bits: u64,
        hw_bits: u64,
        overall_bits: u64,
    ) -> InputDevice {
        let mut input_device = InputDevice::new(device_name.to_string(), device_type);
        let _ = input_device
            .source_states
            .insert(DeviceStateSource::SOFTWARE, DeviceState::from_bits(sw_bits).unwrap());
        let _ = input_device
            .source_states
            .insert(DeviceStateSource::HARDWARE, DeviceState::from_bits(hw_bits).unwrap());
        input_device.state = DeviceState::from_bits(overall_bits).unwrap();
        input_device
    }

    /// Helper for creating the config for an `InputDevice`.
    fn create_device_config(
        device_name: &str,
        device_type: InputDeviceType,
        sw_state: u64,
        hw_state: u64,
    ) -> InputDeviceConfiguration {
        InputDeviceConfiguration {
            device_name: device_name.to_string(),
            device_type,
            source_states: vec![
                SourceState { source: DeviceStateSource::SOFTWARE, state: sw_state },
                SourceState { source: DeviceStateSource::HARDWARE, state: hw_state },
            ],
            mutable_toggle_state: MUTED_DISABLED_BITS,
        }
    }

    /// Helper for verifying the equality of a `FidlInputDevice`. Cannot directly
    /// compare because the order of the source_states vector may vary.
    fn verify_fidl_input_device_eq(res: FidlInputDevice, expected: FidlInputDevice) {
        assert_eq!(res.device_name, expected.device_name);
        assert_eq!(res.device_type, expected.device_type);
        assert_eq!(res.mutable_toggle_state, expected.mutable_toggle_state);
        assert_eq!(res.state, expected.state);
        let res_source_states = res.source_states.unwrap();
        for source_state in expected.source_states.unwrap() {
            assert!(&res_source_states.contains(&source_state));
        }
    }

    #[fuchsia::test]
    fn test_input_state_manipulation() {
        let mut input_state = InputState::new();

        // Set the source state for each source and device type.
        input_state.set_source_state(
            InputDeviceType::MICROPHONE,
            DEFAULT_MIC_NAME.to_string(),
            DeviceStateSource::SOFTWARE,
            DeviceState::from_bits(AVAILABLE_BITS).unwrap(),
        );
        input_state.set_source_state(
            InputDeviceType::MICROPHONE,
            DEFAULT_MIC_NAME.to_string(),
            DeviceStateSource::HARDWARE,
            DeviceState::from_bits(MUTED_BITS).unwrap(),
        );
        input_state.set_source_state(
            InputDeviceType::CAMERA,
            DEFAULT_CAMERA_NAME.to_string(),
            DeviceStateSource::SOFTWARE,
            DeviceState::from_bits(MUTED_BITS).unwrap(),
        );
        input_state.set_source_state(
            InputDeviceType::CAMERA,
            DEFAULT_CAMERA_NAME.to_string(),
            DeviceStateSource::HARDWARE,
            DeviceState::from_bits(AVAILABLE_BITS).unwrap(),
        );

        // Get the source state for each source and device type.
        assert_eq!(
            input_state
                .get_source_state(
                    InputDeviceType::MICROPHONE,
                    DEFAULT_MIC_NAME.to_string(),
                    DeviceStateSource::SOFTWARE
                )
                .unwrap(),
            DeviceState::from_bits(AVAILABLE_BITS).unwrap(),
        );
        assert_eq!(
            input_state
                .get_source_state(
                    InputDeviceType::MICROPHONE,
                    DEFAULT_MIC_NAME.to_string(),
                    DeviceStateSource::HARDWARE
                )
                .unwrap(),
            DeviceState::from_bits(MUTED_BITS).unwrap(),
        );
        assert_eq!(
            input_state
                .get_source_state(
                    InputDeviceType::CAMERA,
                    DEFAULT_CAMERA_NAME.to_string(),
                    DeviceStateSource::SOFTWARE
                )
                .unwrap(),
            DeviceState::from_bits(MUTED_BITS).unwrap(),
        );
        assert_eq!(
            input_state
                .get_source_state(
                    InputDeviceType::CAMERA,
                    DEFAULT_CAMERA_NAME.to_string(),
                    DeviceStateSource::HARDWARE
                )
                .unwrap(),
            DeviceState::from_bits(AVAILABLE_BITS).unwrap(),
        );

        // Get the overall states for each device.
        assert_eq!(
            input_state
                .get_state(InputDeviceType::MICROPHONE, DEFAULT_MIC_NAME.to_string())
                .unwrap(),
            DeviceState::from_bits(MUTED_BITS).unwrap(),
        );
        assert_eq!(
            input_state
                .get_state(InputDeviceType::CAMERA, DEFAULT_CAMERA_NAME.to_string())
                .unwrap(),
            DeviceState::from_bits(MUTED_BITS).unwrap(),
        );

        // Switch the mic hardware on.
        input_state.set_source_state(
            InputDeviceType::MICROPHONE,
            DEFAULT_MIC_NAME.to_string(),
            DeviceStateSource::HARDWARE,
            DeviceState::from_bits(AVAILABLE_BITS).unwrap(),
        );
        assert_eq!(
            input_state
                .get_state(InputDeviceType::MICROPHONE, DEFAULT_MIC_NAME.to_string())
                .unwrap(),
            DeviceState::from_bits(AVAILABLE_BITS).unwrap(),
        );

        // Switch the camera software on.
        input_state.set_source_state(
            InputDeviceType::CAMERA,
            DEFAULT_CAMERA_NAME.to_string(),
            DeviceStateSource::SOFTWARE,
            DeviceState::from_bits(AVAILABLE_BITS).unwrap(),
        );
        assert_eq!(
            input_state
                .get_state(InputDeviceType::CAMERA, DEFAULT_CAMERA_NAME.to_string())
                .unwrap(),
            DeviceState::from_bits(AVAILABLE_BITS).unwrap(),
        );
    }

    #[fuchsia::test]
    fn test_input_configuration_to_input_state() {
        let config = InputConfiguration {
            devices: vec![
                create_device_config(
                    DEFAULT_MIC_NAME,
                    InputDeviceType::MICROPHONE,
                    MUTED_BITS,
                    AVAILABLE_BITS,
                ),
                create_device_config(
                    DEFAULT_CAMERA_NAME,
                    InputDeviceType::CAMERA,
                    AVAILABLE_BITS,
                    AVAILABLE_BITS,
                ),
                create_device_config(
                    "camera2",
                    InputDeviceType::CAMERA,
                    AVAILABLE_BITS,
                    MUTED_DISABLED_BITS,
                ),
            ],
        };
        let result: InputState = config.into();
        assert_eq!(
            result
                .get_source_state(
                    InputDeviceType::MICROPHONE,
                    DEFAULT_MIC_NAME.to_string(),
                    DeviceStateSource::SOFTWARE,
                )
                .unwrap(),
            DeviceState::from_bits(MUTED_BITS).unwrap(),
        );
        assert_eq!(
            result
                .get_source_state(
                    InputDeviceType::MICROPHONE,
                    DEFAULT_MIC_NAME.to_string(),
                    DeviceStateSource::HARDWARE,
                )
                .unwrap(),
            DeviceState::from_bits(AVAILABLE_BITS).unwrap(),
        );
        assert_eq!(
            result
                .get_source_state(
                    InputDeviceType::CAMERA,
                    DEFAULT_CAMERA_NAME.to_string(),
                    DeviceStateSource::SOFTWARE,
                )
                .unwrap(),
            DeviceState::from_bits(AVAILABLE_BITS).unwrap(),
        );
        assert_eq!(
            result
                .get_source_state(
                    InputDeviceType::CAMERA,
                    DEFAULT_CAMERA_NAME.to_string(),
                    DeviceStateSource::HARDWARE,
                )
                .unwrap(),
            DeviceState::from_bits(AVAILABLE_BITS).unwrap(),
        );
        assert_eq!(
            result
                .get_source_state(
                    InputDeviceType::CAMERA,
                    "camera2".to_string(),
                    DeviceStateSource::SOFTWARE,
                )
                .unwrap(),
            DeviceState::from_bits(AVAILABLE_BITS).unwrap(),
        );
        assert_eq!(
            result
                .get_source_state(
                    InputDeviceType::CAMERA,
                    "camera2".to_string(),
                    DeviceStateSource::HARDWARE,
                )
                .unwrap(),
            DeviceState::from_bits(MUTED_DISABLED_BITS).unwrap(),
        );
    }

    #[fuchsia::test]
    /// Test that the combination of the input device's source states results
    /// in the correct overall device state.
    fn test_overall_state() {
        // The last number doesn't matter here, it will be overwritten by the
        // compute_input_state calls.
        let mut mic_available = create_input_device(
            DEFAULT_MIC_NAME,
            InputDeviceType::MICROPHONE,
            AVAILABLE_BITS,
            AVAILABLE_BITS,
            AVAILABLE_BITS,
        );
        let mut mic_disabled = create_input_device(
            DEFAULT_MIC_NAME,
            InputDeviceType::MICROPHONE,
            MUTED_DISABLED_BITS,
            AVAILABLE_BITS,
            MUTED_DISABLED_BITS,
        );
        let mut mic_muted = create_input_device(
            DEFAULT_MIC_NAME,
            InputDeviceType::MICROPHONE,
            AVAILABLE_BITS,
            MUTED_BITS,
            MUTED_BITS,
        );
        let mut mic_active = create_input_device(
            DEFAULT_MIC_NAME,
            InputDeviceType::MICROPHONE,
            3,
            AVAILABLE_BITS,
            3,
        );
        let mut mic_error = create_input_device(
            DEFAULT_MIC_NAME,
            InputDeviceType::MICROPHONE,
            10,
            AVAILABLE_BITS,
            16,
        );

        mic_available.compute_input_state();
        mic_disabled.compute_input_state();
        mic_muted.compute_input_state();
        mic_active.compute_input_state();
        mic_error.compute_input_state();

        assert_eq!(mic_available.state, DeviceState::AVAILABLE);
        assert_eq!(mic_disabled.state, DeviceState::DISABLED | DeviceState::MUTED);
        assert_eq!(mic_muted.state, DeviceState::MUTED);
        assert_eq!(mic_active.state, DeviceState::ACTIVE | DeviceState::AVAILABLE);
        assert_eq!(mic_error.state, DeviceState::ERROR);
    }

    #[fuchsia::test]
    fn test_input_device_to_fidl_input_device() {
        let expected_mic: FidlInputDevice = create_fidl_input_device(
            DEFAULT_MIC_NAME,
            FidlDeviceType::Microphone,
            AVAILABLE_BITS,
            AVAILABLE_BITS,
            AVAILABLE_BITS,
        );
        let expected_cam: FidlInputDevice = create_fidl_input_device(
            DEFAULT_CAMERA_NAME,
            FidlDeviceType::Camera,
            AVAILABLE_BITS,
            MUTED_BITS,
            MUTED_BITS,
        );

        let mut mic = InputDevice::new(DEFAULT_MIC_NAME.to_string(), InputDeviceType::MICROPHONE);
        let _ = mic
            .source_states
            .insert(DeviceStateSource::SOFTWARE, DeviceState::from_bits(AVAILABLE_BITS).unwrap());
        let _ = mic
            .source_states
            .insert(DeviceStateSource::HARDWARE, DeviceState::from_bits(AVAILABLE_BITS).unwrap());
        mic.state = DeviceState::from_bits(AVAILABLE_BITS).unwrap();

        let mut cam = InputDevice::new(DEFAULT_CAMERA_NAME.to_string(), InputDeviceType::CAMERA);
        let _ = cam
            .source_states
            .insert(DeviceStateSource::SOFTWARE, DeviceState::from_bits(AVAILABLE_BITS).unwrap());
        let _ = cam
            .source_states
            .insert(DeviceStateSource::HARDWARE, DeviceState::from_bits(MUTED_BITS).unwrap());
        cam.state = DeviceState::from_bits(MUTED_BITS).unwrap();

        let mic_res: FidlInputDevice = mic.into();
        let cam_res: FidlInputDevice = cam.into();

        verify_fidl_input_device_eq(mic_res, expected_mic);
        verify_fidl_input_device_eq(cam_res, expected_cam);
    }

    #[fuchsia::test]
    fn test_input_device_type_to_string() {
        assert_eq!(InputDeviceType::CAMERA.to_string(), DEFAULT_CAMERA_NAME);
        assert_eq!(InputDeviceType::MICROPHONE.to_string(), DEFAULT_MIC_NAME);
    }

    #[fuchsia::test]
    fn test_fidl_device_type_to_device_type() {
        let cam_res: FidlDeviceType = InputDeviceType::CAMERA.into();
        let mic_res: FidlDeviceType = InputDeviceType::MICROPHONE.into();
        assert_eq!(cam_res, FidlDeviceType::Camera);
        assert_eq!(mic_res, FidlDeviceType::Microphone);
    }

    #[fuchsia::test]
    fn test_device_type_to_fidl_device_type() {
        let cam_res: InputDeviceType = FidlDeviceType::Camera.into();
        let mic_res: InputDeviceType = FidlDeviceType::Microphone.into();
        assert_eq!(cam_res, InputDeviceType::CAMERA);
        assert_eq!(mic_res, InputDeviceType::MICROPHONE);
    }

    #[fuchsia::test]
    fn test_fidl_device_state_source_to_device_state_source() {
        let hw_res: FidlDeviceStateSource = DeviceStateSource::HARDWARE.into();
        let sw_res: FidlDeviceStateSource = DeviceStateSource::SOFTWARE.into();
        assert_eq!(hw_res, FidlDeviceStateSource::Hardware);
        assert_eq!(sw_res, FidlDeviceStateSource::Software);
    }

    #[fuchsia::test]
    fn test_device_state_source_to_fidl_device_state_source() {
        let hw_res: DeviceStateSource = FidlDeviceStateSource::Hardware.into();
        let sw_res: DeviceStateSource = FidlDeviceStateSource::Software.into();
        assert_eq!(hw_res, DeviceStateSource::HARDWARE);
        assert_eq!(sw_res, DeviceStateSource::SOFTWARE);
    }

    #[fuchsia::test]
    fn test_device_state_errors() {
        let available_disabled = DeviceState::from_bits(9).unwrap();
        let available_muted = DeviceState::from_bits(5).unwrap();
        let active_muted = DeviceState::from_bits(6).unwrap();
        let active_disabled = DeviceState::from_bits(10).unwrap();
        assert!(available_disabled.has_error());
        assert!(available_muted.has_error());
        assert!(active_muted.has_error());
        assert!(active_disabled.has_error());
    }

    #[fuchsia::test]
    fn test_fidl_device_state_to_device_state() {
        let device_state: DeviceState = FidlDeviceState {
            toggle_flags: FidlToggleFlags::from_bits(MUTED_BITS),
            ..Default::default()
        }
        .into();
        assert_eq!(device_state, DeviceState::from_bits(MUTED_BITS).unwrap(),);
    }

    #[fuchsia::test]
    fn test_device_state_to_fidl_device_state() {
        let fidl_device_state: FidlDeviceState = DeviceState::from_bits(MUTED_BITS).unwrap().into();
        assert_eq!(
            fidl_device_state,
            FidlDeviceState {
                toggle_flags: FidlToggleFlags::from_bits(MUTED_BITS),
                ..Default::default()
            }
        );
    }
}