Skip to main content

fidl_fuchsia_ui_observation_geometry/
fidl_fuchsia_ui_observation_geometry.rs

1// WARNING: This file is machine generated by fidlgen.
2
3#![warn(clippy::all)]
4#![allow(unused_parens, unused_mut, unused_imports, nonstandard_style)]
5
6use bitflags::bitflags;
7use fidl::client::QueryResponseFut;
8use fidl::encoding::{MessageBufFor, ProxyChannelBox, ResourceDialect};
9use fidl::endpoints::{ControlHandle as _, Responder as _};
10pub use fidl_fuchsia_ui_observation_geometry__common::*;
11use futures::future::{self, MaybeDone, TryFutureExt};
12use zx_status;
13
14#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
15pub struct ViewTreeWatcherMarker;
16
17impl fidl::endpoints::ProtocolMarker for ViewTreeWatcherMarker {
18    type Proxy = ViewTreeWatcherProxy;
19    type RequestStream = ViewTreeWatcherRequestStream;
20    #[cfg(target_os = "fuchsia")]
21    type SynchronousProxy = ViewTreeWatcherSynchronousProxy;
22
23    const DEBUG_NAME: &'static str = "(anonymous) ViewTreeWatcher";
24}
25
26pub trait ViewTreeWatcherProxyInterface: Send + Sync {
27    type WatchResponseFut: std::future::Future<Output = Result<WatchResponse, fidl::Error>> + Send;
28    fn r#watch(&self) -> Self::WatchResponseFut;
29}
30#[derive(Debug)]
31#[cfg(target_os = "fuchsia")]
32pub struct ViewTreeWatcherSynchronousProxy {
33    client: fidl::client::sync::Client,
34}
35
36#[cfg(target_os = "fuchsia")]
37impl fidl::endpoints::SynchronousProxy for ViewTreeWatcherSynchronousProxy {
38    type Proxy = ViewTreeWatcherProxy;
39    type Protocol = ViewTreeWatcherMarker;
40
41    fn from_channel(inner: fidl::Channel) -> Self {
42        Self::new(inner)
43    }
44
45    fn into_channel(self) -> fidl::Channel {
46        self.client.into_channel()
47    }
48
49    fn as_channel(&self) -> &fidl::Channel {
50        self.client.as_channel()
51    }
52}
53
54#[cfg(target_os = "fuchsia")]
55impl ViewTreeWatcherSynchronousProxy {
56    pub fn new(channel: fidl::Channel) -> Self {
57        Self { client: fidl::client::sync::Client::new(channel) }
58    }
59
60    pub fn into_channel(self) -> fidl::Channel {
61        self.client.into_channel()
62    }
63
64    /// Waits until an event arrives and returns it. It is safe for other
65    /// threads to make concurrent requests while waiting for an event.
66    pub fn wait_for_event(
67        &self,
68        deadline: zx::MonotonicInstant,
69    ) -> Result<ViewTreeWatcherEvent, fidl::Error> {
70        ViewTreeWatcherEvent::decode(self.client.wait_for_event::<ViewTreeWatcherMarker>(deadline)?)
71    }
72
73    /// A method of obtaining view tree snapshots for a particular view.
74    ///
75    /// This call is formulated as a "hanging get" pattern: the client asks for
76    /// a set of recent snapshots, and receives them via the callback. This
77    /// pull-based approach ensures that clients consume events at their own
78    /// pace; events don't clog up the channel in an unbounded manner.
79    ///
80    /// Error Handling. If Error is unset, the client may assume that the
81    /// the response contains updates with complete information over its epoch.
82    ///
83    /// Flow control. The caller is allowed at most one in-flight |Watch| call
84    /// at a time; it is a logical error to have concurrent calls to |Watch|.
85    /// Non-compliance results in channel closure.
86    ///
87    /// Client pacing. The server will dispatch snapshots to the caller on a
88    /// lossless, best-effort basis, but the caller must allocate enough time to
89    /// keep up with new snapshots.
90    pub fn r#watch(&self, ___deadline: zx::MonotonicInstant) -> Result<WatchResponse, fidl::Error> {
91        let _response = self
92            .client
93            .send_query::<fidl::encoding::EmptyPayload, WatchResponse, ViewTreeWatcherMarker>(
94                (),
95                0x3c7670983418477b,
96                fidl::encoding::DynamicFlags::empty(),
97                ___deadline,
98            )?;
99        Ok(_response)
100    }
101}
102
103#[cfg(target_os = "fuchsia")]
104impl From<ViewTreeWatcherSynchronousProxy> for zx::NullableHandle {
105    fn from(value: ViewTreeWatcherSynchronousProxy) -> Self {
106        value.into_channel().into()
107    }
108}
109
110#[cfg(target_os = "fuchsia")]
111impl From<fidl::Channel> for ViewTreeWatcherSynchronousProxy {
112    fn from(value: fidl::Channel) -> Self {
113        Self::new(value)
114    }
115}
116
117#[cfg(target_os = "fuchsia")]
118impl fidl::endpoints::FromClient for ViewTreeWatcherSynchronousProxy {
119    type Protocol = ViewTreeWatcherMarker;
120
121    fn from_client(value: fidl::endpoints::ClientEnd<ViewTreeWatcherMarker>) -> Self {
122        Self::new(value.into_channel())
123    }
124}
125
126#[derive(Debug, Clone)]
127pub struct ViewTreeWatcherProxy {
128    client: fidl::client::Client<fidl::encoding::DefaultFuchsiaResourceDialect>,
129}
130
131impl fidl::endpoints::Proxy for ViewTreeWatcherProxy {
132    type Protocol = ViewTreeWatcherMarker;
133
134    fn from_channel(inner: ::fidl::AsyncChannel) -> Self {
135        Self::new(inner)
136    }
137
138    fn into_channel(self) -> Result<::fidl::AsyncChannel, Self> {
139        self.client.into_channel().map_err(|client| Self { client })
140    }
141
142    fn as_channel(&self) -> &::fidl::AsyncChannel {
143        self.client.as_channel()
144    }
145}
146
147impl ViewTreeWatcherProxy {
148    /// Create a new Proxy for fuchsia.ui.observation.geometry/ViewTreeWatcher.
149    pub fn new(channel: ::fidl::AsyncChannel) -> Self {
150        let protocol_name = <ViewTreeWatcherMarker as fidl::endpoints::ProtocolMarker>::DEBUG_NAME;
151        Self { client: fidl::client::Client::new(channel, protocol_name) }
152    }
153
154    /// Get a Stream of events from the remote end of the protocol.
155    ///
156    /// # Panics
157    ///
158    /// Panics if the event stream was already taken.
159    pub fn take_event_stream(&self) -> ViewTreeWatcherEventStream {
160        ViewTreeWatcherEventStream { event_receiver: self.client.take_event_receiver() }
161    }
162
163    /// A method of obtaining view tree snapshots for a particular view.
164    ///
165    /// This call is formulated as a "hanging get" pattern: the client asks for
166    /// a set of recent snapshots, and receives them via the callback. This
167    /// pull-based approach ensures that clients consume events at their own
168    /// pace; events don't clog up the channel in an unbounded manner.
169    ///
170    /// Error Handling. If Error is unset, the client may assume that the
171    /// the response contains updates with complete information over its epoch.
172    ///
173    /// Flow control. The caller is allowed at most one in-flight |Watch| call
174    /// at a time; it is a logical error to have concurrent calls to |Watch|.
175    /// Non-compliance results in channel closure.
176    ///
177    /// Client pacing. The server will dispatch snapshots to the caller on a
178    /// lossless, best-effort basis, but the caller must allocate enough time to
179    /// keep up with new snapshots.
180    pub fn r#watch(
181        &self,
182    ) -> fidl::client::QueryResponseFut<WatchResponse, fidl::encoding::DefaultFuchsiaResourceDialect>
183    {
184        ViewTreeWatcherProxyInterface::r#watch(self)
185    }
186}
187
188impl ViewTreeWatcherProxyInterface for ViewTreeWatcherProxy {
189    type WatchResponseFut = fidl::client::QueryResponseFut<
190        WatchResponse,
191        fidl::encoding::DefaultFuchsiaResourceDialect,
192    >;
193    fn r#watch(&self) -> Self::WatchResponseFut {
194        fn _decode(
195            mut _buf: Result<<fidl::encoding::DefaultFuchsiaResourceDialect as fidl::encoding::ResourceDialect>::MessageBufEtc, fidl::Error>,
196        ) -> Result<WatchResponse, fidl::Error> {
197            let _response = fidl::client::decode_transaction_body::<
198                WatchResponse,
199                fidl::encoding::DefaultFuchsiaResourceDialect,
200                0x3c7670983418477b,
201            >(_buf?)?;
202            Ok(_response)
203        }
204        self.client.send_query_and_decode::<fidl::encoding::EmptyPayload, WatchResponse>(
205            (),
206            0x3c7670983418477b,
207            fidl::encoding::DynamicFlags::empty(),
208            _decode,
209        )
210    }
211}
212
213pub struct ViewTreeWatcherEventStream {
214    event_receiver: fidl::client::EventReceiver<fidl::encoding::DefaultFuchsiaResourceDialect>,
215}
216
217impl std::marker::Unpin for ViewTreeWatcherEventStream {}
218
219impl futures::stream::FusedStream for ViewTreeWatcherEventStream {
220    fn is_terminated(&self) -> bool {
221        self.event_receiver.is_terminated()
222    }
223}
224
225impl futures::Stream for ViewTreeWatcherEventStream {
226    type Item = Result<ViewTreeWatcherEvent, fidl::Error>;
227
228    fn poll_next(
229        mut self: std::pin::Pin<&mut Self>,
230        cx: &mut std::task::Context<'_>,
231    ) -> std::task::Poll<Option<Self::Item>> {
232        match futures::ready!(futures::stream::StreamExt::poll_next_unpin(
233            &mut self.event_receiver,
234            cx
235        )?) {
236            Some(buf) => std::task::Poll::Ready(Some(ViewTreeWatcherEvent::decode(buf))),
237            None => std::task::Poll::Ready(None),
238        }
239    }
240}
241
242#[derive(Debug)]
243pub enum ViewTreeWatcherEvent {}
244
245impl ViewTreeWatcherEvent {
246    /// Decodes a message buffer as a [`ViewTreeWatcherEvent`].
247    fn decode(
248        mut buf: <fidl::encoding::DefaultFuchsiaResourceDialect as fidl::encoding::ResourceDialect>::MessageBufEtc,
249    ) -> Result<ViewTreeWatcherEvent, fidl::Error> {
250        let (bytes, _handles) = buf.split_mut();
251        let (tx_header, _body_bytes) = fidl::encoding::decode_transaction_header(bytes)?;
252        debug_assert_eq!(tx_header.tx_id, 0);
253        match tx_header.ordinal {
254            _ => Err(fidl::Error::UnknownOrdinal {
255                ordinal: tx_header.ordinal,
256                protocol_name:
257                    <ViewTreeWatcherMarker as fidl::endpoints::ProtocolMarker>::DEBUG_NAME,
258            }),
259        }
260    }
261}
262
263/// A Stream of incoming requests for fuchsia.ui.observation.geometry/ViewTreeWatcher.
264pub struct ViewTreeWatcherRequestStream {
265    inner: std::sync::Arc<fidl::ServeInner<fidl::encoding::DefaultFuchsiaResourceDialect>>,
266    is_terminated: bool,
267}
268
269impl std::marker::Unpin for ViewTreeWatcherRequestStream {}
270
271impl futures::stream::FusedStream for ViewTreeWatcherRequestStream {
272    fn is_terminated(&self) -> bool {
273        self.is_terminated
274    }
275}
276
277impl fidl::endpoints::RequestStream for ViewTreeWatcherRequestStream {
278    type Protocol = ViewTreeWatcherMarker;
279    type ControlHandle = ViewTreeWatcherControlHandle;
280
281    fn from_channel(channel: ::fidl::AsyncChannel) -> Self {
282        Self { inner: std::sync::Arc::new(fidl::ServeInner::new(channel)), is_terminated: false }
283    }
284
285    fn control_handle(&self) -> Self::ControlHandle {
286        ViewTreeWatcherControlHandle { inner: self.inner.clone() }
287    }
288
289    fn into_inner(
290        self,
291    ) -> (::std::sync::Arc<fidl::ServeInner<fidl::encoding::DefaultFuchsiaResourceDialect>>, bool)
292    {
293        (self.inner, self.is_terminated)
294    }
295
296    fn from_inner(
297        inner: std::sync::Arc<fidl::ServeInner<fidl::encoding::DefaultFuchsiaResourceDialect>>,
298        is_terminated: bool,
299    ) -> Self {
300        Self { inner, is_terminated }
301    }
302}
303
304impl futures::Stream for ViewTreeWatcherRequestStream {
305    type Item = Result<ViewTreeWatcherRequest, fidl::Error>;
306
307    fn poll_next(
308        mut self: std::pin::Pin<&mut Self>,
309        cx: &mut std::task::Context<'_>,
310    ) -> std::task::Poll<Option<Self::Item>> {
311        let this = &mut *self;
312        if this.inner.check_shutdown(cx) {
313            this.is_terminated = true;
314            return std::task::Poll::Ready(None);
315        }
316        if this.is_terminated {
317            panic!("polled ViewTreeWatcherRequestStream after completion");
318        }
319        fidl::encoding::with_tls_decode_buf::<_, fidl::encoding::DefaultFuchsiaResourceDialect>(
320            |bytes, handles| {
321                match this.inner.channel().read_etc(cx, bytes, handles) {
322                    std::task::Poll::Ready(Ok(())) => {}
323                    std::task::Poll::Pending => return std::task::Poll::Pending,
324                    std::task::Poll::Ready(Err(zx_status::Status::PEER_CLOSED)) => {
325                        this.is_terminated = true;
326                        return std::task::Poll::Ready(None);
327                    }
328                    std::task::Poll::Ready(Err(e)) => {
329                        return std::task::Poll::Ready(Some(Err(fidl::Error::ServerRequestRead(
330                            e.into(),
331                        ))));
332                    }
333                }
334
335                // A message has been received from the channel
336                let (header, _body_bytes) = fidl::encoding::decode_transaction_header(bytes)?;
337
338                std::task::Poll::Ready(Some(match header.ordinal {
339                    0x3c7670983418477b => {
340                        header.validate_request_tx_id(fidl::MethodType::TwoWay)?;
341                        let mut req = fidl::new_empty!(
342                            fidl::encoding::EmptyPayload,
343                            fidl::encoding::DefaultFuchsiaResourceDialect
344                        );
345                        fidl::encoding::Decoder::<fidl::encoding::DefaultFuchsiaResourceDialect>::decode_into::<fidl::encoding::EmptyPayload>(&header, _body_bytes, handles, &mut req)?;
346                        let control_handle =
347                            ViewTreeWatcherControlHandle { inner: this.inner.clone() };
348                        Ok(ViewTreeWatcherRequest::Watch {
349                            responder: ViewTreeWatcherWatchResponder {
350                                control_handle: std::mem::ManuallyDrop::new(control_handle),
351                                tx_id: header.tx_id,
352                            },
353                        })
354                    }
355                    _ => Err(fidl::Error::UnknownOrdinal {
356                        ordinal: header.ordinal,
357                        protocol_name:
358                            <ViewTreeWatcherMarker as fidl::endpoints::ProtocolMarker>::DEBUG_NAME,
359                    }),
360                }))
361            },
362        )
363    }
364}
365
366/// A method of obtaining view tree snapshots for a particular view, the "context
367/// view", and its child views, if any. The returned data is a sequence of
368/// snapshots during the period of observation, which starts at the client's
369/// prior Watch() call's [`epoch_end`] (or zx.Time 0), and ending at the
370/// current [`epoch_end`]. The timebase is ZX_CLOCK_MONOTONIC.
371///
372/// Clients typically obtain a `ViewTreeWatcher` capability from within a test,
373/// and it is not generally possible to obtain outside of a test environment.
374/// For more information see `fuchsia.ui.observation.test.Registry` and
375/// `fuchsia.ui.test.scene.Controller`.
376///
377/// Usage note. With this protocol, a client can watch for changes to the view
378/// tree over which it has authority. For example, if a client owns view A, then
379/// A serves as the context view for A's subtree (i.e., a "root view"), where A
380/// is a parent of view B, and B is a parent of view C. The client can then
381/// observe key lifecycle events in all of A, B, and C, such as newly connected
382/// views, changes to view position and size, etc. In doing so, a client can
383/// gate its actions on changes to the view tree, in a reliable and ergonomic
384/// manner. For example, a client can wait for a descendant view C to become
385/// connected before requesting a focus transfer to C.
386///
387/// Configuration: The context view is determined outside of this protocol.
388///
389/// Frequency: A client can receive one or more snapshots per frame. Clients
390/// should not "count snapshots", as the per-frame snapshot count can be
391/// non-deterministic. Instead, clients should look for specific conditions on
392/// the snapshot state.
393///
394/// Issuance: If the context view is disconnected from a display, no
395/// frames are issued on behalf of the context view, and a Watch() call will
396/// sit quietly.
397///
398/// Lifecycle: The server endpoint is closed when the context view dies.
399#[derive(Debug)]
400pub enum ViewTreeWatcherRequest {
401    /// A method of obtaining view tree snapshots for a particular view.
402    ///
403    /// This call is formulated as a "hanging get" pattern: the client asks for
404    /// a set of recent snapshots, and receives them via the callback. This
405    /// pull-based approach ensures that clients consume events at their own
406    /// pace; events don't clog up the channel in an unbounded manner.
407    ///
408    /// Error Handling. If Error is unset, the client may assume that the
409    /// the response contains updates with complete information over its epoch.
410    ///
411    /// Flow control. The caller is allowed at most one in-flight |Watch| call
412    /// at a time; it is a logical error to have concurrent calls to |Watch|.
413    /// Non-compliance results in channel closure.
414    ///
415    /// Client pacing. The server will dispatch snapshots to the caller on a
416    /// lossless, best-effort basis, but the caller must allocate enough time to
417    /// keep up with new snapshots.
418    Watch { responder: ViewTreeWatcherWatchResponder },
419}
420
421impl ViewTreeWatcherRequest {
422    #[allow(irrefutable_let_patterns)]
423    pub fn into_watch(self) -> Option<(ViewTreeWatcherWatchResponder)> {
424        if let ViewTreeWatcherRequest::Watch { responder } = self {
425            Some((responder))
426        } else {
427            None
428        }
429    }
430
431    /// Name of the method defined in FIDL
432    pub fn method_name(&self) -> &'static str {
433        match *self {
434            ViewTreeWatcherRequest::Watch { .. } => "watch",
435        }
436    }
437}
438
439#[derive(Debug, Clone)]
440pub struct ViewTreeWatcherControlHandle {
441    inner: std::sync::Arc<fidl::ServeInner<fidl::encoding::DefaultFuchsiaResourceDialect>>,
442}
443
444impl fidl::endpoints::ControlHandle for ViewTreeWatcherControlHandle {
445    fn shutdown(&self) {
446        self.inner.shutdown()
447    }
448
449    fn shutdown_with_epitaph(&self, status: zx_status::Status) {
450        self.inner.shutdown_with_epitaph(status)
451    }
452
453    fn is_closed(&self) -> bool {
454        self.inner.channel().is_closed()
455    }
456    fn on_closed(&self) -> fidl::OnSignalsRef<'_> {
457        self.inner.channel().on_closed()
458    }
459
460    #[cfg(target_os = "fuchsia")]
461    fn signal_peer(
462        &self,
463        clear_mask: zx::Signals,
464        set_mask: zx::Signals,
465    ) -> Result<(), zx_status::Status> {
466        use fidl::Peered;
467        self.inner.channel().signal_peer(clear_mask, set_mask)
468    }
469}
470
471impl ViewTreeWatcherControlHandle {}
472
473#[must_use = "FIDL methods require a response to be sent"]
474#[derive(Debug)]
475pub struct ViewTreeWatcherWatchResponder {
476    control_handle: std::mem::ManuallyDrop<ViewTreeWatcherControlHandle>,
477    tx_id: u32,
478}
479
480/// Set the the channel to be shutdown (see [`ViewTreeWatcherControlHandle::shutdown`])
481/// if the responder is dropped without sending a response, so that the client
482/// doesn't hang. To prevent this behavior, call `drop_without_shutdown`.
483impl std::ops::Drop for ViewTreeWatcherWatchResponder {
484    fn drop(&mut self) {
485        self.control_handle.shutdown();
486        // Safety: drops once, never accessed again
487        unsafe { std::mem::ManuallyDrop::drop(&mut self.control_handle) };
488    }
489}
490
491impl fidl::endpoints::Responder for ViewTreeWatcherWatchResponder {
492    type ControlHandle = ViewTreeWatcherControlHandle;
493
494    fn control_handle(&self) -> &ViewTreeWatcherControlHandle {
495        &self.control_handle
496    }
497
498    fn drop_without_shutdown(mut self) {
499        // Safety: drops once, never accessed again due to mem::forget
500        unsafe { std::mem::ManuallyDrop::drop(&mut self.control_handle) };
501        // Prevent Drop from running (which would shut down the channel)
502        std::mem::forget(self);
503    }
504}
505
506impl ViewTreeWatcherWatchResponder {
507    /// Sends a response to the FIDL transaction.
508    ///
509    /// Sets the channel to shutdown if an error occurs.
510    pub fn send(self, mut payload: &WatchResponse) -> Result<(), fidl::Error> {
511        let _result = self.send_raw(payload);
512        if _result.is_err() {
513            self.control_handle.shutdown();
514        }
515        self.drop_without_shutdown();
516        _result
517    }
518
519    /// Similar to "send" but does not shutdown the channel if an error occurs.
520    pub fn send_no_shutdown_on_err(self, mut payload: &WatchResponse) -> Result<(), fidl::Error> {
521        let _result = self.send_raw(payload);
522        self.drop_without_shutdown();
523        _result
524    }
525
526    fn send_raw(&self, mut payload: &WatchResponse) -> Result<(), fidl::Error> {
527        self.control_handle.inner.send::<WatchResponse>(
528            payload,
529            self.tx_id,
530            0x3c7670983418477b,
531            fidl::encoding::DynamicFlags::empty(),
532        )
533    }
534}
535
536mod internal {
537    use super::*;
538}