accesskit_unix/atspi/
object_id.rs

1// Copyright 2022 The AccessKit Authors. All rights reserved.
2// Licensed under the Apache License, Version 2.0 (found in
3// the LICENSE-APACHE file) or the MIT license (found in
4// the LICENSE-MIT file), at your option.
5
6use crate::atspi::OwnedObjectAddress;
7use accesskit_atspi_common::{NodeId, PlatformNode};
8use serde::{Serialize, Serializer};
9use zbus::{
10    names::UniqueName,
11    zvariant::{ObjectPath, OwnedObjectPath, Signature, Structure, Type},
12};
13
14const ACCESSIBLE_PATH_PREFIX: &str = "/org/a11y/atspi/accessible/";
15const ROOT_PATH: &str = "/org/a11y/atspi/accessible/root";
16
17#[derive(Debug, PartialEq)]
18pub(crate) enum ObjectId {
19    Root,
20    Node { adapter: usize, node: NodeId },
21}
22
23impl ObjectId {
24    pub(crate) fn to_address(&self, bus_name: &UniqueName) -> OwnedObjectAddress {
25        OwnedObjectAddress::new(bus_name, self.path())
26    }
27
28    pub(crate) fn path(&self) -> OwnedObjectPath {
29        match self {
30            Self::Root => ObjectPath::from_str_unchecked(ROOT_PATH),
31            Self::Node { adapter, node } => ObjectPath::from_string_unchecked(format!(
32                "{}{}/{}",
33                ACCESSIBLE_PATH_PREFIX,
34                adapter,
35                u128::from(*node)
36            )),
37        }
38        .into()
39    }
40}
41
42impl Serialize for ObjectId {
43    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
44    where
45        S: Serializer,
46    {
47        match self {
48            Self::Root => serializer.serialize_str("root"),
49            Self::Node { node, .. } => serializer.serialize_str(&u128::from(*node).to_string()),
50        }
51    }
52}
53
54impl Type for ObjectId {
55    const SIGNATURE: &'static Signature = <&str>::SIGNATURE;
56}
57
58impl From<ObjectId> for Structure<'_> {
59    fn from(id: ObjectId) -> Self {
60        Self::from((match id {
61            ObjectId::Root => "root".into(),
62            ObjectId::Node { node, .. } => u128::from(node).to_string(),
63        },))
64    }
65}
66
67impl From<&PlatformNode> for ObjectId {
68    fn from(node: &PlatformNode) -> Self {
69        Self::Node {
70            adapter: node.adapter_id(),
71            node: node.id(),
72        }
73    }
74}