settings/agent/
media_buttons.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
// 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::agent::{
    AgentError, Context as AgentContext, Invocation, InvocationResult, Lifespan, Payload,
};
use crate::base::SettingType;
use crate::event::{media_buttons, Event, Publisher};
use crate::handler::base::{Payload as HandlerPayload, Request};
use crate::input::{monitor_media_buttons, MediaButtons};
use crate::message::base::Audience;
use crate::service_context::ServiceContext;
use crate::{service, trace_guard};
use fidl_fuchsia_ui_input::MediaButtonsEvent;
use futures::StreamExt;
use std::collections::HashSet;
use std::rc::Rc;
use {fuchsia_async as fasync, fuchsia_trace as ftrace};

/// Setting types that the media buttons agent will send media button events to, if they're
/// available on the device.
fn get_event_setting_types() -> HashSet<SettingType> {
    vec![SettingType::Audio, SettingType::Light, SettingType::Input].into_iter().collect()
}

pub(crate) struct MediaButtonsAgent {
    publisher: Publisher,
    messenger: service::message::Messenger,

    /// Settings to send media buttons events to.
    recipient_settings: HashSet<SettingType>,
}

impl MediaButtonsAgent {
    pub(crate) async fn create(context: AgentContext) {
        let mut agent = MediaButtonsAgent {
            publisher: context.get_publisher(),
            messenger: context.create_messenger().await.expect("media button messenger created"),
            recipient_settings: context
                .available_components
                .intersection(&get_event_setting_types())
                .cloned()
                .collect::<HashSet<SettingType>>(),
        };

        let mut receptor = context.receptor;
        fasync::Task::local(async move {
            while let Ok((Payload::Invocation(invocation), client)) =
                receptor.next_of::<Payload>().await
            {
                let _ = client.reply(Payload::Complete(agent.handle(invocation).await).into());
            }

            tracing::info!("Media buttons agent done processing requests");
        })
        .detach()
    }

    async fn handle(&mut self, invocation: Invocation) -> InvocationResult {
        match invocation.lifespan {
            Lifespan::Initialization => Err(AgentError::UnhandledLifespan),
            Lifespan::Service => self.handle_service_lifespan(invocation.service_context).await,
        }
    }

    async fn handle_service_lifespan(
        &mut self,
        service_context: Rc<ServiceContext>,
    ) -> InvocationResult {
        let (input_tx, mut input_rx) = futures::channel::mpsc::unbounded::<MediaButtonsEvent>();
        if let Err(e) = monitor_media_buttons(service_context, input_tx).await {
            tracing::error!("Unable to monitor media buttons: {:?}", e);
            return Err(AgentError::UnexpectedError);
        }

        let event_handler = EventHandler {
            publisher: self.publisher.clone(),
            messenger: self.messenger.clone(),
            recipient_settings: self.recipient_settings.clone(),
        };
        fasync::Task::local(async move {
            while let Some(event) = input_rx.next().await {
                let id = ftrace::Id::new();
                event_handler.handle_event(event, id);
            }
        })
        .detach();

        Ok(())
    }
}

struct EventHandler {
    publisher: Publisher,
    messenger: service::message::Messenger,
    recipient_settings: HashSet<SettingType>,
}

impl EventHandler {
    fn handle_event(&self, event: MediaButtonsEvent, id: ftrace::Id) {
        if event.mic_mute.is_some() || event.camera_disable.is_some() {
            let media_buttons: MediaButtons = event.into();
            self.send_event(media_buttons, id);
        }
    }

    fn send_event<E>(&self, event: E, id: ftrace::Id)
    where
        E: Copy + Into<media_buttons::Event> + Into<Request> + std::fmt::Debug,
    {
        self.publisher.send_event(Event::MediaButtons(event.into()));
        let setting_request: Request = event.into();

        // Send the event to all the interested setting types that are also available.
        for setting_type in self.recipient_settings.iter() {
            let guard = trace_guard!(
                id,

                c"media buttons send event",
                "setting_type" => format!("{setting_type:?}").as_str()
            );
            let mut receptor = self.messenger.message(
                HandlerPayload::Request(setting_request.clone()).into(),
                Audience::Address(service::Address::Handler(*setting_type)),
            );
            fasync::Task::local(async move {
                let _ = receptor.next_payload().await;
                drop(guard);
            })
            .detach();
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::event;
    use crate::input::common::MediaButtonsEventBuilder;
    use crate::message::base::MessageEvent;
    use crate::message::receptor::Receptor;
    use crate::tests::fakes::service_registry::ServiceRegistry;
    use crate::tests::helpers::{
        create_messenger_and_publisher, create_messenger_and_publisher_from_hub,
        create_receptor_for_setting_type,
    };

    // Tests that the initialization lifespan is not handled.
    #[fuchsia::test(allow_stalls = false)]
    async fn initialization_lifespan_is_unhandled() {
        // Setup messengers needed to construct the agent.
        let (messenger, publisher) = create_messenger_and_publisher().await;

        // Construct the agent.
        let mut agent =
            MediaButtonsAgent { publisher, messenger, recipient_settings: HashSet::new() };

        // Try to initiatate the initialization lifespan.
        let result = agent
            .handle(Invocation {
                lifespan: Lifespan::Initialization,
                service_context: Rc::new(ServiceContext::new(None, None)),
            })
            .await;

        assert!(matches!(result, Err(AgentError::UnhandledLifespan)));
    }

    // Tests that the agent cannot start without a media buttons service.
    #[fuchsia::test(allow_stalls = false)]
    async fn when_media_buttons_inaccessible_returns_err() {
        // Setup messengers needed to construct the agent.
        let (messenger, publisher) = create_messenger_and_publisher().await;

        // Construct the agent.
        let mut agent =
            MediaButtonsAgent { publisher, messenger, recipient_settings: HashSet::new() };

        let service_context = Rc::new(ServiceContext::new(
            // Create a service registry without a media buttons interface.
            Some(ServiceRegistry::serve(ServiceRegistry::create())),
            None,
        ));

        // Try to initiate the Service lifespan without providing the MediaButtons fidl interface.
        let result =
            agent.handle(Invocation { lifespan: Lifespan::Service, service_context }).await;
        assert!(matches!(result, Err(AgentError::UnexpectedError)));
    }

    // Tests that events can be sent to the intended recipients.
    #[fuchsia::test(allow_stalls = false)]
    async fn event_handler_proxies_event() {
        let service_message_hub = service::MessageHub::create_hub();

        let (messenger, publisher) =
            create_messenger_and_publisher_from_hub(&service_message_hub).await;
        let target_setting_type = SettingType::Unknown;

        // Get the messenger's signature and the receptor for agents. We need
        // a different messenger below because a broadcast would not send a message
        // to itself. The signature is used to delete the original messenger for this
        // receptor.
        let event_receptor = service::build_event_listener(&service_message_hub).await;

        // Create receptor representing handler endpoint.
        let handler_receptor: Receptor =
            create_receptor_for_setting_type(&service_message_hub, target_setting_type).await;

        // Make all setting types available.
        let event_handler = EventHandler {
            publisher,
            messenger,
            recipient_settings: vec![target_setting_type].into_iter().collect(),
        };

        // Send the events.
        event_handler.handle_event(
            MediaButtonsEventBuilder::new().set_mic_mute(true).set_camera_disable(true).build(),
            0.into(),
        );

        // Delete the messengers for the receptors we're selecting below. This
        // will allow the `select!` to eventually hit the `complete` case.
        service_message_hub.delete(handler_receptor.get_signature());
        service_message_hub.delete(event_receptor.get_signature());

        let mut agent_received_media_buttons = false;

        let mut received_events: usize = 0;

        let fused_event = event_receptor.fuse();
        let fused_handler = handler_receptor.fuse();
        futures::pin_mut!(fused_event, fused_handler);

        // Loop over the select so we can handle the messages as they come in. When all messages
        // have been handled, due to the messengers being deleted above, the complete branch should
        // be hit to break out of the loop.
        loop {
            futures::select! {
                message = fused_event.select_next_some() => {
                    if let MessageEvent::Message(
                        service::Payload::Event(event::Payload::Event(
                            event::Event::MediaButtons(event))), _) = message
                    {
                        match event {
                            event::media_buttons::Event::OnButton(
                                MediaButtons{..}
                            ) => {
                                agent_received_media_buttons = true;
                            }
                        }
                    }
                },
                message = fused_handler.select_next_some() => {
                    if let MessageEvent::Message(
                        service::Payload::Setting(HandlerPayload::Request(
                            Request::OnButton(_button),
                        )),
                        _,
                    ) = message
                    {
                        received_events += 1;
                    }
                }
                complete => break,
            }
        }

        assert!(agent_received_media_buttons);

        // setting should have received one event for both mic and camera.
        assert_eq!(received_events, 1);
    }

    // Tests that events are not sent to unavailable settings.
    #[fuchsia::test(allow_stalls = false)]
    async fn event_handler_sends_no_events_if_no_settings_available() {
        let service_message_hub = service::MessageHub::create_hub();
        let (messenger, publisher) =
            create_messenger_and_publisher_from_hub(&service_message_hub).await;

        // Create messenger to represent unavailable setting handler.
        let mut handler_receptor: Receptor =
            create_receptor_for_setting_type(&service_message_hub, SettingType::Unknown).await;

        // Declare all settings as unavailable so that no events are sent.
        let event_handler =
            EventHandler { publisher, messenger, recipient_settings: HashSet::new() };

        // Send the events
        event_handler.handle_event(
            MediaButtonsEventBuilder::new().set_mic_mute(true).set_camera_disable(true).build(),
            0.into(),
        );

        let mut received_events: usize = 0;

        // Delete the messengers for the receptors we're selecting below. This will allow the while
        // loop below to eventually finish.
        service_message_hub.delete(handler_receptor.get_signature());

        while let Ok((HandlerPayload::Request(_), _)) =
            handler_receptor.next_of::<HandlerPayload>().await
        {
            received_events += 1;
        }

        // No events were received via the setting handler.
        assert_eq!(received_events, 0);
    }
}