input_pipeline/
dead_keys_handler.rs

1// Copyright 2021 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
5//! Implements dead key handling.
6//!
7//! Dead key is a character composition approach where an accented character,
8//! typically from a Western European alphabet, is composed by actuating two
9//! keys on the keyboard:
10//!
11//! 1. A "dead key" which determines which diacritic is to be placed on the
12//!    character, and which produces no immediate output; and
13//! 2. The character onto which the diacritic is to be placed.
14//!
15//! The resulting two successive key actuations produce an effect of single
16//! accented character being emitted.
17//!
18//! The dead key handler relies on keymap already having been applied, and the
19//! use of key meanings.
20//!
21//! This means that the dead key handler must be added to the input pipeline
22//! after the keymap handler in the input pipeline.
23//!
24//! The dead key handler can delay or modify the key meanings, but it never delays nor
25//! modifies key events.  This ensures that clients which require key events see the
26//! key events as they come in.  The key meanings may be delayed because of the delayed
27//! effect of composition.
28//!
29//! The state machine of the dead key handler is watching for dead key and "live" key
30//! combinations, and handles all their possible interleaving. The event sequences
31//! vary from the "obvious" ones such as "dead key press and release followed
32//! by a live key press and release", to not so obvious ones such as: "dead key
33//! press and hold, shift press, live key press and hold followed by another
34//! live key press, followed by arbitrary sequence of key releases".
35//!
36//! See the documentation for [Handler] for some more detail.
37
38use crate::input_device::{
39    Handled, InputDeviceDescriptor, InputDeviceEvent, InputEvent, UnhandledInputEvent,
40};
41use crate::input_handler::{InputHandlerStatus, UnhandledInputHandler};
42use crate::keyboard_binding::KeyboardEvent;
43use async_trait::async_trait;
44use core::fmt;
45use fidl_fuchsia_ui_input3::{KeyEventType, KeyMeaning};
46use fuchsia_inspect::health::Reporter;
47use std::cell::RefCell;
48use std::rc::Rc;
49use {rust_icu_sys as usys, rust_icu_unorm2 as unorm};
50
51// There probably is a more general method of determining whether the characters
52// are combining characters. But somehow it escapes me now.
53const GRAVE: u32 = 0x300;
54const ACUTE: u32 = 0x301;
55const CIRCUMFLEX: u32 = 0x302;
56const TILDE: u32 = 0x303;
57
58/// Returns true if `c` is one of the dead keys we support.
59///
60/// This should likely be some ICU library function, but I'm not sure which one.
61fn is_dead_key(c: u32) -> bool {
62    match c {
63        GRAVE | ACUTE | CIRCUMFLEX | TILDE => true,
64        _ => false,
65    }
66}
67
68/// Removes the combining effect from a combining code point, leaving only
69/// the diacritic.
70///
71/// This should likely be some ICU library function, but I'm not sure which one.
72fn remove_combination(c: u32) -> u32 {
73    match c {
74        GRAVE => '`' as u32,
75        ACUTE => '\'' as u32,
76        CIRCUMFLEX => '^' as u32,
77        TILDE => '~' as u32,
78        _ => c,
79    }
80}
81
82/// StoredEvent is an InputEvent which is known to be a keyboard event.
83#[derive(Debug, Clone)]
84struct StoredEvent {
85    event: KeyboardEvent,
86    device_descriptor: InputDeviceDescriptor,
87    event_time: zx::MonotonicInstant,
88    trace_id: Option<fuchsia_trace::Id>,
89}
90
91impl fmt::Display for StoredEvent {
92    // Implement a compact [Display], as the device descriptor is not
93    // normally very interesting to see.
94    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
95        write!(f, "event: {:?}, event_time: {:?}", &self.event, &self.event_time)
96    }
97}
98
99impl Into<InputEvent> for StoredEvent {
100    /// Converts [StoredEvent] into [InputEvent].
101    fn into(self) -> InputEvent {
102        InputEvent {
103            device_event: InputDeviceEvent::Keyboard(self.event),
104            device_descriptor: self.device_descriptor,
105            event_time: self.event_time,
106            handled: Handled::No,
107            trace_id: self.trace_id,
108        }
109    }
110}
111
112impl Into<Vec<InputEvent>> for StoredEvent {
113    fn into(self) -> Vec<InputEvent> {
114        vec![self.into()]
115    }
116}
117
118/// Whether a [StoredEvent] corresponds to a live key or a dead key.
119enum Liveness {
120    /// The key is dead.
121    Dead,
122    /// The key is live.
123    Live,
124}
125
126/// Whether two events are the same or different by key.
127enum Sameness {
128    /// Two events are the same by key.
129    Same,
130    /// Two events are different.
131    Other,
132}
133
134impl StoredEvent {
135    /// Repackages self into a new [StoredEvent], with `event` replaced as supplied.
136    fn into_with_event(self, event: KeyboardEvent) -> Self {
137        StoredEvent {
138            event,
139            device_descriptor: self.device_descriptor,
140            event_time: self.event_time,
141            trace_id: self.trace_id,
142        }
143    }
144
145    /// Returns the code point contained in this [StoredEvent].
146    fn code_point(&self) -> u32 {
147        match self.event.get_key_meaning() {
148            Some(KeyMeaning::Codepoint(c)) => c,
149            _ => panic!("programming error: requested code point for an event that has none"),
150        }
151    }
152
153    /// Modifies this [StoredEvent] to contain a new code point instead of whatever was there.
154    fn into_with_code_point(self, code_point: u32) -> Self {
155        let new_event =
156            self.event.clone().into_with_key_meaning(Some(KeyMeaning::Codepoint(code_point)));
157        self.into_with_event(new_event)
158    }
159
160    /// Returns true if [StoredEvent] contains a valid code point.
161    fn is_code_point(&self) -> bool {
162        match self.event.get_key_meaning() {
163            // Some nonprintable keys have the code point value set to 0.
164            Some(KeyMeaning::Codepoint(c)) => c != 0,
165            _ => false,
166        }
167    }
168
169    /// Returns whether the key is a dead key or not.  The return value is an enum
170    /// to make the state machine match arms more readable.
171    fn key_liveness(&self) -> Liveness {
172        match self.event.get_key_meaning() {
173            Some(KeyMeaning::Codepoint(c)) if is_dead_key(c) => Liveness::Dead,
174            _ => Liveness::Live,
175        }
176    }
177
178    /// Returns the key event type (pressed, released, or something else)
179    fn e_type(&self) -> KeyEventType {
180        self.event.get_event_type_folded()
181    }
182
183    /// Returns a new [StoredEvent] based on `Self`, but with the combining effect removed.
184    fn into_base_character(self) -> Self {
185        let key_meaning = self.event.get_key_meaning();
186        match key_meaning {
187            Some(KeyMeaning::Codepoint(c)) => {
188                let new_event = self
189                    .event
190                    .clone()
191                    .into_with_key_meaning(Some(KeyMeaning::Codepoint(remove_combination(c))));
192                self.into_with_event(new_event)
193            }
194            _ => self,
195        }
196    }
197
198    /// Returns a new [StoredEvent], but with key meaning removed.
199    fn remove_key_meaning(self) -> Self {
200        let mut event = self.event.clone();
201        // A zero code point means a KeyEvent for which its edit effect should
202        // be ignored. In contrast, an event with an unset code point has by
203        // definition the same effect as if the US QWERTY keymap were applied.
204        // See discussion at:
205        // https://groups.google.com/a/fuchsia.dev/g/ui-input-dev/c/ITYKvbJS6_o/m/8kK0DRccDAAJ
206        event = event.into_with_key_meaning(Some(KeyMeaning::Codepoint(0)));
207        self.into_with_event(event)
208    }
209
210    /// Returns whether the two keys `this` and `that` are in fact the same key
211    /// as per the USB HID usage reported.  The return value is an enum to make
212    /// the state machine match arms more readable.
213    fn key_sameness(this: &StoredEvent, that: &StoredEvent) -> Sameness {
214        match this.event.get_key() == that.event.get_key() {
215            true => Sameness::Same,
216            false => Sameness::Other,
217        }
218    }
219}
220
221#[allow(clippy::large_enum_variant)] // TODO(https://fxbug.dev/401086995)
222/// State contains the current observed state of the dead key state machine.
223///
224/// The dead key composition is started by observing a key press that amounts
225/// to a dead key.  The first non-dead key that gets actuated thereafter becomes
226/// the "live" key that we will attempt to add a diacritic to.  When such a live
227/// key is actuated, we will emit a key meaning equivalent to producing an
228/// accented character.
229///
230/// A complication here is that composition can unfold in any number of ways.
231/// The user could press and release the dead key, then press and release
232/// the live key.  The user could, also, press and hold the dead key, then
233/// press any number of live or dead keys in an arbitrary order.
234///
235/// Another complication is that the user could press the dead key twice, which
236/// should also be handled correctly. In this case, "correct" handling implies
237/// emitting the dead key as an accented character.  Similarly, two different
238/// dead keys pressed in succession are handled by (1) emitting the first as
239/// an accented character, and restarting composition with the second. It is
240/// worth noting that the key press and key release events could be arbitrarily
241/// interleaved for the two dead keys, and that should be handled correctly too.
242///
243/// A third complication is that, while all the composition is taking place,
244/// the pipeline must emit the `KeyEvent`s consistent with the key event protocol,
245/// but keep key meanings suppressed until the time that the key meanings have
246/// been resolved by the combination.
247///
248/// The elements of state are as follows:
249///
250///   * Did we see a dead key press event? (bit `a`)
251///   * Did we see a dead key release event? (bit `b`)
252///   * Did we see a live key press event? (bit `c`)
253///   * Did we see a live key release event? (bit `d`)
254///
255/// Almost any variation of the above elements is possible and allowed.  Even
256/// the states that ostensibly shouldn't be possible (e.g. observed a release
257/// event before a press) should be accounted for in order to implement
258/// self-correcting behavior if needed.  The [State] enum below encodes each
259/// state as a name `Sdcba`, where each of `a..d` are booleans, encoded
260/// as characters `0` and `1` as conventional. So for example, `S0101`
261/// is a state where we observed a dead key press event, and a live key press
262/// event.  I made an experiment where I tried to use more illustrative state
263/// names, but the number of variations didn't make the resulting names any more
264/// meaningful compared to the current state name encoding scheme. So compact
265/// naming it is.
266#[derive(Debug, Clone)]
267enum State {
268    /// We have yet to see a key to act on.
269    S0000,
270
271    /// We saw an actuation of a dead key.
272    S0001 { dead_key_down: StoredEvent },
273
274    /// A dead key was pressed and released.
275    S0011 { dead_key_down: StoredEvent, dead_key_up: StoredEvent },
276
277    /// A dead key was pressed and released, followed by a live key press.
278    S0111 { dead_key_down: StoredEvent, dead_key_up: StoredEvent, live_key_down: StoredEvent },
279
280    /// A dead key was pressed, followed by a live key press.
281    S0101 { dead_key_down: StoredEvent, live_key_down: StoredEvent },
282
283    /// A dead key was pressed, then a live key was pressed and released.
284    S1101 { dead_key_down: StoredEvent },
285}
286
287#[derive(Debug)]
288pub struct DeadKeysHandler {
289    /// Tracks the current state of the dead key composition.
290    state: RefCell<State>,
291
292    /// The unicode normalizer used for composition.
293    normalizer: unorm::UNormalizer,
294
295    /// This handler requires ICU data to be live. This is ensured by holding
296    /// a reference to an ICU data loader.
297    _data: icu_data::Loader,
298
299    /// The inventory of this handler's Inspect status.
300    pub inspect_status: InputHandlerStatus,
301}
302
303/// This trait implementation allows the [Handler] to be hooked up into the input
304/// pipeline.
305#[async_trait(?Send)]
306impl UnhandledInputHandler for DeadKeysHandler {
307    async fn handle_unhandled_input_event(
308        self: Rc<Self>,
309        unhandled_input_event: UnhandledInputEvent,
310    ) -> Vec<InputEvent> {
311        self.handle_unhandled_input_event_internal(unhandled_input_event)
312    }
313
314    fn set_handler_healthy(self: std::rc::Rc<Self>) {
315        self.inspect_status.health_node.borrow_mut().set_ok();
316    }
317
318    fn set_handler_unhealthy(self: std::rc::Rc<Self>, msg: &str) {
319        self.inspect_status.health_node.borrow_mut().set_unhealthy(msg);
320    }
321}
322
323impl DeadKeysHandler {
324    /// Creates a new instance of the dead keys handler.
325    pub fn new(
326        icu_data: icu_data::Loader,
327        input_handlers_node: &fuchsia_inspect::Node,
328    ) -> Rc<Self> {
329        let inspect_status = InputHandlerStatus::new(
330            input_handlers_node,
331            "dead_keys_handler",
332            /* generates_events */ false,
333        );
334        let handler = DeadKeysHandler {
335            state: RefCell::new(State::S0000),
336            // The NFC normalizer performs the needed composition and is not
337            // lossy.
338            normalizer: unorm::UNormalizer::new_nfc().unwrap(),
339            _data: icu_data,
340            inspect_status,
341        };
342        Rc::new(handler)
343    }
344
345    fn handle_unhandled_input_event_internal(
346        self: Rc<Self>,
347        unhandled_input_event: UnhandledInputEvent,
348    ) -> Vec<InputEvent> {
349        match unhandled_input_event.clone() {
350            UnhandledInputEvent {
351                device_event: InputDeviceEvent::Keyboard(event),
352                device_descriptor,
353                event_time,
354                trace_id,
355            } => {
356                fuchsia_trace::duration!(c"input", c"dead_keys_handler");
357                if let Some(trace_id) = trace_id {
358                    fuchsia_trace::flow_step!(
359                        c"input",
360                        c"event_in_input_pipeline",
361                        trace_id.into()
362                    );
363                }
364
365                self.inspect_status.count_received_event(InputEvent::from(unhandled_input_event));
366                let event = StoredEvent { event, device_descriptor, event_time, trace_id };
367                // Separated into two statements to ensure the logs are not truncated.
368                log::debug!("state: {:?}", self.state.borrow());
369                log::debug!("event: {}", &event);
370                let result = self.process_keyboard_event(event);
371                log::debug!("result: {:?}", &result);
372                result
373            }
374
375            // Pass other events unchanged.
376            _ => vec![InputEvent::from(unhandled_input_event)],
377        }
378    }
379
380    /// Sets the internal handler state to `new_state`.
381    fn set_state(self: &Rc<Self>, new_state: State) {
382        *(self.state.borrow_mut()) = new_state;
383    }
384
385    /// Attaches a key meaning to each passing keyboard event.
386    ///
387    /// Underlying this function is a state machine which registers the flow of dead and live keys
388    /// after each reported event, and modifies the input event stream accordingly.  For example,
389    /// a sequence of events where a dead key is pressed and released, followed by a live key
390    /// press and release, results in a composed character being emitted.  The state machine
391    /// takese care of this sequence, but also of other less obvious sequences and their effects.
392    fn process_keyboard_event(self: &Rc<Self>, event: StoredEvent) -> Vec<InputEvent> {
393        if !event.is_code_point() {
394            // Pass through any non-codepoint events.
395            return event.into();
396        }
397        let old_state = self.state.borrow().clone();
398        match old_state {
399            // We are waiting for the composition to begin.
400            State::S0000 => match (event.key_liveness(), event.e_type()) {
401                // A dead key press starts composition.  We advance to the next
402                // state machine state, and eliminate any key meaning from the
403                // key event, since we anticipate its use in composition.
404                (Liveness::Dead, KeyEventType::Pressed) => {
405                    self.set_state(State::S0001 { dead_key_down: event.clone() });
406                    event.remove_key_meaning().into()
407                }
408
409                // A dead key release while we're waiting for a dead key press,
410                // this is probably a remnant of an earlier double press, remove the
411                // combining from it and forward.  Keep waiting for composition
412                // to begin.
413                (Liveness::Dead, KeyEventType::Released) => event.into_base_character().into(),
414
415                // Any other events can be forwarded unmodified.
416                _ => event.into(),
417            },
418
419            // We have seen a dead key press, but not release.
420            State::S0001 { dead_key_down } => {
421                match (
422                    event.key_liveness(),
423                    StoredEvent::key_sameness(&event, &dead_key_down),
424                    event.e_type(),
425                ) {
426                    // The same dead key that was pressed the other time was released.
427                    // Emit a stripped version, and start waiting for a live key.
428                    (Liveness::Dead, Sameness::Same, KeyEventType::Released) => {
429                        self.set_state(State::S0011 { dead_key_down, dead_key_up: event.clone() });
430                        event.remove_key_meaning().into()
431                    }
432
433                    // Another dead key was released at this point.  Since
434                    // we can not start a new combination here, we must forward
435                    // it with meaning stripped.
436                    (Liveness::Dead, Sameness::Other, KeyEventType::Released) => {
437                        event.remove_key_meaning().into()
438                    }
439
440                    // The same dead key was pressed again, while we have seen
441                    // it pressed before.  This can happen when autorepeat kicks
442                    // in.  We treat this the same as two successive actuations
443                    // i.e. we send a stripped version of the character, and
444                    // go back to waiting.
445                    (Liveness::Dead, Sameness::Same, KeyEventType::Pressed) => {
446                        self.set_state(State::S0000);
447                        event.into_base_character().into()
448                    }
449
450                    // A different dead key was pressed.  This stops the ongoing
451                    // composition, and starts a new one with a new dead key.  However,
452                    // what we emit is a bit subtle: we emit a key press event
453                    // for the *new* key, but with a key meaning of the stripped
454                    // version of the current key.
455                    (Liveness::Dead, Sameness::Other, KeyEventType::Pressed) => {
456                        let current_removed = dead_key_down.clone().into_base_character();
457                        self.set_state(State::S0001 { dead_key_down: event.clone() });
458                        event.into_with_code_point(current_removed.code_point()).into()
459                    }
460
461                    // A live key was pressed while the dead key is held down. Yay!
462                    //
463                    // Compose and ship out the live key with attached new meaning.
464                    //
465                    // A very similar piece of code happens in the state `State::S0011`,
466                    // except we get there through a different sequence of events.
467                    // Please refer to that code for the details about composition.
468                    (Liveness::Live, _, KeyEventType::Pressed) => {
469                        let maybe_composed = self.normalizer.compose_pair(
470                            event.code_point() as usys::UChar32,
471                            dead_key_down.code_point() as usys::UChar32,
472                        );
473
474                        if maybe_composed >= 0 {
475                            // Composition was a success.
476                            let composed_event = event.into_with_code_point(maybe_composed as u32);
477                            self.set_state(State::S0101 {
478                                dead_key_down,
479                                live_key_down: composed_event.clone(),
480                            });
481                            return composed_event.into();
482                        } else {
483                            // FAIL!
484                            self.set_state(State::S0101 {
485                                dead_key_down,
486                                live_key_down: event.clone(),
487                            });
488                            return event.into();
489                        }
490                    }
491                    // All other key events are forwarded unmodified.
492                    _ => event.into(),
493                }
494            }
495
496            // The dead key was pressed and released, the first live key that
497            // gets pressed after that now will be used for the composition.
498            State::S0011 { dead_key_down, dead_key_up } => {
499                match (event.key_liveness(), event.e_type()) {
500                    // We observed a dead key actuation.
501                    (Liveness::Dead, KeyEventType::Pressed) => {
502                        match StoredEvent::key_sameness(&dead_key_down, &event) {
503                            // The user pressed the same dead key again.  Let's "compose" it by
504                            // stripping its diacritic and making that a compose key.
505                            Sameness::Same => {
506                                let event = event.into_base_character();
507                                self.set_state(State::S0111 {
508                                    dead_key_down,
509                                    dead_key_up,
510                                    live_key_down: event.clone(),
511                                });
512                                event.into()
513                            }
514                            // The user pressed a different dead key. It would have been nice
515                            // to start a new composition, but we can not express that with the
516                            // KeyEvent API, since that would require emitting spurious press and
517                            // release key events for the dead key press and release.
518                            //
519                            // Instead, forward the key unmodified and cancel
520                            // the composition.  We may revisit this if the KeyEvent API is
521                            // changed to allow decoupling key events from key meanings.
522                            Sameness::Other => {
523                                self.set_state(State::S0000);
524                                event.into_base_character().into()
525                            }
526                        }
527                    }
528
529                    // We observed a dead key release.  This is likely a dead key
530                    // from the *previous* composition attempt.  Nothing to do here,
531                    // except forward it stripped of key meaning.
532                    (Liveness::Dead, KeyEventType::Released) => event.remove_key_meaning().into(),
533
534                    // Oh, frabjous day! Someone pressed a live key that may be
535                    // possible to combine!  Let's try it out!  If composition is
536                    // a success, emit the current key with the meaning set to
537                    // the composed character.
538                    (Liveness::Live, KeyEventType::Pressed) => {
539                        let maybe_composed = self.normalizer.compose_pair(
540                            event.code_point() as usys::UChar32,
541                            dead_key_down.code_point() as usys::UChar32,
542                        );
543
544                        if maybe_composed >= 0 {
545                            // Composition was a success.
546                            // Emit the composed event, remember it also when
547                            // transitioning to S0111, so we can recover the key meaning
548                            // when the live key is released.
549                            let composed_event = event.into_with_code_point(maybe_composed as u32);
550                            self.set_state(State::S0111 {
551                                dead_key_down,
552                                dead_key_up,
553                                live_key_down: composed_event.clone(),
554                            });
555                            return composed_event.into();
556                        } else {
557                            log::debug!("compose failed for: {}\n", &event);
558                            // FAIL!
559                            // Composition failed, what now?  We would need to
560                            // emit TWO characters - one for the now-defunct
561                            // dead key, and another for the current live key.
562                            // But this is not possible, since we may not emit
563                            // more combining key events, but must always emit
564                            // both the key and the key meaning since that is
565                            // how our protocol works.  Well, we reached the
566                            // limit of what key event composition may do, so
567                            // let's simply agree to emit the current event
568                            // unmodified and forget we had the dead key.
569                            self.set_state(State::S0111 {
570                                dead_key_down,
571                                dead_key_up,
572                                live_key_down: event.clone(),
573                            });
574                            return event.into();
575                        }
576                    }
577
578                    // All other key events are forwarded unmodified.
579                    _ => event.into(),
580                }
581            }
582
583            // We already combined the live key with the dead key, and are
584            // now waiting for the live key to be released.
585            State::S0111 { dead_key_down, dead_key_up, live_key_down } => {
586                match (
587                    event.key_liveness(),
588                    // Here we compare the current key with the live key down,
589                    // unlike in prior states.
590                    StoredEvent::key_sameness(&event, &live_key_down),
591                    event.e_type(),
592                ) {
593                    // This is what we've been waiting for: the live key is now
594                    // lifted.  Emit the live key release using the same code point
595                    // as we used when the key went down, and we're done.
596                    (Liveness::Live, Sameness::Same, KeyEventType::Released) => {
597                        self.set_state(State::S0000);
598                        event.into_with_code_point(live_key_down.code_point()).into()
599                    }
600
601                    // A second press of the live key we're combining.  This is
602                    // probably a consequence of autorepeat.  The effect should
603                    // be to complete the composition and continue emitting the
604                    // "base" key meaning for any further repeats; but also
605                    // continue waiting for a key release.
606                    (Liveness::Live, Sameness::Same, KeyEventType::Pressed) => {
607                        let base_codepoint = event.code_point();
608                        let combined_event =
609                            event.clone().into_with_code_point(live_key_down.code_point());
610                        // We emit a combined key, but further repeats will use the
611                        // base code point and not combine.
612                        self.set_state(State::S0111 {
613                            dead_key_down,
614                            dead_key_up,
615                            live_key_down: event.into_with_code_point(base_codepoint),
616                        });
617                        combined_event.into()
618                    }
619
620                    // If another live key event comes in, just forward it, and
621                    // continue waiting for the last live key release.
622                    (Liveness::Live, Sameness::Other, _) => event.into(),
623
624                    // Another dead key has been pressed in addition to what
625                    // had been pressed before. So now, we are waiting for the
626                    // user to release the live key we already composed, but the
627                    // user is again pressing a compose key instead.
628                    //
629                    // Ideally, we'd want to start new composition with the
630                    // new dead key.  But, there's still the issue with the
631                    // live key that is still being pressed: when it is eventually
632                    // released, we want to have it have exactly the same key
633                    // meaning as what we emitted for when it was pressed.  But,
634                    // that may happen arbitrarily late afterwards, and we'd
635                    // prefer not to keep any composition state for that long.
636                    //
637                    // That suggests that we must not honor this new dead key
638                    // as composition.  But, also, we must not drop the key
639                    // event on the floor, since the clients that read key
640                    // events must receive it.  So, we just *turn* off
641                    // the combining effect on this key, forward it like that,
642                    // and continue waiting for the key release.
643                    (Liveness::Dead, _, KeyEventType::Pressed) => event.remove_key_meaning().into(),
644
645                    (Liveness::Dead, _, KeyEventType::Released) => {
646                        match StoredEvent::key_sameness(&event, &live_key_down) {
647                            // Special: if the released key a dead key and the same as the
648                            // "live" composing key, then we're seeing a release of a doubly-
649                            // pressed dead key.  This one needs to be emitted as a diacritic.
650                            Sameness::Same => {
651                                self.set_state(State::S0000);
652                                event.into_base_character().into()
653                            }
654
655                            // All other dead keys are forwarded with stripped key meanings.
656                            // We have no way to handle them further.
657                            Sameness::Other => event.remove_key_meaning().into(),
658                        }
659                    }
660
661                    // Forward any other events unmodified.
662                    _ => event.into(),
663                }
664            }
665
666            // The user pressed and is holding the dead key; and pressed and
667            // is holding a live key.
668            State::S0101 { dead_key_down, live_key_down } => {
669                match (event.key_liveness(), event.e_type()) {
670                    // The same dead key we're already holding is pressed.  Just forward
671                    // the key event, but not meaning.
672                    (Liveness::Dead, KeyEventType::Pressed) => event.remove_key_meaning().into(),
673
674                    (Liveness::Dead, KeyEventType::Released) => {
675                        // The dead key that we are using for combining is released.
676                        // Emit its release event without a key meaning and go to a
677                        // state that expects a release of the live key.
678                        match StoredEvent::key_sameness(&dead_key_down, &event) {
679                            Sameness::Same => {
680                                self.set_state(State::S0111 {
681                                    dead_key_down,
682                                    dead_key_up: event.clone(),
683                                    live_key_down,
684                                });
685                                event.remove_key_meaning().into()
686                            }
687
688                            // Other dead key is released.  Remove its key meaning, but forward.
689                            Sameness::Other => event.remove_key_meaning().into(),
690                        }
691                    }
692                    (Liveness::Live, KeyEventType::Pressed) => {
693                        match StoredEvent::key_sameness(&live_key_down, &event) {
694                            // The currently pressed live key is pressed again.
695                            // This is autorepeat.  We emit one composed key, but any
696                            // further emitted keys will not compose.  This
697                            // should be similar to `State::S0111`, except the
698                            // transition is back to *this* state.
699                            Sameness::Same => {
700                                let base_codepoint = event.code_point();
701                                let combined_event =
702                                    event.clone().into_with_code_point(live_key_down.code_point());
703                                self.set_state(State::S0101 {
704                                    dead_key_down,
705                                    live_key_down: event.into_with_code_point(base_codepoint),
706                                });
707                                combined_event.into()
708                            }
709                            Sameness::Other => event.into(),
710                        }
711                    }
712                    (Liveness::Live, KeyEventType::Released) => {
713                        match StoredEvent::key_sameness(&live_key_down, &event) {
714                            Sameness::Same => {
715                                self.set_state(State::S1101 { dead_key_down });
716                                event.into_with_code_point(live_key_down.code_point()).into()
717                            }
718
719                            // Any other release just gets forwarded.
720                            Sameness::Other => event.into(),
721                        }
722                    }
723
724                    // Forward any other events unmodified
725                    _ => event.into(),
726                }
727            }
728
729            // The dead key is still actuated, but we already sent out the
730            // combined versions of the live key.
731            State::S1101 { dead_key_down } => {
732                match (event.key_liveness(), event.e_type()) {
733                    (Liveness::Dead, KeyEventType::Pressed) => {
734                        // Two possible cases here, but the outcome is the
735                        // same:
736                        //
737                        // The same dead key is pressed again.  Let's not
738                        // do any more compositions here.
739                        //
740                        // A different dead key has been pressed.  We can
741                        // not start a new composition while we have not
742                        // closed out the current composition.  For this
743                        // reason we ignore the other key.
744                        //
745                        // A real compositioning API would perhaps allow us
746                        // to stack compositions on top of each other, but
747                        // we will require any such consumers to go talk to
748                        // the text editing API instead.
749                        event.remove_key_meaning().into()
750                    }
751
752                    (Liveness::Dead, KeyEventType::Released) => {
753                        match StoredEvent::key_sameness(&dead_key_down, &event) {
754                            // The dead key is released, the composition is
755                            // done, let's close up shop.
756                            Sameness::Same => {
757                                self.set_state(State::S0000);
758                                event.remove_key_meaning().into()
759                            }
760                            // A dead key was released, but not the one that we
761                            // are combining by.  Forward with the combining
762                            // effect stripped.
763                            Sameness::Other => event.remove_key_meaning().into(),
764                        }
765                    }
766
767                    // Any additional live keys, no matter if they are the same
768                    // as the one currently being composed, will *not* be composed,
769                    // we forward them unmodified as we wait to close off this
770                    // composition.
771                    //
772                    // Forward any other events unmodified.
773                    _ => event.into(),
774                }
775            }
776        }
777    }
778}
779
780#[cfg(test)]
781mod tests {
782    use super::*;
783    use crate::testing_utilities;
784    use fidl_fuchsia_input::Key;
785    use fidl_fuchsia_input_report::ConsumerControlButton;
786
787    use pretty_assertions::assert_eq;
788    use std::convert::TryFrom as _;
789
790    // Creates a new keyboard event for testing.
791    fn new_event(
792        key: Key,
793        event_type: KeyEventType,
794        key_meaning: Option<KeyMeaning>,
795    ) -> UnhandledInputEvent {
796        UnhandledInputEvent::try_from(testing_utilities::create_keyboard_event_with_handled(
797            key,
798            event_type,
799            /*modifiers=*/ None,
800            /*event_time*/ zx::MonotonicInstant::ZERO,
801            &InputDeviceDescriptor::Fake,
802            /*keymap=*/ None,
803            key_meaning,
804            /*handled=*/ Handled::No,
805        ))
806        .unwrap()
807    }
808
809    // Tests some common keyboard input use cases with dead keys actuation.
810    #[test]
811    fn test_input_processing() {
812        // A zero codepoint is a way to let the consumers know that this key
813        // event should have no effect on the edited text; even though its
814        // key event may have other effects, such as moving the hero across
815        // the screen in a game.
816        const ZERO_CP: Option<KeyMeaning> = Some(KeyMeaning::Codepoint(0));
817
818        #[derive(Debug)]
819        struct TestCase {
820            name: &'static str,
821            // The sequence of input events at the input of the dead keys
822            // handler.
823            inputs: Vec<UnhandledInputEvent>,
824            // The expected sequence of input events, after being transformed
825            // by the dead keys handler.
826            expected: Vec<UnhandledInputEvent>,
827        }
828        let tests: Vec<TestCase> = vec![
829            TestCase {
830                name: "passthrough",
831                inputs: vec![
832                    new_event(
833                        Key::A,
834                        KeyEventType::Pressed,
835                        Some(KeyMeaning::Codepoint('A' as u32)),
836                    ),
837                    new_event(
838                        Key::A,
839                        KeyEventType::Released,
840                        Some(KeyMeaning::Codepoint('A' as u32)),
841                    ),
842                ],
843                expected: vec![
844                    new_event(
845                        Key::A,
846                        KeyEventType::Pressed,
847                        Some(KeyMeaning::Codepoint('A' as u32)),
848                    ),
849                    new_event(
850                        Key::A,
851                        KeyEventType::Released,
852                        Some(KeyMeaning::Codepoint('A' as u32)),
853                    ),
854                ],
855            },
856            TestCase {
857                name: "A circumflex - dead key first, then live key",
858                inputs: vec![
859                    new_event(
860                        Key::Key5,
861                        KeyEventType::Pressed,
862                        Some(KeyMeaning::Codepoint(CIRCUMFLEX as u32)),
863                    ),
864                    new_event(
865                        Key::Key5,
866                        KeyEventType::Released,
867                        Some(KeyMeaning::Codepoint(CIRCUMFLEX as u32)),
868                    ),
869                    new_event(
870                        Key::A,
871                        KeyEventType::Pressed,
872                        Some(KeyMeaning::Codepoint('A' as u32)),
873                    ),
874                    new_event(
875                        Key::A,
876                        KeyEventType::Released,
877                        Some(KeyMeaning::Codepoint('A' as u32)),
878                    ),
879                ],
880                expected: vec![
881                    new_event(Key::Key5, KeyEventType::Pressed, ZERO_CP),
882                    new_event(Key::Key5, KeyEventType::Released, ZERO_CP),
883                    new_event(
884                        Key::A,
885                        KeyEventType::Pressed,
886                        Some(KeyMeaning::Codepoint('Â' as u32)),
887                    ),
888                    new_event(
889                        Key::A,
890                        KeyEventType::Released,
891                        Some(KeyMeaning::Codepoint('Â' as u32)),
892                    ),
893                ],
894            },
895            TestCase {
896                name: "A circumflex - dead key held all the way through composition",
897                inputs: vec![
898                    new_event(
899                        Key::Key5,
900                        KeyEventType::Pressed,
901                        Some(KeyMeaning::Codepoint(CIRCUMFLEX as u32)),
902                    ),
903                    new_event(
904                        Key::A,
905                        KeyEventType::Pressed,
906                        Some(KeyMeaning::Codepoint('A' as u32)),
907                    ),
908                    new_event(
909                        Key::A,
910                        KeyEventType::Released,
911                        Some(KeyMeaning::Codepoint('A' as u32)),
912                    ),
913                    new_event(
914                        Key::Key5,
915                        KeyEventType::Released,
916                        Some(KeyMeaning::Codepoint(CIRCUMFLEX as u32)),
917                    ),
918                ],
919                expected: vec![
920                    new_event(Key::Key5, KeyEventType::Pressed, ZERO_CP),
921                    new_event(
922                        Key::A,
923                        KeyEventType::Pressed,
924                        Some(KeyMeaning::Codepoint('Â' as u32)),
925                    ),
926                    new_event(
927                        Key::A,
928                        KeyEventType::Released,
929                        Some(KeyMeaning::Codepoint('Â' as u32)),
930                    ),
931                    new_event(Key::Key5, KeyEventType::Released, ZERO_CP),
932                ],
933            },
934            TestCase {
935                name: "A circumflex - dead key held until the live key was down",
936                inputs: vec![
937                    new_event(
938                        Key::Key5,
939                        KeyEventType::Pressed,
940                        Some(KeyMeaning::Codepoint(CIRCUMFLEX as u32)),
941                    ),
942                    new_event(
943                        Key::A,
944                        KeyEventType::Pressed,
945                        Some(KeyMeaning::Codepoint('A' as u32)),
946                    ),
947                    new_event(
948                        Key::Key5,
949                        KeyEventType::Released,
950                        Some(KeyMeaning::Codepoint(CIRCUMFLEX as u32)),
951                    ),
952                    new_event(
953                        Key::A,
954                        KeyEventType::Released,
955                        Some(KeyMeaning::Codepoint('A' as u32)),
956                    ),
957                ],
958                expected: vec![
959                    new_event(Key::Key5, KeyEventType::Pressed, ZERO_CP),
960                    new_event(
961                        Key::A,
962                        KeyEventType::Pressed,
963                        Some(KeyMeaning::Codepoint('Â' as u32)),
964                    ),
965                    new_event(Key::Key5, KeyEventType::Released, ZERO_CP),
966                    new_event(
967                        Key::A,
968                        KeyEventType::Released,
969                        Some(KeyMeaning::Codepoint('Â' as u32)),
970                    ),
971                ],
972            },
973            TestCase {
974                name: "Combining character pressed twice - results in a single diacritic",
975                inputs: vec![
976                    new_event(
977                        Key::Key5,
978                        KeyEventType::Pressed,
979                        Some(KeyMeaning::Codepoint(CIRCUMFLEX as u32)),
980                    ),
981                    new_event(
982                        Key::Key5,
983                        KeyEventType::Released,
984                        Some(KeyMeaning::Codepoint(CIRCUMFLEX as u32)),
985                    ),
986                    new_event(
987                        Key::Key5,
988                        KeyEventType::Pressed,
989                        Some(KeyMeaning::Codepoint(CIRCUMFLEX as u32)),
990                    ),
991                    new_event(
992                        Key::Key5,
993                        KeyEventType::Released,
994                        Some(KeyMeaning::Codepoint(CIRCUMFLEX as u32)),
995                    ),
996                ],
997                expected: vec![
998                    new_event(Key::Key5, KeyEventType::Pressed, ZERO_CP),
999                    new_event(Key::Key5, KeyEventType::Released, ZERO_CP),
1000                    new_event(
1001                        Key::Key5,
1002                        KeyEventType::Pressed,
1003                        Some(KeyMeaning::Codepoint('^' as u32)),
1004                    ),
1005                    new_event(
1006                        Key::Key5,
1007                        KeyEventType::Released,
1008                        Some(KeyMeaning::Codepoint('^' as u32)),
1009                    ),
1010                ],
1011            },
1012            TestCase {
1013                name: "A circumflex - dead key spans live key",
1014                inputs: vec![
1015                    new_event(
1016                        Key::Key5,
1017                        KeyEventType::Pressed,
1018                        Some(KeyMeaning::Codepoint(CIRCUMFLEX as u32)),
1019                    ),
1020                    new_event(
1021                        Key::A,
1022                        KeyEventType::Pressed,
1023                        Some(KeyMeaning::Codepoint('A' as u32)),
1024                    ),
1025                    new_event(
1026                        Key::A,
1027                        KeyEventType::Released,
1028                        Some(KeyMeaning::Codepoint('A' as u32)),
1029                    ),
1030                    new_event(
1031                        Key::Key5,
1032                        KeyEventType::Released,
1033                        Some(KeyMeaning::Codepoint(CIRCUMFLEX as u32)),
1034                    ),
1035                ],
1036                expected: vec![
1037                    new_event(Key::Key5, KeyEventType::Pressed, ZERO_CP),
1038                    new_event(
1039                        Key::A,
1040                        KeyEventType::Pressed,
1041                        Some(KeyMeaning::Codepoint('Â' as u32)),
1042                    ),
1043                    new_event(
1044                        Key::A,
1045                        KeyEventType::Released,
1046                        Some(KeyMeaning::Codepoint('Â' as u32)),
1047                    ),
1048                    new_event(Key::Key5, KeyEventType::Released, ZERO_CP),
1049                ],
1050            },
1051            TestCase {
1052                name: "Only the first key after the dead key actuation is composed",
1053                inputs: vec![
1054                    new_event(
1055                        Key::Key5,
1056                        KeyEventType::Pressed,
1057                        Some(KeyMeaning::Codepoint(CIRCUMFLEX as u32)),
1058                    ),
1059                    new_event(
1060                        Key::Key5,
1061                        KeyEventType::Released,
1062                        Some(KeyMeaning::Codepoint(CIRCUMFLEX as u32)),
1063                    ),
1064                    new_event(
1065                        Key::A,
1066                        KeyEventType::Pressed,
1067                        Some(KeyMeaning::Codepoint('A' as u32)),
1068                    ),
1069                    new_event(
1070                        Key::E,
1071                        KeyEventType::Pressed,
1072                        Some(KeyMeaning::Codepoint('E' as u32)),
1073                    ),
1074                    new_event(
1075                        Key::A,
1076                        KeyEventType::Released,
1077                        Some(KeyMeaning::Codepoint('A' as u32)),
1078                    ),
1079                    new_event(
1080                        Key::E,
1081                        KeyEventType::Released,
1082                        Some(KeyMeaning::Codepoint('E' as u32)),
1083                    ),
1084                ],
1085                expected: vec![
1086                    new_event(Key::Key5, KeyEventType::Pressed, ZERO_CP),
1087                    new_event(Key::Key5, KeyEventType::Released, ZERO_CP),
1088                    new_event(
1089                        Key::A,
1090                        KeyEventType::Pressed,
1091                        Some(KeyMeaning::Codepoint('Â' as u32)),
1092                    ),
1093                    new_event(
1094                        Key::E,
1095                        KeyEventType::Pressed,
1096                        Some(KeyMeaning::Codepoint('E' as u32)),
1097                    ),
1098                    new_event(
1099                        Key::A,
1100                        KeyEventType::Released,
1101                        Some(KeyMeaning::Codepoint('Â' as u32)),
1102                    ),
1103                    new_event(
1104                        Key::E,
1105                        KeyEventType::Released,
1106                        Some(KeyMeaning::Codepoint('E' as u32)),
1107                    ),
1108                ],
1109            },
1110            TestCase {
1111                name: "Modifier keys are not affected",
1112                inputs: vec![
1113                    new_event(
1114                        Key::Key5,
1115                        KeyEventType::Pressed,
1116                        Some(KeyMeaning::Codepoint(CIRCUMFLEX as u32)),
1117                    ),
1118                    new_event(
1119                        Key::Key5,
1120                        KeyEventType::Released,
1121                        Some(KeyMeaning::Codepoint(CIRCUMFLEX as u32)),
1122                    ),
1123                    new_event(Key::LeftShift, KeyEventType::Pressed, ZERO_CP),
1124                    new_event(
1125                        Key::A,
1126                        KeyEventType::Pressed,
1127                        Some(KeyMeaning::Codepoint('A' as u32)),
1128                    ),
1129                    new_event(
1130                        Key::A,
1131                        KeyEventType::Released,
1132                        Some(KeyMeaning::Codepoint('A' as u32)),
1133                    ),
1134                    new_event(Key::LeftShift, KeyEventType::Released, ZERO_CP),
1135                ],
1136                expected: vec![
1137                    new_event(Key::Key5, KeyEventType::Pressed, ZERO_CP),
1138                    new_event(Key::Key5, KeyEventType::Released, ZERO_CP),
1139                    new_event(Key::LeftShift, KeyEventType::Pressed, ZERO_CP),
1140                    new_event(
1141                        Key::A,
1142                        KeyEventType::Pressed,
1143                        Some(KeyMeaning::Codepoint('Â' as u32)),
1144                    ),
1145                    new_event(
1146                        Key::A,
1147                        KeyEventType::Released,
1148                        Some(KeyMeaning::Codepoint('Â' as u32)),
1149                    ),
1150                    new_event(Key::LeftShift, KeyEventType::Released, ZERO_CP),
1151                ],
1152            },
1153            TestCase {
1154                name: "Two dead keys in succession - no compose",
1155                inputs: vec![
1156                    new_event(
1157                        Key::Key5,
1158                        KeyEventType::Pressed,
1159                        Some(KeyMeaning::Codepoint(CIRCUMFLEX as u32)),
1160                    ),
1161                    new_event(
1162                        Key::Key5,
1163                        KeyEventType::Released,
1164                        Some(KeyMeaning::Codepoint(CIRCUMFLEX as u32)),
1165                    ),
1166                    new_event(
1167                        Key::A,
1168                        KeyEventType::Pressed,
1169                        Some(KeyMeaning::Codepoint(GRAVE as u32)),
1170                    ),
1171                    new_event(
1172                        Key::A,
1173                        KeyEventType::Released,
1174                        Some(KeyMeaning::Codepoint(GRAVE as u32)),
1175                    ),
1176                ],
1177                expected: vec![
1178                    new_event(Key::Key5, KeyEventType::Pressed, ZERO_CP),
1179                    new_event(Key::Key5, KeyEventType::Released, ZERO_CP),
1180                    new_event(
1181                        Key::A,
1182                        KeyEventType::Pressed,
1183                        Some(KeyMeaning::Codepoint('`' as u32)),
1184                    ),
1185                    new_event(
1186                        Key::A,
1187                        KeyEventType::Released,
1188                        Some(KeyMeaning::Codepoint('`' as u32)),
1189                    ),
1190                ],
1191            },
1192            TestCase {
1193                name: "Compose with capital letter",
1194                inputs: vec![
1195                    new_event(
1196                        Key::Key5,
1197                        KeyEventType::Pressed,
1198                        Some(KeyMeaning::Codepoint(CIRCUMFLEX as u32)),
1199                    ),
1200                    new_event(
1201                        Key::Key5,
1202                        KeyEventType::Released,
1203                        Some(KeyMeaning::Codepoint(CIRCUMFLEX as u32)),
1204                    ),
1205                    new_event(
1206                        Key::LeftShift,
1207                        KeyEventType::Pressed,
1208                        Some(KeyMeaning::Codepoint(0)),
1209                    ),
1210                    new_event(
1211                        Key::A,
1212                        KeyEventType::Pressed,
1213                        Some(KeyMeaning::Codepoint('A' as u32)),
1214                    ),
1215                    new_event(
1216                        Key::A,
1217                        KeyEventType::Released,
1218                        Some(KeyMeaning::Codepoint('A' as u32)),
1219                    ),
1220                    new_event(
1221                        Key::LeftShift,
1222                        KeyEventType::Released,
1223                        Some(KeyMeaning::Codepoint(0)),
1224                    ),
1225                ],
1226                expected: vec![
1227                    new_event(Key::Key5, KeyEventType::Pressed, ZERO_CP),
1228                    new_event(Key::Key5, KeyEventType::Released, ZERO_CP),
1229                    new_event(
1230                        Key::LeftShift,
1231                        KeyEventType::Pressed,
1232                        Some(KeyMeaning::Codepoint(0)),
1233                    ),
1234                    new_event(
1235                        Key::A,
1236                        KeyEventType::Pressed,
1237                        Some(KeyMeaning::Codepoint('Â' as u32)),
1238                    ),
1239                    new_event(
1240                        Key::A,
1241                        KeyEventType::Released,
1242                        Some(KeyMeaning::Codepoint('Â' as u32)),
1243                    ),
1244                    new_event(
1245                        Key::LeftShift,
1246                        KeyEventType::Released,
1247                        Some(KeyMeaning::Codepoint(0)),
1248                    ),
1249                ],
1250            },
1251        ];
1252        let inspector = fuchsia_inspect::Inspector::default();
1253        let test_node = inspector.root().create_child("test_node");
1254        let loader = icu_data::Loader::new().unwrap();
1255        let handler = super::DeadKeysHandler::new(loader, &test_node);
1256        for test in tests {
1257            let actuals: Vec<InputEvent> = test
1258                .inputs
1259                .into_iter()
1260                .map(|event| handler.clone().handle_unhandled_input_event_internal(event))
1261                .flatten()
1262                .collect();
1263            assert_eq!(
1264                test.expected.into_iter().map(InputEvent::from).collect::<Vec<_>>(),
1265                actuals,
1266                "in test: {}",
1267                test.name
1268            );
1269        }
1270    }
1271
1272    #[test]
1273    fn dead_keys_handler_initialized_with_inspect_node() {
1274        let loader = icu_data::Loader::new().unwrap();
1275        let inspector = fuchsia_inspect::Inspector::default();
1276        let fake_handlers_node = inspector.root().create_child("input_handlers_node");
1277        let _handler = DeadKeysHandler::new(loader, &fake_handlers_node);
1278        diagnostics_assertions::assert_data_tree!(inspector, root: {
1279            input_handlers_node: {
1280                dead_keys_handler: {
1281                    events_received_count: 0u64,
1282                    events_handled_count: 0u64,
1283                    last_received_timestamp_ns: 0u64,
1284                    "fuchsia.inspect.Health": {
1285                        status: "STARTING_UP",
1286                        // Timestamp value is unpredictable and not relevant in this context,
1287                        // so we only assert that the property is present.
1288                        start_timestamp_nanos: diagnostics_assertions::AnyProperty
1289                    },
1290                }
1291            }
1292        });
1293    }
1294
1295    #[test]
1296    fn dead_keys_handler_inspect_counts_events() {
1297        let loader = icu_data::Loader::new().unwrap();
1298        let inspector = fuchsia_inspect::Inspector::default();
1299        let fake_handlers_node = inspector.root().create_child("input_handlers_node");
1300        let handler = DeadKeysHandler::new(loader, &fake_handlers_node);
1301
1302        // Inspect should count unhandled key events and ignore irrelevent InputEvent types.
1303        let events = vec![
1304            new_event(Key::A, KeyEventType::Pressed, Some(KeyMeaning::Codepoint('A' as u32))),
1305            UnhandledInputEvent::try_from(testing_utilities::create_consumer_controls_event(
1306                vec![ConsumerControlButton::VolumeUp],
1307                zx::MonotonicInstant::ZERO,
1308                &testing_utilities::consumer_controls_device_descriptor(),
1309            ))
1310            .unwrap(),
1311            new_event(Key::A, KeyEventType::Released, Some(KeyMeaning::Codepoint('A' as u32))),
1312        ];
1313        let _res: Vec<InputEvent> = events
1314            .into_iter()
1315            .map(|event| handler.clone().handle_unhandled_input_event_internal(event))
1316            .flatten()
1317            .collect();
1318        diagnostics_assertions::assert_data_tree!(inspector, root: {
1319            input_handlers_node: {
1320                dead_keys_handler: {
1321                    events_received_count: 2u64,
1322                    events_handled_count: 0u64,
1323                    last_received_timestamp_ns: 0u64,
1324                    "fuchsia.inspect.Health": {
1325                        status: "STARTING_UP",
1326                        // Timestamp value is unpredictable and not relevant in this context,
1327                        // so we only assert that the property is present.
1328                        start_timestamp_nanos: diagnostics_assertions::AnyProperty
1329                    },
1330                }
1331            }
1332        });
1333    }
1334}