Skip to main content

input_pipeline/
focus_listener.rs

1// Copyright 2020 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5use crate::{Incoming, metrics};
6use zx;
7
8const DEFAULT_TEXT_MANAGER_TIMEOUT: zx::MonotonicDuration = zx::MonotonicDuration::from_seconds(15);
9use anyhow::{Context, Error};
10use fidl_fuchsia_ui_focus as focus;
11use fidl_fuchsia_ui_keyboard_focus as kbd_focus;
12use focus_chain_provider::FocusChainProviderPublisher;
13use fuchsia_async::{self as fasync, TimeoutExt as _};
14use futures::StreamExt;
15use metrics_registry::*;
16
17/// FocusListener listens to focus change and notify to related input modules.
18pub struct FocusListener {
19    /// The FIDL proxy to text_manager.
20    text_manager: kbd_focus::ControllerProxy,
21
22    /// A channel that receives focus chain updates.
23    focus_chain_listener: focus::FocusChainListenerRequestStream,
24
25    /// Forwards focus chain updates to downstream watchers.
26    focus_chain_publisher: FocusChainProviderPublisher,
27
28    /// The metrics logger.
29    metrics_logger: metrics::MetricsLogger,
30}
31
32impl FocusListener {
33    /// Creates a new focus listener that holds proxy to text manager.
34    /// The caller is expected to spawn a task to continually listen to focus change event.
35    ///
36    /// # Arguments
37    /// - `focus_chain_publisher`: Allows focus chain updates to be sent to downstream listeners.
38    ///   Note that this is not required for `FocusListener` to function, so it could be made an
39    ///  `Option` in future changes.
40    ///
41    /// # Example
42    ///
43    /// ```ignore
44    /// let mut listener = FocusListener::new(focus_chain_publisher);
45    /// let task = fuchsia_async::Task::local(async move {
46    ///     listener.dispatch_focus_changes().await
47    /// });
48    /// ```
49    ///
50    /// # FIDL
51    ///
52    /// Required:
53    ///
54    /// - `fuchsia.ui.views.FocusChainListener`
55    /// - `fuchsia.ui.keyboard.focus.Controller`
56    ///
57    /// # Errors
58    /// If unable to connect to the text_manager protocol.
59    pub fn new(
60        incoming: &Incoming,
61        focus_chain_publisher: FocusChainProviderPublisher,
62        metrics_logger: metrics::MetricsLogger,
63    ) -> Result<Self, Error> {
64        let text_manager = incoming.connect_protocol::<kbd_focus::ControllerProxy>()?;
65
66        let (focus_chain_listener_client_end, focus_chain_listener) =
67            fidl::endpoints::create_request_stream::<focus::FocusChainListenerMarker>();
68
69        let focus_chain_listener_registry: focus::FocusChainListenerRegistryProxy =
70            incoming.connect_protocol::<focus::FocusChainListenerRegistryProxy>()?;
71        focus_chain_listener_registry
72            .register(focus_chain_listener_client_end)
73            .context("Failed to register focus chain listener.")?;
74
75        Ok(Self::new_listener(
76            text_manager,
77            focus_chain_listener,
78            focus_chain_publisher,
79            metrics_logger,
80        ))
81    }
82
83    /// Creates a new focus listener that holds proxy to text manager.
84    /// The caller is expected to spawn a task to continually listen to focus change event.
85    ///
86    /// # Parameters
87    /// - `text_manager`: A proxy to the text manager service.
88    /// - `focus_chain_listener`: A channel that receives focus chain updates.
89    /// - `focus_chain_publisher`: Forwards focus chain updates to downstream watchers.
90    ///
91    /// # Errors
92    /// If unable to connect to the text_manager protocol.
93    fn new_listener(
94        text_manager: kbd_focus::ControllerProxy,
95        focus_chain_listener: focus::FocusChainListenerRequestStream,
96        focus_chain_publisher: FocusChainProviderPublisher,
97        metrics_logger: metrics::MetricsLogger,
98    ) -> Self {
99        Self { text_manager, focus_chain_listener, focus_chain_publisher, metrics_logger }
100    }
101
102    /// Dispatches focus chain updates from `focus_chain_listener` to `text_manager` and any subscribers of `focus_chain_publisher`.
103    pub async fn dispatch_focus_changes(&mut self) -> Result<(), Error> {
104        while let Some(focus_change) = self.focus_chain_listener.next().await {
105            fuchsia_trace::duration!("input", "dispatch_focus_changes");
106            match focus_change {
107                Ok(focus::FocusChainListenerRequest::OnFocusChange {
108                    focus_chain,
109                    responder,
110                    ..
111                }) => {
112                    fuchsia_trace::duration!("input", "dispatch_focus_changes[processing]");
113                    // Dispatch to downstream watchers.
114                    self.focus_chain_publisher
115                        .set_state_and_notify_if_changed(&focus_chain)
116                        .context("while notifying FocusChainProviderPublisher")?;
117
118                    // Dispatch to text manager.
119                    if let Some(ref focus_chain) = focus_chain.focus_chain {
120                        if let Some(ref view_ref) = focus_chain.last() {
121                            let view_ref_dup = fuchsia_scenic::duplicate_view_ref(&view_ref)?;
122                            let notify_result = self
123                                .text_manager
124                                .notify(view_ref_dup)
125                                .on_timeout(
126                                    fasync::MonotonicInstant::after(DEFAULT_TEXT_MANAGER_TIMEOUT),
127                                    || {
128                                        Err(fidl::Error::ClientChannelClosed {
129                                            epitaph: fidl::Epitaph::PeerClosed,
130                                            protocol_name: "fuchsia.ui.keyboard.focus.Controller",
131                                        })
132                                    },
133                                )
134                                .await;
135                            if let Err(e) = notify_result {
136                                log::warn!(
137                                    "Failed to notify text_manager of focus change: {:?}",
138                                    e
139                                );
140                            }
141                        }
142                    };
143
144                    responder.send().context("while sending focus chain listener response")?;
145                }
146                Err(e) => self.metrics_logger.log_error(
147                    InputPipelineErrorMetricDimensionEvent::FocusChainListenerRequestError,
148                    std::format!("FocusChainListenerRequest has error: {}.", e),
149                ),
150            }
151        }
152        log::warn!("Stopped dispatching focus changes.");
153        Ok(())
154    }
155}
156
157#[cfg(test)]
158mod tests {
159    use super::*;
160    use fidl_fuchsia_ui_focus_ext::FocusChainExt;
161    use fidl_fuchsia_ui_views as fidl_ui_views;
162    use fidl_fuchsia_ui_views_ext::ViewRefExt;
163    use fuchsia_scenic as scenic;
164    use futures::join;
165    use pretty_assertions::assert_eq;
166
167    /// Listens for a ViewRef from a view focus change request on `request_stream`.
168    ///
169    /// # Parameters
170    /// `request_stream`: A channel where ViewFocusChanged requests are received.
171    ///
172    /// # Returns
173    /// The ViewRef of the focused view.
174    async fn expect_focus_ctl_focus_change(
175        mut request_stream: kbd_focus::ControllerRequestStream,
176    ) -> fidl_ui_views::ViewRef {
177        match request_stream.next().await {
178            Some(Ok(kbd_focus::ControllerRequest::Notify { view_ref, responder, .. })) => {
179                let _ = responder.send();
180                view_ref
181            }
182            _ => panic!("Error expecting text_manager focus change."),
183        }
184    }
185
186    async fn expect_focus_koid_chain(
187        focus_chain_provider_proxy: &focus::FocusChainProviderProxy,
188    ) -> focus::FocusKoidChain {
189        focus_chain_provider_proxy
190            .watch_focus_koid_chain(&focus::FocusChainProviderWatchFocusKoidChainRequest::default())
191            .await
192            .expect("watch_focus_koid_chain")
193    }
194
195    /// Tests focused view routing from FocusChainListener to text_manager service.
196    #[fuchsia::test(allow_stalls = false)]
197    async fn dispatch_focus() -> Result<(), Error> {
198        let (focus_proxy, focus_request_stream) =
199            fidl::endpoints::create_proxy_and_stream::<kbd_focus::ControllerMarker>();
200
201        let (focus_chain_listener_client_end, focus_chain_listener) =
202            fidl::endpoints::create_proxy_and_stream::<focus::FocusChainListenerMarker>();
203
204        let (focus_chain_watcher, focus_chain_provider_stream) =
205            fidl::endpoints::create_proxy_and_stream::<focus::FocusChainProviderMarker>();
206        let (focus_chain_provider_publisher, focus_chain_provider_stream_handler) =
207            focus_chain_provider::make_publisher_and_stream_handler();
208        let _provider_task =
209            focus_chain_provider_stream_handler.handle_request_stream(focus_chain_provider_stream);
210
211        let mut listener = FocusListener::new_listener(
212            focus_proxy,
213            focus_chain_listener,
214            focus_chain_provider_publisher,
215            metrics::MetricsLogger::default(),
216        );
217
218        let _listener_task = fuchsia_async::Task::local(async move {
219            let _ = listener.dispatch_focus_changes().await;
220        });
221
222        // Flush the initial value from the hanging get server.
223        // Note that if the focus chain watcher tried to retrieve the koid chain for the first time
224        // inside the `join!` statement below, concurrently with the update operation, it would end
225        // up receiving the old value.
226        let got_focus_koid_chain = expect_focus_koid_chain(&focus_chain_watcher).await;
227        assert_eq!(got_focus_koid_chain, focus::FocusKoidChain::default());
228
229        let view_ref = scenic::ViewRefPair::new()?.view_ref;
230        let view_ref_dup = fuchsia_scenic::duplicate_view_ref(&view_ref)?;
231        let focus_chain =
232            focus::FocusChain { focus_chain: Some(vec![view_ref]), ..Default::default() };
233
234        let (_, view_ref, got_focus_koid_chain) = join!(
235            focus_chain_listener_client_end.on_focus_change(focus_chain.duplicate().unwrap()),
236            expect_focus_ctl_focus_change(focus_request_stream),
237            expect_focus_koid_chain(&focus_chain_watcher),
238        );
239
240        assert_eq!(view_ref.get_koid().unwrap(), view_ref_dup.get_koid().unwrap(),);
241        assert!(focus_chain.equivalent(&got_focus_koid_chain).unwrap());
242
243        Ok(())
244    }
245}